Example #1
0
        public void Terminate()
        {
            foreach (NsScriptThread thread in _threads.AsSpan())
            {
                CommitTerminateThread(thread);
            }

            _clock.Stop();
            _threads.Clear();
            _newThreads.Clear();
        }
Example #2
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());
 }
Example #3
0
        internal static void FillUsedEnumFields(ArrayBuilder <EnumField> usedFields, ArrayBuilder <EnumField> fields, ulong underlyingValue)
        {
            var remaining = underlyingValue;

            foreach (var field in fields)
            {
                var fieldValue = field.Value;
                if (fieldValue == 0)
                {
                    continue;                  // Otherwise, we'd tack the zero flag onto everything.
                }
                if ((remaining & fieldValue) == fieldValue)
                {
                    remaining -= fieldValue;

                    usedFields.Add(field);

                    if (remaining == 0)
                    {
                        break;
                    }
                }
            }

            // The value contained extra bit flags that didn't correspond to any enum field.  We will
            // report "no fields used" here so the Formatter will just display the underlying value.
            if (remaining != 0)
            {
                usedFields.Clear();
            }
        }
Example #4
0
        private static async Task <ImmutableArray <INavigateToSearchResult> > FindNavigableDeclaredSymbolInfosAsync(
            Project project, Document searchDocument,
            PatternMatcher nameMatcher, PatternMatcher containerMatcherOpt,
            ArrayBuilder <PatternMatch> nameMatches, ArrayBuilder <PatternMatch> containerMatches,
            CancellationToken cancellationToken)
        {
            var result = ArrayBuilder <INavigateToSearchResult> .GetInstance();

            foreach (var document in project.Documents)
            {
                if (searchDocument != null && document != searchDocument)
                {
                    continue;
                }

                cancellationToken.ThrowIfCancellationRequested();
                var declarationInfo = await document.GetSyntaxTreeIndexAsync(cancellationToken).ConfigureAwait(false);

                foreach (var declaredSymbolInfo in declarationInfo.DeclaredSymbolInfos)
                {
                    nameMatches.Clear();
                    containerMatches.Clear();

                    cancellationToken.ThrowIfCancellationRequested();
                    if (nameMatcher.AddMatches(declaredSymbolInfo.Name, nameMatches) &&
                        containerMatcherOpt?.AddMatches(declaredSymbolInfo.FullyQualifiedContainerName, containerMatches) != false)
                    {
                        result.Add(ConvertResult(
                                       declaredSymbolInfo, document, nameMatches, containerMatches));
                    }
                }
            }

            return(result.ToImmutableAndFree());
        }
Example #5
0
 /// <summary>
 /// Restore the data saved by SaveTypes
 /// </summary>
 public void RestoreTypes()
 {
     _classes.Clear();
     _classes.Add(_savedClasses.AsSlice());
     _pairedBracketTypes.Clear();
     _pairedBracketTypes.Add(_savedPairedBracketTypes.AsSlice());
 }
Example #6
0
 /// <summary>
 /// Save the Types and PairedBracketTypes of this BiDiData
 /// </summary>
 /// <remarks>
 /// This is used when processing embedded style runs with
 /// BiDiClass overrides. Text layout process saves the data,
 /// overrides the style runs to neutral, processes the bidi
 /// data for the entire paragraph and then restores this data
 /// before processing the embedded runs.
 /// </remarks>
 public void SaveTypes()
 {
     // Capture the types data
     _savedClasses.Clear();
     _savedClasses.Add(_classes.AsSlice());
     _savedPairedBracketTypes.Clear();
     _savedPairedBracketTypes.Add(_pairedBracketTypes.AsSlice());
 }
Example #7
0
 public void Clear()
 {
     EditsBuffer.Clear();
     ReferenceFramesBuffer.Clear();
     ComponentRenderQueue.Clear();
     UpdatedComponentDiffs.Clear();
     _disposedComponentIds.Clear();
     _disposedEventHandlerIds.Clear();
 }
Example #8
0
            private void AddConjunct(BoundExpression test)
            {
                if (_sideEffectBuilder.Count != 0)
                {
                    test = _factory.Sequence(ImmutableArray <LocalSymbol> .Empty, _sideEffectBuilder.ToImmutable(), test);
                    _sideEffectBuilder.Clear();
                }

                _conjunctBuilder.Add(test);
            }
        protected static SyntaxTokenList GetUpdatedDeclarationAccessibilityModifiers(
            ArrayBuilder <SyntaxToken> newModifierTokens, SyntaxTokenList modifiersList,
            Func <SyntaxToken, bool> isAccessibilityModifier)
        {
            using var _ = ArrayBuilder <SyntaxToken> .GetInstance(out var updatedModifiersList);

            var anyAccessModifierSeen = false;

            foreach (var modifier in modifiersList)
            {
                SyntaxToken newModifier;
                if (isAccessibilityModifier(modifier))
                {
                    if (newModifierTokens.Count == 0)
                    {
                        continue;
                    }

                    newModifier = newModifierTokens[0]
                                  .WithLeadingTrivia(modifier.LeadingTrivia)
                                  .WithTrailingTrivia(modifier.TrailingTrivia);
                    newModifierTokens.RemoveAt(0);
                    anyAccessModifierSeen = true;
                }
                else
                {
                    if (anyAccessModifierSeen && newModifierTokens.Any())
                    {
                        updatedModifiersList.AddRange(newModifierTokens);
                        newModifierTokens.Clear();
                    }

                    newModifier = modifier;
                }

                updatedModifiersList.Add(newModifier);
            }

            if (!anyAccessModifierSeen)
            {
                for (var i = newModifierTokens.Count - 1; i >= 0; i--)
                {
                    updatedModifiersList.Insert(0, newModifierTokens[i]);
                }
            }
            else
            {
                updatedModifiersList.AddRange(newModifierTokens);
            }

            return(updatedModifiersList.ToSyntaxTokenList());
        }
Example #10
0
        private void ReleaseExpressionTemps()
        {
            if (_expressionTemps?.Count > 0)
            {
                // release in reverse order to keep same temps on top of the temp stack if possible
                for (int i = _expressionTemps.Count - 1; i >= 0; i--)
                {
                    var temp = _expressionTemps[i];
                    FreeTemp(temp);
                }

                _expressionTemps.Clear();
            }
        }
            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);
                }
            }
