Exemplo n.º 1
0
        protected override void LeaveRegion()
        {
            foreach (var pending in PendingBranches)
            {
                if (pending.Branch == null || !RegionContains(pending.Branch.Syntax.Span))
                {
                    continue;
                }
                switch (pending.Branch.Kind)
                {
                case BoundKind.GotoStatement:
                    if (_labelsInside.Contains(((BoundGotoStatement)pending.Branch).Label))
                    {
                        continue;
                    }
                    break;

                case BoundKind.BreakStatement:
                    if (_labelsInside.Contains(((BoundBreakStatement)pending.Branch).Label))
                    {
                        continue;
                    }
                    break;

                case BoundKind.ContinueStatement:
                    if (_labelsInside.Contains(((BoundContinueStatement)pending.Branch).Label))
                    {
                        continue;
                    }
                    break;

                case BoundKind.YieldBreakStatement:
                case BoundKind.ReturnStatement:
                    // Return statements are included
                    break;

                case BoundKind.YieldReturnStatement:
                case BoundKind.AwaitExpression:
                case BoundKind.UsingStatement:
                case BoundKind.ForEachStatement
                    when((BoundForEachStatement)pending.Branch).AwaitOpt != null:
                    // We don't do anything with yield return statements, async using statement, async foreach statement, or await expressions;
                    // they are treated as if they are not jumps.
                    continue;

                default:
                    throw ExceptionUtilities.UnexpectedValue(pending.Branch.Kind);
                }
                _branchesOutOf.Add((StatementSyntax)pending.Branch.Syntax);
            }

            base.LeaveRegion();
        }
Exemplo n.º 2
0
        override protected void LeaveRegion()
        {
            foreach (var pending in PendingBranches)
            {
                if (pending.Branch == null || !RegionContains(pending.Branch.Syntax.Span))
                {
                    continue;
                }
                switch (pending.Branch.Kind)
                {
                case BoundKind.GotoStatement:
                    if (labelsInside.Contains(((pending.Branch) as BoundGotoStatement).Label))
                    {
                        continue;
                    }
                    break;

                case BoundKind.BreakStatement:
                    if (labelsInside.Contains(((pending.Branch) as BoundBreakStatement).Label))
                    {
                        continue;
                    }
                    break;

                case BoundKind.ContinueStatement:
                    if (labelsInside.Contains(((pending.Branch) as BoundContinueStatement).Label))
                    {
                        continue;
                    }
                    break;

                case BoundKind.YieldBreakStatement:
                case BoundKind.ReturnStatement:
                    // Return statements are included
                    break;

                case BoundKind.YieldReturnStatement:
                case BoundKind.AwaitExpression:
                    // We don't do anything with yield return statements or await expressions; they are treated as if they are not jumps.
                    continue;

                default:
                    Debug.Assert(false);     // there are no other branch statements
                    break;
                }
                branchesOutOf.Add((StatementSyntax)pending.Branch.Syntax);
            }

            base.LeaveRegion();
        }
Exemplo n.º 3
0
 private static void AddInterface(ArrayBuilder <NamedTypeSymbol> builder, NamedTypeSymbol @interface)
 {
     if (!builder.Contains(@interface))
     {
         builder.Add(@interface);
     }
 }
Exemplo n.º 4
0
 private static void AddNonIncluded(ArrayBuilder<string> builder, string item)
 {
     if (!builder.Contains(item))
     {
         builder.Add(item);
     }
 }
        private static void GetInstantiatedConstraintsRecursive(InstantiationContext typeContext, TypeDesc type, ref ArrayBuilder <TypeDesc> instantiatedConstraints)
        {
            if (!type.IsGenericParameter || typeContext == null)
            {
                return;
            }

            GenericParameterDesc genericParam = (GenericParameterDesc)type;

            foreach (var constraint in genericParam.TypeConstraints)
            {
                var instantiatedType = constraint.InstantiateSignature(typeContext.TypeInstantiation, typeContext.MethodInstantiation);

                if (instantiatedType.IsGenericParameter)
                {
                    // Make sure it is save to call this method recursively
                    if (!instantiatedConstraints.Contains(instantiatedType))
                    {
                        instantiatedConstraints.Add(instantiatedType);

                        // Constraints of this constraint apply to 'genericParam' too
                        GetInstantiatedConstraintsRecursive(typeContext, instantiatedType, ref instantiatedConstraints);
                    }
                }
                else
                {
                    instantiatedConstraints.Add(instantiatedType);
                }
            }
        }