Example #12
0
        private static void AddResultIfMatch(
            Document document, DeclaredSymbolInfo declaredSymbolInfo,
            PatternMatcher nameMatcher, PatternMatcher containerMatcherOpt,
            ArrayBuilder <PatternMatch> nameMatches, ArrayBuilder <PatternMatch> containerMatches,
            ArrayBuilder <SearchResult> result, CancellationToken cancellationToken)
        {
            nameMatches.Clear();
            containerMatches.Clear();

            cancellationToken.ThrowIfCancellationRequested();
            if (nameMatcher.AddMatches(declaredSymbolInfo.Name, nameMatches) &&
                containerMatcherOpt?.AddMatches(declaredSymbolInfo.FullyQualifiedContainerName, containerMatches) != false)
            {
                result.Add(ConvertResult(
                               declaredSymbolInfo, document, nameMatches, containerMatches));
            }
        }
        private ImmutableArray <TItem> GetNextBatchAndResetQueue()
        {
            lock (_gate)
            {
                var result = ArrayBuilder <TItem> .GetInstance();

                result.AddRange(_nextBatch);

                // mark there being no existing update task so that the next OOP notification will
                // kick one off.
                _nextBatch.Clear();
                _uniqueItems.Clear();
                _taskInFlight = false;

                return(result.ToImmutableAndFree());
            }
        }
Example #14
0
        internal override ReadOnlyCollection <byte> CompileGetLocals(
            ArrayBuilder <LocalAndMethod> locals,
            bool argumentsOnly,
            ImmutableArray <Alias> aliases,
            DiagnosticBag diagnostics,
            out string typeName,
            Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData)
        {
            var context       = this.CreateCompilationContext();
            var moduleBuilder = context.CompileGetLocals(TypeName, locals, argumentsOnly, aliases, testData, diagnostics);
            ReadOnlyCollection <byte> assembly = null;

            if ((moduleBuilder != null) && (locals.Count > 0))
            {
                using (var stream = new MemoryStream())
                {
                    Cci.PeWriter.WritePeToStream(
                        new EmitContext(moduleBuilder, null, diagnostics, metadataOnly: false, includePrivateMembers: true),
                        context.MessageProvider,
                        () => stream,
                        getPortablePdbStreamOpt: null,
                        nativePdbWriterOpt: null,
                        pdbPathOpt: null,
                        metadataOnly: false,
                        isDeterministic: false,
                        emitTestCoverageData: false,
                        privateKeyOpt: null,
                        cancellationToken: default(CancellationToken));

                    if (!diagnostics.HasAnyErrors())
                    {
                        assembly = new ReadOnlyCollection <byte>(stream.ToArray());
                    }
                }
            }

            if (assembly == null)
            {
                locals.Clear();
                assembly = s_emptyBytes;
            }

            typeName = TypeName;
            return(assembly);
        }
Example #15
0
        private static void FillCollisionIndices(
            ArrayBuilder <string> names,
            string name,
            bool isCaseSensitive,
            ArrayBuilder <int> collisionIndices)
        {
            collisionIndices.Clear();

            var comparer = isCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase;

            for (int i = 0, n = names.Count; i < n; i++)
            {
                if (comparer.Equals(names[i], name))
                {
                    collisionIndices.Add(i);
                }
            }
        }
Example #16
0
        internal override ReadOnlyCollection <byte> CompileGetLocals(
            ArrayBuilder <LocalAndMethod> locals,
            bool argumentsOnly,
            out string typeName,
            Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData = null)
        {
            var diagnostics   = DiagnosticBag.GetInstance();
            var context       = this.CreateCompilationContext(null);
            var moduleBuilder = context.CompileGetLocals(TypeName, locals, argumentsOnly, testData, diagnostics);
            ReadOnlyCollection <byte> assembly = null;

            if ((moduleBuilder != null) && (locals.Count > 0))
            {
                using (var stream = new MemoryStream())
                {
                    Cci.PeWriter.WritePeToStream(
                        new EmitContext((Cci.IModule)moduleBuilder, null, diagnostics),
                        context.MessageProvider,
                        () => stream,
                        nativePdbWriterOpt: null,
                        pdbPathOpt: null,
                        allowMissingMethodBodies: false,
                        deterministic: false,
                        cancellationToken: default(CancellationToken));

                    if (!diagnostics.HasAnyErrors())
                    {
                        assembly = new ReadOnlyCollection <byte>(stream.ToArray());
                    }
                }
            }

            diagnostics.Free();

            if (assembly == null)
            {
                locals.Clear();
                assembly = s_emptyBytes;
            }

            typeName = TypeName;
            return(assembly);
        }
        /// <summary>
        /// Trim excessive inaccessible text.
        /// </summary>
        private static void TrimInaccessibleText(ArrayBuilder <SourceText> segments)
        {
            int length, size;

            ComputeLengthAndStorageSize(segments, out length, out size);

            // if more than half of the storage is unused, compress into a single new segment
            if (length < size / 2)
            {
                var writer = SourceTextWriter.Create(length);
                foreach (var segment in segments)
                {
                    segment.Write(writer);
                }

                segments.Clear();
                segments.Add(writer.ToSourceText());
            }
        }
Example #18
0
        /// <summary>
        /// Trim excessive inaccessible text.
        /// </summary>
        private static void TrimInaccessibleText(ArrayBuilder <SourceText> segments)
        {
            ComputeLengthAndStorageSize(segments, out int length, out int size);

            // if more than half of the storage is unused, compress into a single new segment
            if (length < size / 2)
            {
                Encoding            encoding  = segments[0].Encoding;
                SourceHashAlgorithm algorithm = segments[0].ChecksumAlgorithm;

                SourceTextWriter writer = SourceTextWriter.Create(encoding, algorithm, length);
                foreach (SourceText segment in segments)
                {
                    segment.Write(writer);
                }

                segments.Clear();
                segments.Add(writer.ToSourceText());
            }
        }
Example #19
0
        internal void Tick()
        {
            if (!IsRunning)
            {
                return;
            }
            long?time = null;

            _newThreads.Clear();
            _terminatedThreads.Clear();
            foreach (NsScriptThread thread in _threads.AsSpan())
            {
                if (thread.SuspensionTime.HasValue && thread.SleepTimeout.HasValue)
                {
                    time ??= Ticks;
                    long delta = time.Value - thread.SuspensionTime.Value;
                    if (delta >= thread.SleepTimeout)
                    {
                        CommitResumeThread(thread);
                    }
                }
            }
        }
Example #20
0
        /// <summary>
        /// Given a list of method and/or property candidates, choose the first one (if any) with a signature
        /// that matches the parameter list in the cref.  Return null if there isn't one.
        /// </summary>
        /// <remarks>
        /// Produces a diagnostic for ambiguous matches, but not for unresolved members - WRN_BadXMLRef is
        /// handled in BindMemberCref.
        /// </remarks>
        private static ImmutableArray <Symbol> PerformCrefOverloadResolution(ArrayBuilder <Symbol> candidates, ImmutableArray <ParameterSymbol> parameterSymbols, int arity, MemberCrefSyntax memberSyntax, out Symbol ambiguityWinner, DiagnosticBag diagnostics)
        {
            ArrayBuilder <Symbol> viable = null;

            foreach (Symbol candidate in candidates)
            {
                // BREAK: In dev11, any candidate with the type "dynamic" anywhere in its parameter list would be skipped
                // (see XmlDocCommentBinder::bindXmlReference).  Apparently, this was because "the params that the xml doc
                // comments produce never will."  This does not appear to have made sense in dev11 (skipping dropping the
                // candidate doesn't cause anything to blow up and may cause resolution to start succeeding) and it almost
                // certainly does not in roslyn (the signature comparer ignores the object-dynamic distiction anyway).

                Symbol signatureMember;
                switch (candidate.Kind)
                {
                case SymbolKind.Method:
                {
                    MethodSymbol candidateMethod         = (MethodSymbol)candidate;
                    MethodKind   candidateMethodKind     = candidateMethod.MethodKind;
                    bool         candidateMethodIsVararg = candidateMethod.IsVararg;

                    // If the arity from the cref is zero, then we accept methods of any arity.
                    int signatureMemberArity = candidateMethodKind == MethodKind.Constructor
                                ? 0
                                : (arity == 0 ? candidateMethod.Arity : arity);

                    // CONSIDER: we might want to reuse this method symbol (as long as the MethodKind and Vararg-ness match).
                    signatureMember = new SignatureOnlyMethodSymbol(
                        methodKind: candidateMethodKind,
                        typeParameters: IndexedTypeParameterSymbol.Take(signatureMemberArity),
                        parameters: parameterSymbols,
                        // This specific comparer only looks for varargs.
                        callingConvention: candidateMethodIsVararg ? Microsoft.Cci.CallingConvention.ExtraArguments : Microsoft.Cci.CallingConvention.HasThis,
                        // These are ignored by this specific MemberSignatureComparer.
                        containingType: null,
                        name: null,
                        returnType: null,
                        returnTypeCustomModifiers: ImmutableArray <CustomModifier> .Empty,
                        explicitInterfaceImplementations: ImmutableArray <MethodSymbol> .Empty);
                    break;
                }

                case SymbolKind.Property:
                {
                    // CONSIDER: we might want to reuse this property symbol.
                    signatureMember = new SignatureOnlyPropertySymbol(
                        parameters: parameterSymbols,
                        // These are ignored by this specific MemberSignatureComparer.
                        containingType: null,
                        name: null,
                        type: null,
                        typeCustomModifiers: ImmutableArray <CustomModifier> .Empty,
                        isStatic: false,
                        explicitInterfaceImplementations: ImmutableArray <PropertySymbol> .Empty);
                    break;
                }

                case SymbolKind.NamedType:
                    // Because we replaced them with constructors when we built the candidate list.
                    throw ExceptionUtilities.UnexpectedValue(candidate.Kind);

                default:
                    continue;
                }

                if (MemberSignatureComparer.CrefComparer.Equals(signatureMember, candidate))
                {
                    Debug.Assert(candidate.GetMemberArity() != 0 || candidate.Name == WellKnownMemberNames.InstanceConstructorName || arity == 0,
                                 "Can only have a 0-arity, non-constructor candidate if the desired arity is 0.");

                    if (viable == null)
                    {
                        viable = ArrayBuilder <Symbol> .GetInstance();

                        viable.Add(candidate);
                    }
                    else
                    {
                        bool oldArityIsZero = viable[0].GetMemberArity() == 0;
                        bool newArityIsZero = candidate.GetMemberArity() == 0;

                        // If the cref specified arity 0 and the current candidate has arity 0 but the previous
                        // match did not, then the current candidate is the unambiguous winner (unless there's
                        // another match with arity 0 in a subsequent iteration).
                        if (!oldArityIsZero || newArityIsZero)
                        {
                            if (!oldArityIsZero && newArityIsZero)
                            {
                                viable.Clear();
                            }

                            viable.Add(candidate);
                        }
                    }
                }
            }

            if (viable == null)
            {
                ambiguityWinner = null;
                return(ImmutableArray <Symbol> .Empty);
            }

            if (viable.Count > 1)
            {
                ambiguityWinner = viable[0];
                CrefSyntax crefSyntax = GetRootCrefSyntax(memberSyntax);
                diagnostics.Add(ErrorCode.WRN_AmbiguousXMLReference, crefSyntax.Location, crefSyntax.ToString(), ambiguityWinner, viable[1]);
            }
            else
            {
                ambiguityWinner = null;
            }

            return(viable.ToImmutableAndFree());
        }
        private bool GetUserDefinedOperators(UnaryOperatorKind kind, BoundExpression operand, ArrayBuilder <UnaryOperatorAnalysisResult> results, ref HashSet <DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert(operand != null);

            if ((object)operand.Type == null)
            {
                // If the operand has no type -- because it is a null reference or a lambda or a method group --
                // there is no way we can determine what type to search for user-defined operators.
                return(false);
            }

            // Spec 7.3.5 Candidate user-defined operators
            // SPEC: Given a type T and an operation op(A) ... the set of candidate user-defined
            // SPEC: operators provided by T for op(A) is determined as follows:

            // SPEC: If T is a nullable type then T0 is its underlying type; otherwise T0 is T.
            // SPEC: For all operator declarations in T0 and all lifted forms of such operators, if
            // SPEC: at least one operator is applicable with respect to A then the set of candidate
            // SPEC: operators consists of all such applicable operators. Otherwise, if T0 is object
            // SPEC: then the set of candidate operators is empty. Otherwise, the set of candidate
            // SPEC: operators is the set provided by the direct base class of T0, or the effective
            // SPEC: base class of T0 if T0 is a type parameter.

            // https://github.com/dotnet/roslyn/issues/34451: The spec quote should be adjusted to cover operators from interfaces as well.
            // From https://github.com/dotnet/csharplang/blob/master/meetings/2017/LDM-2017-06-27.md:
            // - We only even look for operator implementations in interfaces if one of the operands has a type that is an interface or
            // a type parameter with a non-empty effective base interface list.
            // - The applicable operators from classes / structs shadow those in interfaces.This matters for constrained type parameters:
            // the effective base class can shadow operators from effective base interfaces.
            // - If we find an applicable candidate in an interface, that candidate shadows all applicable operators in base interfaces:
            // we stop looking.

            TypeSymbol type0 = operand.Type.StrippedType();

            // Searching for user-defined operators is expensive; let's take an early out if we can.
            if (OperatorFacts.DefinitelyHasNoUserDefinedOperators(type0))
            {
                return(false);
            }

            string name      = OperatorFacts.UnaryOperatorNameFromOperatorKind(kind);
            var    operators = ArrayBuilder <UnaryOperatorSignature> .GetInstance();

            bool hadApplicableCandidates = false;

            NamedTypeSymbol current = type0 as NamedTypeSymbol;

            if ((object)current == null)
            {
                current = type0.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics);
            }

            if ((object)current == null && type0.IsTypeParameter())
            {
                current = ((TypeParameterSymbol)type0).EffectiveBaseClass(ref useSiteDiagnostics);
            }

            for (; (object)current != null; current = current.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics))
            {
                operators.Clear();
                GetUserDefinedUnaryOperatorsFromType(current, kind, name, operators);
                results.Clear();
                if (CandidateOperators(operators, operand, results, ref useSiteDiagnostics))
                {
                    hadApplicableCandidates = true;
                    break;
                }
            }

            // Look in base interfaces, or effective interfaces for type parameters
            if (!hadApplicableCandidates)
            {
                ImmutableArray <NamedTypeSymbol> interfaces = default;
                if (type0.IsInterfaceType())
                {
                    interfaces = type0.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics);
                }
                else if (type0.IsTypeParameter())
                {
                    interfaces = ((TypeParameterSymbol)type0).AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics);
                }

                if (!interfaces.IsDefaultOrEmpty)
                {
                    var shadowedInterfaces = PooledHashSet <NamedTypeSymbol> .GetInstance();

                    var resultsFromInterface = ArrayBuilder <UnaryOperatorAnalysisResult> .GetInstance();

                    results.Clear();

                    foreach (NamedTypeSymbol @interface in interfaces)
                    {
                        if ([email protected])
                        {
                            // this code could be reachable in error situations
                            continue;
                        }

                        if (shadowedInterfaces.Contains(@interface))
                        {
                            // this interface is "shadowed" by a derived interface
                            continue;
                        }

                        operators.Clear();
                        resultsFromInterface.Clear();
                        GetUserDefinedUnaryOperatorsFromType(@interface, kind, name, operators);
                        if (CandidateOperators(operators, operand, resultsFromInterface, ref useSiteDiagnostics))
                        {
                            hadApplicableCandidates = true;
                            results.AddRange(resultsFromInterface);

                            // this interface "shadows" all its base interfaces
                            shadowedInterfaces.AddAll(@interface.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics));
                        }
                    }

                    shadowedInterfaces.Free();
                    resultsFromInterface.Free();
                }
            }

            operators.Free();

            return(hadApplicableCandidates);
        }