Exemplo n.º 6
0
 public void AssertPublicMembersThrow(ArrayBuilder <string?> builder, string?[] array)
 {
     // Public methods & properties except for IsClosed
     Assert.Throws <ObjectDisposedException>(() => builder.Capacity -= 1);
     Assert.Throws <ObjectDisposedException>(() => builder[0]        = "closed");
     Assert.Throws <ObjectDisposedException>(() => builder.Add("closed"));
     Assert.Throws <ObjectDisposedException>(() => builder.AddRange(Enumerable.Repeat("closed", 2)));
     Assert.Throws <ObjectDisposedException>(() => _ = builder.BinarySearch(0, 4, "element", StringComparer.Ordinal));
     Assert.Throws <ObjectDisposedException>(() => _ = builder.BinarySearch("element"));
     Assert.Throws <ObjectDisposedException>(() => _ = builder.BinarySearch("element", StringComparer.Ordinal));
     Assert.Throws <ObjectDisposedException>(() => builder.Clear());
     Assert.Throws <ObjectDisposedException>(() => _ = builder.Close());
     Assert.Throws <ObjectDisposedException>(() => _ = builder.CloseAndSlice());
     Assert.Throws <ObjectDisposedException>(() => _ = builder.CloseAndSlice(1));
     Assert.Throws <ObjectDisposedException>(() => _ = builder.CloseAndSlice(1, 1));
     Assert.Throws <ObjectDisposedException>(() => _ = builder.Contains("element"));
     Assert.Throws <ObjectDisposedException>(() => builder.CopyTo(array));
     Assert.Throws <ObjectDisposedException>(() => builder.CopyTo(0, array, 0, 4));
     Assert.Throws <ObjectDisposedException>(() => builder.CopyTo(array, 0));
     Assert.Throws <ObjectDisposedException>(() => builder.EnsureCapacity(12));
     Assert.Throws <ObjectDisposedException>(() => _ = builder.GetEnumerator());
     Assert.Throws <ObjectDisposedException>(() => _ = builder.IndexOf("element"));
     Assert.Throws <ObjectDisposedException>(() => _ = builder.IndexOf("element", 0));
     Assert.Throws <ObjectDisposedException>(() => _ = builder.IndexOf("element", 0, 4));
     Assert.Throws <ObjectDisposedException>(() => builder.Insert(0, "closed"));
     Assert.Throws <ObjectDisposedException>(() => builder.InsertRange(0, Enumerable.Repeat("closed", 2)));
     Assert.Throws <ObjectDisposedException>(() => builder.Remove("element"));
     Assert.Throws <ObjectDisposedException>(() => builder.RemoveAt(2));
     Assert.Throws <ObjectDisposedException>(() => builder.RemoveRange(0, 3));
     Assert.Throws <ObjectDisposedException>(() => _ = builder.TrimAndClose());
     Assert.Throws <ObjectDisposedException>(() => builder.TrimExcess());
 }
Exemplo n.º 7
0
        private static void HandleCollisions(
            ArrayBuilder <string> names,
            ArrayBuilder <bool> isFixed,
            string name,
            Func <string, bool> canUse,
            bool isCaseSensitive,
            ArrayBuilder <int> collisionIndices)
        {
            var suffix   = 1;
            var comparer = isCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase;

            for (var i = 0; i < collisionIndices.Count; i++)
            {
                var collisionIndex = collisionIndices[i];
                if (isFixed[collisionIndex])
                {
                    // can't do anything about this name.
                    continue;
                }

                while (true)
                {
                    var newName = name + suffix++;
                    if (!names.Contains(newName, comparer) && canUse(newName))
                    {
                        // Found a name that doesn't conflict with anything else.
                        names[collisionIndex] = newName;
                        break;
                    }
                }
            }
        }