Example #22
0
        private static void MergeReducedAndFilteredMethodGroupSymbol(
            ArrayBuilder<MethodSymbol> methods,
            ArrayBuilder<MethodSymbol> filteredMethods,
            SingleLookupResult singleResult,
            ImmutableArray<TypeSymbol> typeArguments,
            TypeSymbol receiverType,
            ref LookupResultKind resultKind)
        {
            Debug.Assert(singleResult.Kind != LookupResultKind.Empty);
            Debug.Assert((object)singleResult.Symbol != null);
            Debug.Assert(singleResult.Symbol.Kind == SymbolKind.Method);

            var singleKind = singleResult.Kind;
            if (resultKind > singleKind)
            {
                return;
            }
            else if (resultKind < singleKind)
            {
                methods.Clear();
                filteredMethods.Clear();
                resultKind = LookupResultKind.Empty;
            }

            var method = (MethodSymbol)singleResult.Symbol;
            if (AddReducedAndFilteredMethodGroupSymbol(methods, filteredMethods, method, typeArguments, receiverType))
            {
                Debug.Assert(methods.Count > 0);
                if (resultKind < singleKind)
                {
                    resultKind = singleKind;
                }
            }

            Debug.Assert((methods.Count == 0) == (resultKind == LookupResultKind.Empty));
            Debug.Assert(methods.Count == filteredMethods.Count);
        }
        // Returns true if there were any applicable candidates.
        private bool GetUserDefinedOperators(UnaryOperatorKind kind, BoundExpression operand, ArrayBuilder<UnaryOperatorAnalysisResult> results, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert(operand != null);

            if ((object)operand.Type == null)
            {
                // If the operand has no type -- because it is a null reference or a lambda or a method group --
                // there is no way we can determine what type to search for user-defined operators.
                return false;
            }

            // Spec 7.3.5 Candidate user-defined operators
            // SPEC: Given a type T and an operation op(A) ... the set of candidate user-defined 
            // SPEC: operators provided by T for op(A) is determined as follows:

            // SPEC: If T is a nullable type then T0 is its underlying type; otherwise T0 is T.
            // SPEC: For all operator declarations in T0 and all lifted forms of such operators, if
            // SPEC: at least one operator is applicable with respect to A then the set of candidate
            // SPEC: operators consists of all such applicable operators. Otherwise, if T0 is object
            // SPEC: then the set of candidate operators is empty. Otherwise, the set of candidate
            // SPEC: operators is the set provided by the direct base class of T0, or the effective
            // SPEC: base class of T0 if T0 is a type parameter.

            TypeSymbol type0 = operand.Type.StrippedType();

            // Searching for user-defined operators is expensive; let's take an early out if we can.
            if (OperatorFacts.DefinitelyHasNoUserDefinedOperators(type0))
            {
                return false;
            }

            string name = OperatorFacts.UnaryOperatorNameFromOperatorKind(kind);
            var operators = ArrayBuilder<UnaryOperatorSignature>.GetInstance();
            bool hadApplicableCandidates = false;

            NamedTypeSymbol current = type0 as NamedTypeSymbol;
            if ((object)current == null)
            {
                current = type0.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics);
            }

            if ((object)current == null && type0.IsTypeParameter())
            {
                current = ((TypeParameterSymbol)type0).EffectiveBaseClass(ref useSiteDiagnostics);
            }

            for (; (object)current != null; current = current.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics))
            {
                operators.Clear();
                GetUserDefinedUnaryOperatorsFromType(current, kind, name, operators);
                results.Clear();
                if (CandidateOperators(operators, operand, results, ref useSiteDiagnostics))
                {
                    hadApplicableCandidates = true;
                    break;
                }
            }

            operators.Free();

            return hadApplicableCandidates;
        }
Example #24
0
        /// <summary>
        /// Get the import strings for a given method, following forward pointers as necessary.
        /// </summary>
        /// <returns>
        /// For each namespace enclosing the method, a list of import strings, innermost to outermost.
        /// There should always be at least one entry, for the global namespace.
        /// </returns>
        public static ImmutableArray <ImmutableArray <string> > GetCSharpGroupedImportStrings(this ISymUnmanagedReader reader, int methodToken, int methodVersion, out ImmutableArray <string> externAliasStrings)
        {
            externAliasStrings = default(ImmutableArray <string>);

            ImmutableArray <short> groupSizes = default(ImmutableArray <short>);
            bool seenForward = false;

RETRY:
            byte[] bytes = reader.GetCustomDebugInfo(methodToken, methodVersion);
            if (bytes == null)
            {
                return(default(ImmutableArray <ImmutableArray <string> >));
            }

            foreach (var record in GetCustomDebugInfoRecords(bytes))
            {
                switch (record.Kind)
                {
                case CustomDebugInfoKind.UsingInfo:
                    if (!groupSizes.IsDefault)
                    {
                        throw new InvalidOperationException(string.Format("Expected at most one Using record for method {0}", FormatMethodToken(methodToken)));
                    }

                    groupSizes = DecodeUsingRecord(record.Data);
                    break;

                case CustomDebugInfoKind.ForwardInfo:
                    if (!externAliasStrings.IsDefault)
                    {
                        throw new InvalidOperationException(string.Format("Did not expect both Forward and ForwardToModule records for method {0}", FormatMethodToken(methodToken)));
                    }

                    methodToken = DecodeForwardRecord(record.Data);

                    // Follow at most one forward link (as in FUNCBRECEE::ensureNamespaces).
                    // NOTE: Dev11 may produce chains of forward links (e.g. for System.Collections.Immutable).
                    if (!seenForward)
                    {
                        seenForward = true;
                        goto RETRY;
                    }

                    break;

                case CustomDebugInfoKind.ForwardToModuleInfo:
                    if (!externAliasStrings.IsDefault)
                    {
                        throw new InvalidOperationException(string.Format("Expected at most one ForwardToModule record for method {0}", FormatMethodToken(methodToken)));
                    }

                    int moduleInfoMethodToken = DecodeForwardToModuleRecord(record.Data);
                    ImmutableArray <string> allModuleInfoImportStrings = reader.GetMethodByVersion(moduleInfoMethodToken, methodVersion).GetImportStrings();
                    ArrayBuilder <string>   externAliasBuilder         = ArrayBuilder <string> .GetInstance();

                    foreach (string importString in allModuleInfoImportStrings)
                    {
                        if (IsCSharpExternAliasInfo(importString))
                        {
                            externAliasBuilder.Add(importString);
                        }
                    }

                    externAliasStrings = externAliasBuilder.ToImmutableAndFree();
                    break;
                }
            }

            if (groupSizes.IsDefault)
            {
                // This can happen in malformed PDBs (e.g. chains of forwards).
                return(default(ImmutableArray <ImmutableArray <string> >));
            }

            var method = reader.GetMethodByVersion(methodToken, methodVersion);

            if (method == null)
            {
                return(default(ImmutableArray <ImmutableArray <string> >));
            }

            ImmutableArray <string> importStrings = method.GetImportStrings();
            int numImportStrings = importStrings.Length;

            ArrayBuilder <ImmutableArray <string> > resultBuilder = ArrayBuilder <ImmutableArray <string> > .GetInstance(groupSizes.Length);

            ArrayBuilder <string> groupBuilder = ArrayBuilder <string> .GetInstance();

            int pos = 0;

            foreach (short groupSize in groupSizes)
            {
                for (int i = 0; i < groupSize; i++, pos++)
                {
                    if (pos >= numImportStrings)
                    {
                        throw new InvalidOperationException(string.Format("Group size indicates more imports than there are import strings (method {0}).", FormatMethodToken(methodToken)));
                    }

                    string importString = importStrings[pos];
                    if (IsCSharpExternAliasInfo(importString))
                    {
                        throw new InvalidOperationException(string.Format("Encountered extern alias info before all import strings were consumed (method {0}).", FormatMethodToken(methodToken)));
                    }

                    groupBuilder.Add(importString);
                }

                resultBuilder.Add(groupBuilder.ToImmutable());
                groupBuilder.Clear();
            }

            if (externAliasStrings.IsDefault)
            {
                Debug.Assert(groupBuilder.Count == 0);

                // Extern alias detail strings (prefix "Z") are not included in the group counts.
                for (; pos < numImportStrings; pos++)
                {
                    string importString = importStrings[pos];
                    if (!IsCSharpExternAliasInfo(importString))
                    {
                        throw new InvalidOperationException(string.Format("Expected only extern alias info strings after consuming the indicated number of imports (method {0}).", FormatMethodToken(methodToken)));
                    }

                    groupBuilder.Add(importString);
                }

                externAliasStrings = groupBuilder.ToImmutableAndFree();
            }
            else
            {
                groupBuilder.Free();

                if (pos < numImportStrings)
                {
                    throw new InvalidOperationException(string.Format("Group size indicates fewer imports than there are import strings (method {0}).", FormatMethodToken(methodToken)));
                }
            }

            return(resultBuilder.ToImmutableAndFree());
        }
Example #25
0
 internal void Clear()
 {
     _kind = LookupResultKind.Empty;
     _symbolList.Clear();
     _error = null;
 }
        /// <summary>
        /// Get the import strings for a given method, following forward pointers as necessary.
        /// </summary>
        /// <returns>
        /// For each namespace enclosing the method, a list of import strings, innermost to outermost.
        /// There should always be at least one entry, for the global namespace.
        /// </returns>
        public static ImmutableArray <ImmutableArray <string> > GetCSharpGroupedImportStrings(this ISymUnmanagedReader reader, int methodToken, out ImmutableArray <string> externAliasStrings)
        {
            externAliasStrings = default(ImmutableArray <string>);

            ImmutableArray <short> groupSizes = default(ImmutableArray <short>);
            bool seenForward = false;

RETRY:
            var bytes = reader.GetCustomDebugInfo(methodToken);

            if (bytes == null)
            {
                return(default(ImmutableArray <ImmutableArray <string> >));
            }

            int offset = 0;

            byte globalVersion;
            byte unusedGlobalCount;

            ReadGlobalHeader(bytes, ref offset, out globalVersion, out unusedGlobalCount);
            CheckVersion(globalVersion, methodToken);

            while (offset < bytes.Length)
            {
                byte version;
                CustomDebugInfoKind kind;
                int size;
                ReadRecordHeader(bytes, ref offset, out version, out kind, out size);
                CheckVersion(version, methodToken);

                if (kind == CustomDebugInfoKind.UsingInfo)
                {
                    if (!groupSizes.IsDefault)
                    {
                        throw new InvalidOperationException(string.Format("Expected at most one Using record for method {0}", FormatMethodToken(methodToken)));
                    }

                    ReadUsingRecord(bytes, ref offset, size, out groupSizes);
                }
                else if (kind == CustomDebugInfoKind.ForwardInfo)
                {
                    if (!externAliasStrings.IsDefault)
                    {
                        throw new InvalidOperationException(string.Format("Did not expect both Forward and ForwardToModule records for method {0}", FormatMethodToken(methodToken)));
                    }

                    ReadForwardRecord(bytes, ref offset, size, out methodToken);
                    if (!seenForward) // Follow at most one forward link.
                    {
                        seenForward = true;
                        goto RETRY;
                    }
                }
                else if (kind == CustomDebugInfoKind.ForwardToModuleInfo)
                {
                    if (!externAliasStrings.IsDefault)
                    {
                        throw new InvalidOperationException(string.Format("Expected at most one ForwardToModule record for method {0}", FormatMethodToken(methodToken)));
                    }

                    int moduleInfoMethodToken;
                    ReadForwardToModuleRecord(bytes, ref offset, size, out moduleInfoMethodToken);
                    ImmutableArray <string> allModuleInfoImportStrings = GetImportStrings(reader.GetBaselineMethod(moduleInfoMethodToken));
                    ArrayBuilder <string>   externAliasBuilder         = ArrayBuilder <string> .GetInstance();

                    foreach (string importString in allModuleInfoImportStrings)
                    {
                        if (IsCSharpExternAliasInfo(importString))
                        {
                            externAliasBuilder.Add(importString);
                        }
                    }
                    externAliasStrings = externAliasBuilder.ToImmutableAndFree();
                }
                else
                {
                    SkipRecord(bytes, ref offset, size);
                }
            }

            if (groupSizes.IsDefault)
            {
                throw new InvalidOperationException(string.Format("Didn't find usings info for method {0}", FormatMethodToken(methodToken)));
            }

            ImmutableArray <string> importStrings = GetImportStrings(reader.GetBaselineMethod(methodToken));
            int numImportStrings = importStrings.Length;

            ArrayBuilder <ImmutableArray <string> > resultBuilder = ArrayBuilder <ImmutableArray <string> > .GetInstance(groupSizes.Length);

            ArrayBuilder <string> groupBuilder = ArrayBuilder <string> .GetInstance();

            int pos = 0;

            foreach (short groupSize in groupSizes)
            {
                for (int i = 0; i < groupSize; i++, pos++)
                {
                    if (pos >= numImportStrings)
                    {
                        throw new InvalidOperationException(string.Format("Group size indicates more imports than there are import strings (method {0}).", FormatMethodToken(methodToken)));
                    }

                    string importString = importStrings[pos];
                    if (IsCSharpExternAliasInfo(importString))
                    {
                        throw new InvalidOperationException(string.Format("Encountered extern alias info before all import strings were consumed (method {0}).", FormatMethodToken(methodToken)));
                    }

                    groupBuilder.Add(importString);
                }

                resultBuilder.Add(groupBuilder.ToImmutable());
                groupBuilder.Clear();
            }


            if (externAliasStrings.IsDefault)
            {
                Debug.Assert(groupBuilder.Count == 0);

                // Extern alias detail strings (prefix "Z") are not included in the group counts.
                for (; pos < numImportStrings; pos++)
                {
                    string importString = importStrings[pos];
                    if (!IsCSharpExternAliasInfo(importString))
                    {
                        throw new InvalidOperationException(string.Format("Expected only extern alias info strings after consuming the indicated number of imports (method {0}).", FormatMethodToken(methodToken)));
                    }

                    groupBuilder.Add(importString);
                }

                externAliasStrings = groupBuilder.ToImmutableAndFree();
            }
            else
            {
                groupBuilder.Free();

                if (pos < numImportStrings)
                {
                    throw new InvalidOperationException(string.Format("Group size indicates fewer imports than there are import strings (method {0}).", FormatMethodToken(methodToken)));
                }
            }

            return(resultBuilder.ToImmutableAndFree());
        }