Exemplo n.º 8
0
 private static void AddNonIncluded(ArrayBuilder <string> builder, string item)
 {
     if (!builder.Contains(item))
     {
         builder.Add(item);
     }
 }
Exemplo n.º 9
0
            public override BoundNode VisitReturnStatement(BoundReturnStatement node)
            {
                if (node.RefKind != RefKind.None)
                {
                    refKind = node.RefKind;
                }

                var expression = node.ExpressionOpt;

                if (expression != null)
                {
                    var returnType = expression.Type;
                    // This is potentially inefficient if there are a large number of returns each with
                    // a different type. This seems unlikely.
                    if (!_types.Contains(returnType))
                    {
                        _types.Add(returnType);
                    }
                }
                else
                {
                    _hasReturnWithoutArgument = true;
                }

                return(null);
            }
            internal bool Contains(V item)
            {
                Debug.Assert(this.Count >= 1);
                ArrayBuilder <V> arrayBuilder = _value as ArrayBuilder <V>;

                return(arrayBuilder == null
                    ? EqualityComparer <V> .Default.Equals(item, (V)_value)
                    : arrayBuilder.Contains(item));
            }
        /// <summary>
        /// Add an interface and its required interfaces to the interfacesArray
        /// </summary>
        private void BuildPostOrderInterfaceList(DefType iface, ref ArrayBuilder <DefType> interfacesArray)
        {
            if (interfacesArray.Contains(iface))
            {
                return;
            }

            foreach (DefType implementedInterface in iface.RuntimeInterfaces)
            {
                BuildPostOrderInterfaceList(implementedInterface, ref interfacesArray);
            }

            if (interfacesArray.Contains(iface))
            {
                return;
            }

            interfacesArray.Add(iface);
        }
        /// <summary>
        /// Add an interface and its required interfaces to the interfacesArray
        /// </summary>
        private void BuildPostOrderInterfaceList(DefType iface, ref ArrayBuilder<DefType> interfacesArray)
        {
            if (interfacesArray.Contains(iface))
                return;

            foreach (DefType implementedInterface in iface.RuntimeInterfaces)
            {
                BuildPostOrderInterfaceList(implementedInterface, ref interfacesArray);
            }

            if (interfacesArray.Contains(iface))
                return;

            interfacesArray.Add(iface);
        }
            private void ClassifyToken(SyntaxToken token)
            {
                if (token.Span.IntersectsWith(_textSpan) && _service._syntaxTokenKinds.Contains(token.RawKind))
                {
                    _classifierBuffer.Clear();

                    var context = new EmbeddedLanguageClassificationContext(
                        _project, _semanticModel, token, _options, _result, _cancellationToken);

                    // First, see if this is a string annotated with either a comment or [StringSyntax] attribute. If
                    // so, delegate to the first classifier we have registered for whatever language ID we find.
                    if (_service._detector.IsEmbeddedLanguageToken(token, _semanticModel, _cancellationToken, out var identifier, out _) &&
                        _service._identifierToClassifiers.TryGetValue(identifier, out var classifiers))
                    {
                        foreach (var classifier in classifiers)
                        {
                            // keep track of what classifiers we've run so we don't call into them multiple times.
                            _classifierBuffer.Add(classifier.Value);

                            // If this classifier added values then need to check the other ones.
                            if (TryClassify(classifier.Value, context))
                            {
                                return;
                            }
                        }
                    }

                    // It wasn't an annotated API.  See if it's some legacy API our historical classifiers have direct
                    // support for (for example, .net APIs prior to Net6).
                    foreach (var legacyClassifier in _service._legacyClassifiers)
                    {
                        // don't bother trying to classify again if we already tried above.
                        if (_classifierBuffer.Contains(legacyClassifier.Value))
                        {
                            continue;
                        }

                        // If this classifier added values then need to check the other ones.
                        if (TryClassify(legacyClassifier.Value, context))
                        {
                            return;
                        }
                    }

                    // Finally, give the fallback classifier a chance to classify basic language escapes.
                    TryClassify(_service._fallbackClassifier, context);
                }
            }