Example #27
0
 public void Clear()
 {
     _set.Clear();
     _list.Clear();
 }
Example #28
0
        // Returns true if there were any applicable candidates.
        private bool GetUserDefinedOperators(UnaryOperatorKind kind, BoundExpression operand, ArrayBuilder <UnaryOperatorAnalysisResult> results, ref HashSet <DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert(operand != null);

            if ((object)operand.Type == null)
            {
                // If the operand has no type -- because it is a null reference or a lambda or a method group --
                // there is no way we can determine what type to search for user-defined operators.
                return(false);
            }

            // Spec 7.3.5 Candidate user-defined operators
            // SPEC: Given a type T and an operation op(A) ... the set of candidate user-defined
            // SPEC: operators provided by T for op(A) is determined as follows:

            // SPEC: If T is a nullable type then T0 is its underlying type; otherwise T0 is T.
            // SPEC: For all operator declarations in T0 and all lifted forms of such operators, if
            // SPEC: at least one operator is applicable with respect to A then the set of candidate
            // SPEC: operators consists of all such applicable operators. Otherwise, if T0 is object
            // SPEC: then the set of candidate operators is empty. Otherwise, the set of candidate
            // SPEC: operators is the set provided by the direct base class of T0, or the effective
            // SPEC: base class of T0 if T0 is a type parameter.

            TypeSymbol type0 = operand.Type.StrippedType();

            // Searching for user-defined operators is expensive; let's take an early out if we can.
            if (OperatorFacts.DefinitelyHasNoUserDefinedOperators(type0))
            {
                return(false);
            }

            string name      = OperatorFacts.UnaryOperatorNameFromOperatorKind(kind);
            var    operators = ArrayBuilder <UnaryOperatorSignature> .GetInstance();

            bool hadApplicableCandidates = false;

            NamedTypeSymbol current = type0 as NamedTypeSymbol;

            if ((object)current == null)
            {
                current = type0.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics);
            }

            if ((object)current == null && type0.IsTypeParameter())
            {
                current = ((TypeParameterSymbol)type0).EffectiveBaseClass(ref useSiteDiagnostics);
            }

            for (; (object)current != null; current = current.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics))
            {
                operators.Clear();
                GetUserDefinedUnaryOperatorsFromType(current, kind, name, operators);
                results.Clear();
                if (CandidateOperators(operators, operand, results, ref useSiteDiagnostics))
                {
                    hadApplicableCandidates = true;
                    break;
                }
            }

            operators.Free();

            return(hadApplicableCandidates);
        }
Example #29
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            using var portableDeviceManager = new PortableDeviceManager();

            portableDeviceManager.GetDevices();

            int i;

            for (i = 0; i < portableDeviceManager.PortableDevices.Count; i++)
            {
                Console.WriteLine($"{i}: {portableDeviceManager.PortableDevices[i].DeviceFriendlyName}");
            }

            Console.WriteLine("Please choose a device.");

            if (uint.TryParse(Console.ReadLine(), out uint uintResult) && uintResult < i)
            {
                IPortableDevice portableDevice = portableDeviceManager.PortableDevices[(int)uintResult];

                portableDevice.Open(new ClientVersion("PortableDeviceTests", 1, 0, 0), new PortableDeviceOpeningOptions(GenericRights.Read | GenericRights.Write, FileShareOptions.Read | FileShareOptions.Write, false));

                i = 0;

                var b = new ArrayBuilder <IPortableDeviceObject>();

                foreach (IPortableDeviceObject portableDeviceObject in portableDevice)
                {
                    if (portableDeviceObject.Type == new Guid(Microsoft.WindowsAPICodePack.PortableDevices.Guids.PropertySystem.ContentType.FunctionalObject))
                    {
                        _ = b.AddLast(portableDeviceObject);

                        Console.WriteLine($"{i++}: {portableDeviceObject.Name}");
                    }
                }

                Console.WriteLine("Please enter a memory id.");

                if (uint.TryParse(Console.ReadLine(), out uintResult) && uintResult < i)
                {
                    i = 0;

                    var enumerable = (IEnumerablePortableDeviceObject)b.ToArray()[(int)uintResult];

                    b.Clear();

                    foreach (IPortableDeviceObject portableDeviceObject in enumerable)
                    {
                        if (portableDeviceObject is IPortableDeviceFolder folder)
                        {
                            _ = b.AddLast(folder);

                            Console.WriteLine($"{i++}: {folder.Name}");
                        }
                    }

                    Console.WriteLine("Enter the id of the action to perform on the device.");
                    Console.WriteLine("0: Transfer content.");
                    Console.WriteLine("1: Delete content.");

                    string _menuId = Console.ReadLine();

                    if (int.TryParse(_menuId, out int menuId))
                    {
                        if (menuId == 0)
                        {
                            Console.WriteLine("Please enter the id of the folder to copy the file to.");

                            if (uint.TryParse(Console.ReadLine(), out uintResult) && uintResult < i)
                            {
                                var _folder = (IPortableDeviceFolder)b.ToArray()[(int)uintResult];

                                b.Clear();

                                Console.WriteLine("Please enter a file to copy to the portable device.");

                                string path = Console.ReadLine();

                                Console.WriteLine("Enter the file content type GUID.");

                                string contentType = Console.ReadLine();

                                if (Guid.TryParse(contentType, out Guid guidContentType))
                                {
                                    Console.WriteLine("Enter the file format GUID.");

                                    string format = Console.ReadLine();

                                    if (Guid.TryParse(format, out Guid guidFormat))
                                    {
                                        var stream = new FileStream(path, FileMode.Open);

                                        uint totalWritten = 0;

                                        _folder.PortableDeviceObjectAdded += PortableDevice_PortableDeviceObjectAdded;

                                        _folder.TransferTo(stream, 4000, false, guidContentType, guidFormat, written =>
                                        {
                                            Console.WriteLine($"{written} bytes written during the last write operation; {(totalWritten += written)} total. Continue (Y/y: yes; other input: no)?");

                                            return(true); // Console.ReadLine().ToUpper() == "Y"
                                        });
                                    }
                                }

                                i = 0;

                                foreach (IPortableDeviceObject file in _folder)
                                {
                                    if (file is IPortableDeviceFile _file)
                                    {
                                        _ = b.AddLast(_file);

                                        Console.WriteLine($"{i++}: {_file.Name}");
                                    }
                                }

                                if (uint.TryParse(Console.ReadLine(), out uintResult) && uintResult < i)
                                {
                                    var portableDeviceFile = (IPortableDeviceFile)b.ToArray()[(int)uintResult];

                                    b.Clear();

                                    Console.WriteLine("Please enter a destination file.");

                                    path = Console.ReadLine();

                                    path = $"{System.IO.Path.GetDirectoryName(path)}\\{Path.GetFileNameWithoutExtension(path)} - Copy{Path.GetExtension(path)}";

                                    uint totalWritten = 0;

                                    var stream = new FileStream(path, FileMode.CreateNew);

                                    portableDeviceFile.TransferFrom(stream, 4000, false, written =>
                                    {
                                        Console.WriteLine($"Written: {written}; total: {(totalWritten += written)}.");

                                        return(true);
                                    });

                                    stream.Flush();

                                    stream.Dispose();
                                }
                            }
                        }

                        else if (menuId == 1)
                        {
                            Console.WriteLine("Please enter the id of the folder of the file to delete.");

                            if (uint.TryParse(Console.ReadLine(), out uintResult) && uintResult < i)
                            {
                                var _folder = (IPortableDeviceFolder)b.ToArray()[(int)uintResult];

                                b.Clear();

                                if (_folder.Count == 1)
                                {
                                    if (_folder[0] is IPortableDeviceFile item)
                                    {
                                        _folder.PortableDeviceObjectRemoved += PortableDevice_PortableDeviceObjectRemoved;

                                        item.Delete();
                                    }

                                    else
                                    {
                                        Console.WriteLine("The folder of the given id does not contain a file.");
                                    }
                                }

                                else
                                {
                                    Console.WriteLine("The folder of the given id is empty or contains more than one file.");
                                }
                            }
                        }

                        else
                        {
                            Console.WriteLine("Incorrect menu id.");
                        }
                    }

                    else
                    {
                        Console.WriteLine("Incorrect menu id.");
                    }
                }
            }

            else
            {
                Console.WriteLine("Incorrect device id.");
            }
        }
Example #30
0
        /// <summary>
        /// Gets a temporary level buffer. Used by the text layout process when
        /// resolving style runs with different BiDiClass.
        /// </summary>
        /// <param name="length">Length of the required ExpandableBuffer</param>
        /// <returns>An uninitialized level ExpandableBuffer</returns>
        public ArraySlice <sbyte> GetTempLevelBuffer(int length)
        {
            _tempLevelBuffer.Clear();

            return(_tempLevelBuffer.Add(length, false));
        }
Example #31
0
        internal void LookupExtensionMethodsInUsings(
            ArrayBuilder <MethodSymbol> methods,
            string name,
            int arity,
            LookupOptions options,
            bool callerIsSemanticModel)
        {
            Debug.Assert(methods.Count == 0);

            // We need to avoid collecting multiple candidates for an extension method imported both through a namespace and a static class
            // We will look for duplicates only if both of the following flags are set to true
            bool seenNamespaceWithExtensionMethods   = false;
            bool seenStaticClassWithExtensionMethods = false;

            foreach (var nsOrType in this.Usings)
            {
                switch (nsOrType.NamespaceOrType.Kind)
                {
                case SymbolKind.Namespace:
                {
                    var count = methods.Count;
                    ((NamespaceSymbol)nsOrType.NamespaceOrType).GetExtensionMethods(methods, name, arity, options);

                    // If we found any extension methods, then consider this using as used.
                    if (methods.Count != count)
                    {
                        MarkImportDirective(nsOrType.UsingDirective, callerIsSemanticModel);
                        seenNamespaceWithExtensionMethods = true;
                    }

                    break;
                }

                case SymbolKind.NamedType:
                {
                    var count = methods.Count;
                    ((NamedTypeSymbol)nsOrType.NamespaceOrType).GetExtensionMethods(methods, name, arity, options);

                    // If we found any extension methods, then consider this using as used.
                    if (methods.Count != count)
                    {
                        MarkImportDirective(nsOrType.UsingDirective, callerIsSemanticModel);
                        seenStaticClassWithExtensionMethods = true;
                    }

                    break;
                }
                }
            }

            if (seenNamespaceWithExtensionMethods && seenStaticClassWithExtensionMethods)
            {
                var methodsNoDuplicates = ArrayBuilder <MethodSymbol> .GetInstance();

                methodsNoDuplicates.AddRange(methods.Distinct());
                if (methodsNoDuplicates.Count < methods.Count)
                {
                    methods.Clear();
                    methods.AddRange(methodsNoDuplicates);
                }

                methodsNoDuplicates.Free();
            }
        }
        private bool GetUserDefinedOperators(
            BinaryOperatorKind kind,
            TypeSymbol type0,
            BoundExpression left,
            BoundExpression right,
            ArrayBuilder<BinaryOperatorAnalysisResult> results,
            ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            // Spec 7.3.5 Candidate user-defined operators
            // SPEC: Given a type T and an operation operator op(A), where op is an overloadable 
            // SPEC: operator and A is an argument list, the set of candidate user-defined operators 
            // SPEC: provided by T for operator op(A) is determined as follows:

            // SPEC: Determine the type T0. If T is a nullable type, T0 is its underlying type, 
            // SPEC: otherwise T0 is equal to T.

            // (The caller has already passed in the stripped type.)

            // SPEC: For all operator op declarations in T0 and all lifted forms of such operators, 
            // SPEC: if at least one operator is applicable (7.5.3.1) with respect to the argument 
            // SPEC: list A, then the set of candidate operators consists of all such applicable 
            // SPEC: operators in T0. Otherwise, if T0 is object, the set of candidate operators is empty.
            // SPEC: Otherwise, the set of candidate operators provided by T0 is the set of candidate 
            // SPEC: operators provided by the direct base class of T0, or the effective base class of
            // SPEC: T0 if T0 is a type parameter.

            string name = OperatorFacts.BinaryOperatorNameFromOperatorKind(kind);
            var operators = ArrayBuilder<BinaryOperatorSignature>.GetInstance();
            bool hadApplicableCandidates = false;

            NamedTypeSymbol current = type0 as NamedTypeSymbol;
            if ((object)current == null)
            {
                current = type0.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics);
            }

            if ((object)current == null && type0.IsTypeParameter())
            {
                current = ((TypeParameterSymbol)type0).EffectiveBaseClass(ref useSiteDiagnostics);
            }

            for (; (object)current != null; current = current.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics))
            {
                operators.Clear();
                GetUserDefinedBinaryOperatorsFromType(current, kind, name, operators);
                results.Clear();
                if (CandidateOperators(operators, left, right, results, ref useSiteDiagnostics))
                {
                    hadApplicableCandidates = true;
                    break;
                }
            }

            operators.Free();

            return hadApplicableCandidates;
        }