Exemplo n.º 14
0
            private static void AddExample(
                ArrayBuilder <string> examples,
                bool standard,
                string displayText,
                CultureInfo culture,
                bool hideCulture
                )
            {
                // Single letter custom strings need a %, or else they're interpreted as a format
                // standard format string (and will throw a format exception).
                var formatString =
                    !standard && displayText.Length == 1 ? "%" + displayText : displayText;

                if (formatString == "")
                {
                    return;
                }

                // Format string may be invalid.  Just don't show anything in that case.
                string formattedDate;

                try
                {
                    formattedDate = s_exampleDateTime.ToString(formatString);
                }
                catch (FormatException)
                {
                    return;
                }
                catch (ArgumentOutOfRangeException)
                {
                    return;
                }

                var example = hideCulture
                    ? $"   {displayText} → {formattedDate}"
                    : $"   {displayText} ({culture}) → {formattedDate}";

                if (!examples.Contains(example))
                {
                    examples.Add(example);
                }
            }
Exemplo n.º 15
0
        private void AddExpressionTemp(LocalDefinition temp)
        {
            // in some cases like stack locals, there is no slot allocated.
            if (temp == null)
            {
                return;
            }

            ArrayBuilder <LocalDefinition> exprTemps = _expressionTemps;

            if (exprTemps == null)
            {
                exprTemps = ArrayBuilder <LocalDefinition> .GetInstance();

                _expressionTemps = exprTemps;
            }

            Debug.Assert(!exprTemps.Contains(temp));
            exprTemps.Add(temp);
        }
Exemplo n.º 16
0
        // Reduce extension methods to their reduced form, and remove:
        //   a) Extension methods are aren't applicable to receiverType
        //   including constraint checking.
        //   b) Duplicate methods
        //   c) Methods that are hidden or overridden by another method in the group.
        private static bool AddReducedAndFilteredMethodGroupSymbol(
            ArrayBuilder<MethodSymbol> methods,
            ArrayBuilder<MethodSymbol> filteredMethods,
            MethodSymbol method,
            ImmutableArray<TypeSymbol> typeArguments,
            TypeSymbol receiverType)
        {
            MethodSymbol constructedMethod;
            if (!typeArguments.IsDefaultOrEmpty && method.Arity == typeArguments.Length)
            {
                constructedMethod = method.Construct(typeArguments);
                Debug.Assert((object)constructedMethod != null);
            }
            else
            {
                constructedMethod = method;
            }

            if ((object)receiverType != null)
            {
                constructedMethod = constructedMethod.ReduceExtensionMethod(receiverType);
                if ((object)constructedMethod == null)
                {
                    return false;
                }
            }

            // Don't add exact duplicates.
            if (filteredMethods.Contains(constructedMethod))
            {
                return false;
            }

            methods.Add(method);
            filteredMethods.Add(constructedMethod);
            return true;
        }
        public static void GetAssemblyLocation(
            Assembly oRootAssembly,
            ArrayBuilder oAssemblyList,
            AssemblyName[] SystemAssemblies,
            bool bCustomOnly,
            bool bWithDependencies,
            bool includeRootAssembly = true,
            CustomAssemblyResolver assemblyResolver = null)
        {
            if (assemblyResolver != null)
            {
                AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(assemblyResolver.AssemblyResolveHandler);
            }

            try
            {
                if (!bCustomOnly || IsCustomAssembly(
                        SystemAssemblies,
                        oRootAssembly.GetName()))
                {
                    if (includeRootAssembly)
                    {
                        oAssemblyList.AddIfNotExists(oRootAssembly.Location);
                    }

                    if (bWithDependencies)
                    {
                        AssemblyName[] Dependencies = oRootAssembly.GetReferencedAssemblies();

                        foreach (AssemblyName oAssemblyName in Dependencies)
                        {
                            try
                            {
                                if (!bCustomOnly || IsCustomAssembly(
                                        SystemAssemblies,
                                        oAssemblyName))
                                {
                                    Assembly oDependentAssembly = Assembly.Load(oAssemblyName);

                                    // Check for circullar references
                                    if (!oAssemblyList.Contains(oDependentAssembly.Location))
                                    {
                                        GetAssemblyLocation(oDependentAssembly, oAssemblyList, SystemAssemblies, bCustomOnly, bWithDependencies, true, assemblyResolver);
                                    }
                                }
                            }
                            catch (Exception oExc)
                            {
                                Log.WriteException(oExc);
                            }
                        }
                    }
                }
            }
            finally
            {
                if (assemblyResolver != null)
                {
                    AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(assemblyResolver.AssemblyResolveHandler);
                }
            }
        }