Example #33
0
        /// <summary>
        /// Trim excessive inaccessible text.
        /// </summary>
        private static void TrimInaccessibleText(ArrayBuilder<SourceText> segments)
        {
            int length, size;
            ComputeLengthAndStorageSize(segments, out length, out size);

            // if more than half of the storage is unused, compress into a single new segment
            if (length < size / 2)
            {
                var encoding = segments[0].Encoding;
                var algorithm = segments[0].ChecksumAlgorithm;

                var writer = SourceTextWriter.Create(encoding, algorithm, length);
                foreach (var segment in segments)
                {
                    segment.Write(writer);
                }

                segments.Clear();
                segments.Add(writer.ToSourceText());
            }
        }
        internal static void FillUsedEnumFields(ArrayBuilder<EnumField> usedFields, ArrayBuilder<EnumField> fields, ulong underlyingValue)
        {
            var remaining = underlyingValue;
            foreach (var field in fields)
            {
                var fieldValue = field.Value;
                if (fieldValue == 0) continue; // Otherwise, we'd tack the zero flag onto everything.

                if ((remaining & fieldValue) == fieldValue)
                {
                    remaining -= fieldValue;

                    usedFields.Add(field);

                    if (remaining == 0) break;
                }
            }

            // The value contained extra bit flags that didn't correspond to any enum field.  We will
            // report "no fields used" here so the Formatter will just display the underlying value.
            if (remaining != 0)
            {
                usedFields.Clear();
            }
        }
Example #35
0
        internal void LookupExtensionMethodsInUsings(
            ArrayBuilder<MethodSymbol> methods,
            string name,
            int arity,
            LookupOptions options,
            bool callerIsSemanticModel)
        {
            Debug.Assert(methods.Count == 0);

            // We need to avoid collecting multiple candidates for an extension method imported both through a namespace and a static class
            // We will look for duplicates only if both of the following flags are set to true
            bool seenNamespaceWithExtensionMethods = false;
            bool seenStaticClassWithExtensionMethods = false;

            foreach (var nsOrType in this.Usings)
            {
                switch (nsOrType.NamespaceOrType.Kind)
                {
                    case SymbolKind.Namespace:
                        {
                            var count = methods.Count;
                            ((NamespaceSymbol)nsOrType.NamespaceOrType).GetExtensionMethods(methods, name, arity, options);

                            // If we found any extension methods, then consider this using as used.
                            if (methods.Count != count)
                            {
                                MarkImportDirective(nsOrType.UsingDirective, callerIsSemanticModel);
                                seenNamespaceWithExtensionMethods = true;
                            }

                            break;
                        }

                    case SymbolKind.NamedType:
                        {
                            var count = methods.Count;
                            ((NamedTypeSymbol)nsOrType.NamespaceOrType).GetExtensionMethods(methods, name, arity, options);

                            // If we found any extension methods, then consider this using as used.
                            if (methods.Count != count)
                            {
                                MarkImportDirective(nsOrType.UsingDirective, callerIsSemanticModel);
                                seenStaticClassWithExtensionMethods = true;
                            }

                            break;
                        }
                }
            }

            if (seenNamespaceWithExtensionMethods && seenStaticClassWithExtensionMethods)
            {
                var methodsNoDuplicates = ArrayBuilder<MethodSymbol>.GetInstance();
                methodsNoDuplicates.AddRange(methods.Distinct());
                if (methodsNoDuplicates.Count < methods.Count)
                {
                    methods.Clear();
                    methods.AddRange(methodsNoDuplicates);
                }

                methodsNoDuplicates.Free();
            }
        }
        internal override ReadOnlyCollection<byte> CompileGetLocals(
            ReadOnlyCollection<Alias> aliases,
            ArrayBuilder<LocalAndMethod> locals,
            bool argumentsOnly,
            DiagnosticBag diagnostics,
            out string typeName,
            Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData)
        {
            var context = this.CreateCompilationContext(null);
            var moduleBuilder = context.CompileGetLocals(aliases, TypeName, locals, argumentsOnly, testData, diagnostics);
            ReadOnlyCollection<byte> assembly = null;

            if ((moduleBuilder != null) && (locals.Count > 0))
            {
                using (var stream = new MemoryStream())
                {
                    Cci.PeWriter.WritePeToStream(
                        new EmitContext((Cci.IModule)moduleBuilder, null, diagnostics),
                        context.MessageProvider,
                        () => stream,
                        nativePdbWriterOpt: null,
                        pdbPathOpt: null,
                        allowMissingMethodBodies: false,
                        deterministic: false,
                        cancellationToken: default(CancellationToken));

                    if (!diagnostics.HasAnyErrors())
                    {
                        assembly = new ReadOnlyCollection<byte>(stream.ToArray());
                    }
                }
            }

            if (assembly == null)
            {
                locals.Clear();
                assembly = s_emptyBytes;
            }

            typeName = TypeName;
            return assembly;
        }
Example #37
0
 public void Clear()
 {
     _entries.Clear();
 }