Exemplo n.º 18
0
 private static void AddInterface(ArrayBuilder<NamedTypeSymbol> builder, NamedTypeSymbol @interface)
 {
     if (!builder.Contains(@interface))
     {
         builder.Add(@interface);
     }
 }
Exemplo n.º 19
0
        /// <summary>
        /// Returns true if the constraint is valid. Otherwise
        /// returns false and generates a diagnostic.
        /// </summary>
        internal static bool IsValidConstraint(
            string typeParameterName,
            TypeConstraintSyntax syntax,
            TypeSymbolWithAnnotations type,
            TypeParameterConstraintKind constraints,
            ArrayBuilder <TypeSymbolWithAnnotations> constraintTypes,
            DiagnosticBag diagnostics)
        {
            if (!IsValidConstraintType(syntax, type, diagnostics))
            {
                return(false);
            }

            // Ignore nullability when comparing constraints.
            if (constraintTypes.Contains(c => type.Equals(c, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)))
            {
                // "Duplicate constraint '{0}' for type parameter '{1}'"
                Error(diagnostics, ErrorCode.ERR_DuplicateBound, syntax, type.TypeSymbol.SetUnknownNullabilityForReferenceTypes(), typeParameterName);
                return(false);
            }

            if (type.TypeKind == TypeKind.Class)
            {
                // If there is already a struct or class constraint (class constraint could be
                // 'class' or explicit type), report an error and drop this class. If we don't
                // drop this additional class, we may end up with conflicting class constraints.

                if (constraintTypes.Count > 0)
                {
                    // "The class type constraint '{0}' must come before any other constraints"
                    Error(diagnostics, ErrorCode.ERR_ClassBoundNotFirst, syntax, type.TypeSymbol);
                    return(false);
                }

                if ((constraints & (TypeParameterConstraintKind.ReferenceType)) != 0)
                {
                    switch (type.SpecialType)
                    {
                    case SpecialType.System_Enum:
                    case SpecialType.System_Delegate:
                    case SpecialType.System_MulticastDelegate:
                        break;

                    default:
                        // "'{0}': cannot specify both a constraint class and the 'class' or 'struct' constraint"
                        Error(diagnostics, ErrorCode.ERR_RefValBoundWithClass, syntax, type.TypeSymbol);
                        return(false);
                    }
                }
                else if (type.SpecialType != SpecialType.System_Enum)
                {
                    if ((constraints & TypeParameterConstraintKind.ValueType) != 0)
                    {
                        // "'{0}': cannot specify both a constraint class and the 'class' or 'struct' constraint"
                        Error(diagnostics, ErrorCode.ERR_RefValBoundWithClass, syntax, type.TypeSymbol);
                        return(false);
                    }
                    else if ((constraints & TypeParameterConstraintKind.Unmanaged) != 0)
                    {
                        // "'{0}': cannot specify both a constraint class and the 'unmanaged' constraint"
                        Error(diagnostics, ErrorCode.ERR_UnmanagedBoundWithClass, syntax, type.TypeSymbol);
                        return(false);
                    }
                }
            }

            return(true);
        }