示例#1
0
 public ImmutableDictionary<string, object> PrepareMetadata(ImmutableDictionary<string, object> metadata)
 {
     if (!metadata.ContainsKey("_enableSearch"))
     {
         metadata = metadata.Add("_enableSearch", true);
     }
     return metadata;
 }
            private static Dictionary <ITextBuffer, DiffResult> ProcessNewTagTrees(
                ImmutableArray <DocumentSnapshotSpan> spansToTag,
                ImmutableDictionary <ITextBuffer, TagSpanIntervalTree <TTag> > oldTagTrees,
                ImmutableDictionary <ITextBuffer, TagSpanIntervalTree <TTag> > newTagTrees,
                CancellationToken cancellationToken)
            {
                using (Logger.LogBlock(FunctionId.Tagger_TagSource_ProcessNewTags, cancellationToken))
                {
                    var bufferToChanges = new Dictionary <ITextBuffer, DiffResult>();

                    foreach (var(latestBuffer, latestSpans) in newTagTrees)
                    {
                        var snapshot = spansToTag.First(s => s.SnapshotSpan.Snapshot.TextBuffer == latestBuffer).SnapshotSpan.Snapshot;

                        if (oldTagTrees.TryGetValue(latestBuffer, out var previousSpans))
                        {
                            var difference = ComputeDifference(snapshot, latestSpans, previousSpans);
                            bufferToChanges[latestBuffer] = difference;
                        }
                        else
                        {
                            // It's a new buffer, so report all spans are changed
                            bufferToChanges[latestBuffer] = new DiffResult(added: new(latestSpans.GetSpans(snapshot).Select(t => t.Span)), removed: null);
                        }
                    }

                    foreach (var(oldBuffer, previousSpans) in oldTagTrees)
                    {
                        if (!newTagTrees.ContainsKey(oldBuffer))
                        {
                            // This buffer disappeared, so let's notify that the old tags are gone
                            bufferToChanges[oldBuffer] = new DiffResult(added: null, removed: new(previousSpans.GetSpans(oldBuffer.CurrentSnapshot).Select(t => t.Span)));
                        }
                    }

                    return(bufferToChanges);
                }
            }
示例#3
0
            > MergeDiagnosticAnalyzerMap(
            ImmutableDictionary <object, ImmutableArray <DiagnosticAnalyzer> > map1,
            ImmutableDictionary <object, ImmutableArray <DiagnosticAnalyzer> > map2
            )
        {
            var current = map1;
            var seen    = new HashSet <DiagnosticAnalyzer>(map1.Values.SelectMany(v => v));

            foreach (var(referenceIdentity, analyzers) in map2)
            {
                if (map1.ContainsKey(referenceIdentity))
                {
                    continue;
                }

                current = current.Add(
                    referenceIdentity,
                    analyzers.Where(a => seen.Add(a)).ToImmutableArray()
                    );
            }

            return(current);
        }
示例#4
0
        private void UpdateCompilerAnalyzerMapIfNeeded(
            string language,
            ImmutableArray <DiagnosticAnalyzer> analyzers
            )
        {
            if (_compilerDiagnosticAnalyzerMap.ContainsKey(language))
            {
                return;
            }

            foreach (var analyzer in analyzers)
            {
                if (analyzer.IsCompilerAnalyzer())
                {
                    ImmutableInterlocked.GetOrAdd(
                        ref _compilerDiagnosticAnalyzerMap,
                        language,
                        analyzer
                        );
                    return;
                }
            }
        }
示例#5
0
        public OcarinaSelector(ModeData data,
                               ImmutableDictionary <ModeId, ModeData> modesData,
                               ImmutableDictionary <ModeId, Func <DeskPiMode, DeskPiMode> > modes,
                               ImmutableDictionary <KeyId, Note> keyToNote,
                               Func <DeskPiMode, DeskPiMode> createIntroMode)
            : base(() => new OcarinaSelector(data, modesData, modes, keyToNote, createIntroMode), data)
        {
            CheckOrphans(modesData, modes);

            this.songTrie = new Trie <Note, Func <DeskPiMode, DeskPiMode> >();

            foreach (var entry in modesData)
            {
                if (modes.ContainsKey(entry.Key))
                {
                    songTrie = songTrie.Insert(entry.Value.Song.Notes, modes[entry.Key]);
                }
            }

            this.keyToNote       = keyToNote;
            this.createIntroMode = createIntroMode;
            this.receivedNotes   = ImmutableList <Note> .Empty;
        }
示例#6
0
        public bool Equals(CompositeCacheKey other)
        {
            if (ReferenceEquals(null, other))
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }
            if (BaseCacheKey != other.BaseCacheKey)
            {
                return(false);
            }

            var allOthersMatch = other.SubKeys.All(kvp =>
                                                   SubKeys.ContainsKey(kvp.Key) &&
                                                   kvp.Value == SubKeys[kvp.Key]
                                                   );
            var otherContainsAll = SubKeys.All(kvp => other.SubKeys.ContainsKey(kvp.Key));

            return(allOthersMatch && otherContainsAll);
        }
示例#7
0
        internal virtual int?Step()
        {
            var instr = ReadNext();

            if (instr == 0)
            {
                return(null);
            }

            var opCode = (OpCode)instr;

            if (!opCodes.ContainsKey(opCode))
            {
                throw new InvalidOperationException(string.Format("Unknown opcode: 0x{0}", instr.ToString("X2")));
            }

            opCodes[opCode]();

            // TODO: Count costs...
            var cyclesSpent = 1;

            return(cyclesSpent);
        }
示例#8
0
        private ImmutableDictionary <string, DiagnosticDescriptor> LoadDiagnosticsById()
        {
            ImmutableDictionary <string, DiagnosticDescriptor> .Builder diagnosticsById = ImmutableDictionary.CreateBuilder <string, DiagnosticDescriptor>();

            diagnosticsById.AddRange(Analyzers
                                     .SelectMany(f => f.SupportedDiagnostics)
                                     .Distinct(DiagnosticDescriptorComparer.Id)
                                     .OrderBy(f => f, DiagnosticDescriptorComparer.Id)
                                     .Select(f => new KeyValuePair <string, DiagnosticDescriptor>(f.Id, f)));

            foreach (CodeFixProvider fixer in Fixers)
            {
                foreach (string diagnosticId in fixer.FixableDiagnosticIds)
                {
                    if (!diagnosticsById.ContainsKey(diagnosticId))
                    {
                        diagnosticsById[diagnosticId] = null;
                    }
                }
            }

            return(diagnosticsById.ToImmutable());
        }
        public InterceptedProjectProperties(ImmutableArray <Lazy <IInterceptingPropertyValueProvider, IInterceptingPropertyValueProviderMetadata> > valueProviders, IProjectProperties defaultProperties)
            : base(defaultProperties)
        {
            Requires.NotNullOrEmpty(valueProviders, nameof(valueProviders));

            ImmutableDictionary <string, Lazy <IInterceptingPropertyValueProvider, IInterceptingPropertyValueProviderMetadata> > .Builder builder = ImmutableDictionary.CreateBuilder <string, Lazy <IInterceptingPropertyValueProvider, IInterceptingPropertyValueProviderMetadata> >(StringComparers.PropertyNames);
            foreach (Lazy <IInterceptingPropertyValueProvider, IInterceptingPropertyValueProviderMetadata> valueProvider in valueProviders)
            {
                string[] propertyNames = valueProvider.Metadata.PropertyNames;

                foreach (var propertyName in propertyNames)
                {
                    Requires.Argument(!string.IsNullOrEmpty(propertyName), nameof(valueProvider), "A null or empty property name was found");

                    // CONSIDER: Allow duplicate intercepting property value providers for same property name.
                    Requires.Argument(!builder.ContainsKey(propertyName), nameof(valueProviders), "Duplicate property value providers for same property name");

                    builder.Add(propertyName, valueProvider);
                }
            }

            _valueProviders = builder.ToImmutable();
        }
示例#10
0
        public override string GetMangledStringName(string literal)
        {
            Debug.Assert(OrdinalReceived);

            string mangledName;

            if (_mangledStringLiterals.TryGetValue(literal, out mangledName))
            {
                return(mangledName);
            }

            mangledName = SanitizeNameWithHash(literal);

            lock (this)
            {
                if (!_mangledStringLiterals.ContainsKey(literal))
                {
                    _mangledStringLiterals = _mangledStringLiterals.Add(literal, mangledName);
                }
            }

            return(mangledName);
        }
示例#11
0
        public void Set(string key, object val)
        {
            object old = Get <object> (key);

            if (val == null)
            {
                //avoid emitting the event if not necessary
                if (old == null)
                {
                    return;
                }
                if (properties.ContainsKey(key))
                {
                    properties = properties.Remove(key);
                }
            }
            else
            {
                //avoid emitting the event if not necessary
                if (val.Equals(old))
                {
                    return;
                }
                properties = properties.SetItem(key, val);
                if (!val.GetType().IsClass || (val is string))
                {
                    if (defaultValues.ContainsKey(key))
                    {
                        if (defaultValues[key] == val)
                        {
                            properties = properties.Remove(key);
                        }
                    }
                }
            }
            OnPropertyChanged(new PropertyChangedEventArgs(key, old, val));
        }
示例#12
0
        protected override IInPacket CreatePacket(Stream stream, out int packetSize)
        {
            packetSize = 0;
            if (stream.Length - stream.Position < ClientPacketHeaderSize)
            {
                return(null);
            }

            var initialPosition = stream.Position;
            var header          = new byte[ClientPacketHeaderSize];

            stream.Read(header, 0, header.Length);

            // the size is encoded in big endian and doesn't include the size of the size itself
            var size    = sizeof(ushort) + BitConverter.ToUInt16(new[] { header[1], header[0] }, 0);
            var ordinal = BitConverter.ToUInt32(header, sizeof(ushort));

            packetSize = size;

            if (stream.Length - initialPosition < size)
            {
                return(null);
            }

            var opcode = (ShardClientOpcode)ordinal;

            if (packetMap.ContainsKey(opcode))
            {
                Console.WriteLine($"received packet from client: type = {opcode}, total size = {size}");
                return((IInPacket)Activator.CreateInstance(packetMap[opcode]));
            }
            else
            {
                Console.WriteLine($"received unimplemented packet from client: type = {opcode} (0x{(ushort)opcode:x4}), total size = {size}");
                return(new UnimplementedPacket(size - ClientPacketHeaderSize));
            }
        }
示例#13
0
        private static ImmutableDictionary <Language, LanguageConfig> ValidateLanguages(ImmutableDictionary <Language, LanguageConfig> languages)
        {
            var errors = new List <ValidationError>();

            foreach (var languageConfig in languages.Values)
            {
                foreach (var fallback in languageConfig.LanguageFallbacks)
                {
                    if (!languages.ContainsKey(fallback))
                    {
                        var message = $"Config for language '{languageConfig.Language.Iso2Code}' contains unsupported fallback language '{fallback.Iso2Code}'";

                        errors.Add(new ValidationError(message));
                    }
                }
            }

            if (errors.Count > 0)
            {
                throw new ValidationException("Cannot configure language.", errors);
            }

            return(languages);
        }
示例#14
0
        /// <summary>
        /// Returns true if this cross-targeting aggregate project context has the same set of target frameworks and active target framework as the given active and known configurations.
        /// </summary>
        public bool HasMatchingTargetFrameworks(ProjectConfiguration activeProjectConfiguration,
                                                IEnumerable <ProjectConfiguration> knownProjectConfigurations)
        {
            Assumes.True(IsCrossTargeting);
            Assumes.True(activeProjectConfiguration.IsCrossTargeting());
            Assumes.True(knownProjectConfigurations.All(c => c.IsCrossTargeting()));

            ITargetFramework activeTargetFramework = TargetFrameworkProvider.GetTargetFramework(activeProjectConfiguration.Dimensions[ConfigurationGeneral.TargetFrameworkProperty]);

            if (!_activeTargetFramework.Equals(activeTargetFramework))
            {
                // Active target framework is different.
                return(false);
            }

            var targetFrameworks = knownProjectConfigurations.Select(
                c => c.Dimensions[ConfigurationGeneral.TargetFrameworkProperty]).ToImmutableHashSet();

            if (targetFrameworks.Count != _configuredProjectContextsByTargetFramework.Count)
            {
                // Different number of target frameworks.
                return(false);
            }

            foreach (string targetFrameworkMoniker in targetFrameworks)
            {
                ITargetFramework targetFramework = TargetFrameworkProvider.GetTargetFramework(targetFrameworkMoniker);
                if (!_configuredProjectContextsByTargetFramework.ContainsKey(targetFramework))
                {
                    // Differing TargetFramework
                    return(false);
                }
            }

            return(true);
        }
示例#15
0
        public Task <(string id, object state)> NewResourceAsync(
            string type, string name, ImmutableDictionary <string, object> inputs, string?provider, string?id)
        {
            var outputs = ImmutableDictionary.CreateBuilder <string, object>();

            // Forward all input parameters as resource outputs, so that we could test them.
            outputs.AddRange(inputs);

            // <-- We'll customize the mocks here
            // Set the name to resource name if it's not set explicitly in inputs.
            if (!inputs.ContainsKey("name"))
            {
                outputs.Add("name", name);
            }

            if (type == "azure-native:storage:StorageAccount")
            {
                // ... set its web endpoint property.
                // Normally this would be calculated by Azure, so we have to mock it.
                outputs.Add("primaryEndpoints", new Dictionary <string, object?>
                {
                    { "blob", "BlobEndpoint" },
                    { "dfs", "DfsEndpoint" },
                    { "file", "FileEndpoint" },
                    { "internetEndpoints", null },
                    { "microsoftEndpoints", null },
                    { "queue", "QueueEndpoint" },
                    { "table", "TableEndpoint" },
                    { "web", $"https://{name}.web.core.windows.net" },
                });
            }

            // Default the resource ID to `{name}_id`.
            id ??= $"{name}_id";
            return(Task.FromResult((id, (object)outputs)));
        }
        // Internal, for test use -- normal code should use the factory methods
        internal DependenciesSnapshot(
            TargetFramework activeTargetFramework,
            ImmutableDictionary <TargetFramework, TargetedDependenciesSnapshot> dependenciesByTargetFramework)
        {
            Requires.NotNull(activeTargetFramework, nameof(activeTargetFramework));
            Requires.NotNull(dependenciesByTargetFramework, nameof(dependenciesByTargetFramework));

#if false
            // The validation in this #if/#endif block is sound in theory, however is causing quite a few NFEs.
            // For example https://github.com/dotnet/project-system/issues/6656.
            //
            // We have disabled it for now. The consequence of this test failing is that dependencies added to
            // the tree are not exposed via extensibility APIs such as DTE/VSLangProj.
            //
            // At some point we should revisit how the dependencies tree models its target frameworks, likely
            // as part of https://github.com/dotnet/project-system/issues/6183.

            // We have seen NFEs where the active target framework is unsupported. Skipping validation in such cases is better than faulting the dataflow.
            if (!activeTargetFramework.Equals(TargetFramework.Empty) &&
                !activeTargetFramework.Equals(TargetFramework.Unsupported) &&
                !dependenciesByTargetFramework.ContainsKey(activeTargetFramework))
            {
                string keyNames = dependenciesByTargetFramework.Count == 0
                    ? "no items"
                    : string.Join(", ", dependenciesByTargetFramework.Keys.Select(t => $"\"{t.TargetFrameworkMoniker}\""));

                Requires.Argument(
                    false,
                    nameof(activeTargetFramework),
                    $"Value \"{activeTargetFramework.TargetFrameworkMoniker}\" is unexpected. Must be a key in {nameof(dependenciesByTargetFramework)}, which contains {keyNames}.");
            }
#endif

            ActiveTargetFramework         = activeTargetFramework;
            DependenciesByTargetFramework = dependenciesByTargetFramework;
        }
        protected EnumToStringUsingTranslationMappingSerializer(Dictionary <T, string> translation)
        {
            _translation = translation.ToImmutableDictionary();
            foreach (T enumValue in Enum.GetValues(typeof(T)).OfType <T>())
            {
                if (!_translation.ContainsKey(enumValue))
                {
                    throw new ArgumentException(
                              $"enum translation must be exhaustive, but '{enumValue}' is missing.");
                }
            }
            var translationBack = new Dictionary <string, T>();

            foreach ((T key, string value) in _translation)
            {
                if (translationBack.ContainsKey(value))
                {
                    throw new ArgumentException(
                              $"enum translation values must be unique, but '{value}' was used multiple times");
                }
                translationBack[value] = key;
            }
            _translationBack = translationBack.ToImmutableDictionary();
        }
示例#18
0
            public State(ImmutableDictionary <Language, LanguageConfig> languages, LanguageConfig master)
            {
                foreach (var languageConfig in languages.Values)
                {
                    foreach (var fallback in languageConfig.LanguageFallbacks)
                    {
                        if (!languages.ContainsKey(fallback))
                        {
                            var message = $"Config for language '{languageConfig.Language.Iso2Code}' contains unsupported fallback language '{fallback.Iso2Code}'";

                            throw new InvalidOperationException(message);
                        }
                    }
                }

                Languages = languages;

                if (master == null)
                {
                    throw new InvalidOperationException("Config has no master language.");
                }

                this.Master = master;
            }
示例#19
0
            private void ProcessLambdaOrLocalFunctionInvocation(IMethodSymbol targetMethod, IOperation invocation)
            {
                Debug.Assert(targetMethod.MethodKind == MethodKind.LambdaMethod || targetMethod.MethodKind == MethodKind.LocalFunction);

                // Lambda and local function invocations can access captured variables.
                if (_hazardousParameterUsageBuilderOpt != null &&
                    TryGetInterproceduralAnalysisResult(invocation, out var invokedMethodAnalysisResult))
                {
                    var notValidatedLocations = CurrentAnalysisData.Keys.Where(IsNotOrMaybeValidatedLocation);
                    if (notValidatedLocations.Any())
                    {
                        var hazardousParameterUsagesInInvokedMethod = invokedMethodAnalysisResult.HazardousParameterUsages;
                        foreach (var kvp in hazardousParameterUsagesInInvokedMethod)
                        {
                            var parameter  = kvp.Key;
                            var syntaxNode = kvp.Value;
                            if (!_hazardousParameterUsageBuilderOpt.ContainsKey(parameter))
                            {
                                HandleHazardousOperation(syntaxNode, notValidatedLocations.Where(l => l.SymbolOpt == parameter));
                            }
                        }
                    }
                }
            }
示例#20
0
 protected override bool CanBeChanged(SyntaxNode node, SemanticModel semanticModel) =>
 NodeToDeclarationName.ContainsKey(node.Kind()) && VerifyCanBeChangedBySymbol(node, semanticModel);
示例#21
0
 public bool HasOption(string optionKey)
 {
     return(options.ContainsKey(optionKey));
 }
 public bool ContainsKey(TKey key)
 => _forwardMap.ContainsKey(key);
 public bool ContainsValue(TValue value)
 => _backwardMap.ContainsKey(value);
 public bool HasType(ResourceScope scopeType, ResourceTypeReference typeReference)
 => typeDictionary.ContainsKey(typeReference);
 public void ContainsKey_Test()
 {
 	Dictionary<int, string> _dictionary = new Dictionary<int, string>
     {
         {1, "aabb"},
         {2, "bbcc"},
         {3, "ccdd"}
     };
 	ImmutableDictionary<int, string> _immutableDictionary = new ImmutableDictionary<int, string>(_dictionary);        	
 	Assert.IsTrue(_immutableDictionary.ContainsKey(1));
 }
示例#26
0
        /// <summary>
        /// Returns if <see cref="DisableType"/> and objectId are disabled.
        /// </summary>
        public bool IsDisabled(DisableType type, uint objectId)
        {
            ulong hash = Hash(type, objectId);

            return(disables.ContainsKey(hash));
        }
示例#27
0
        private static ProjectDependencyGraph CreateDependencyGraph(
            IReadOnlyList<ProjectId> projectIds,
            ImmutableDictionary<ProjectId, ProjectState> projectStates)
        {
            var map = projectStates.Values.Select(state => new KeyValuePair<ProjectId, ImmutableHashSet<ProjectId>>(
                    state.Id,
                    state.ProjectReferences.Where(pr => projectStates.ContainsKey(pr.ProjectId)).Select(pr => pr.ProjectId).ToImmutableHashSet()))
                    .ToImmutableDictionary();

            return new ProjectDependencyGraph(projectIds.ToImmutableArray(), map);
        }
 public bool ContainsKey(string key)
 {
     return(_dictionary.ContainsKey(key));
 }
 private static bool MethodCalledFromDispose(ImmutableDictionary<INamedTypeSymbol, ImmutableHashSet<IMethodSymbol>> disposeMethodsCalledFromDispose, IMethodSymbol dispose)
 {
     return disposeMethodsCalledFromDispose.ContainsKey(dispose.ContainingType) &&
            disposeMethodsCalledFromDispose[dispose.ContainingType].Contains(dispose);
 }
示例#30
0
 public override bool CanConvert(Type typeToConvert) =>
 typeToConvert.IsGenericType && converters.ContainsKey(typeToConvert.GetGenericTypeDefinition());
示例#31
0
 public bool ContainsEdge(TEdgeId edgeId) => _edges.ContainsKey(edgeId);
示例#32
0
        private static ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>> MergeDiagnosticAnalyzerMap(
            ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>> map1, ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>> map2)
        {
            var current = map1;
            var seen = new HashSet<DiagnosticAnalyzer>(map1.Values.SelectMany(v => v));

            foreach (var kv in map2)
            {
                var referenceIdentity = kv.Key;
                var analyzers = kv.Value;

                if (map1.ContainsKey(referenceIdentity))
                {
                    continue;
                }

                current = current.Add(referenceIdentity, analyzers.Where(a => seen.Add(a)).ToImmutableArray());
            }

            return current;
        }
示例#33
0
 public bool HasParameter(string parameterKey)
 {
     return(parameters.ContainsKey(parameterKey));
 }
示例#34
0
        /// <summary>
        /// TBD
        /// </summary>
        /// <param name="message">TBD</param>
        protected override void OnReceive(object message)
        {
            var state = message as ClusterEvent.CurrentClusterState;

            if (state != null)
            {
                _leader = state.Leader != null && state.Leader.Equals(SelfAddress);
                foreach (var m in state.Unreachable)
                {
                    UnreachableMember(m);
                }
                return;
            }

            var unreachableMember = message as ClusterEvent.UnreachableMember;

            if (unreachableMember != null)
            {
                UnreachableMember(unreachableMember.Member);
                return;
            }

            var reachableMember = message as ClusterEvent.ReachableMember;

            if (reachableMember != null)
            {
                Remove(reachableMember.Member.UniqueAddress);
                return;
            }
            var memberRemoved = message as ClusterEvent.MemberRemoved;

            if (memberRemoved != null)
            {
                Remove(memberRemoved.Member.UniqueAddress);
                return;
            }

            var leaderChanged = message as ClusterEvent.LeaderChanged;

            if (leaderChanged != null)
            {
                _leader = leaderChanged.Leader != null && leaderChanged.Leader.Equals(SelfAddress);
                if (_leader)
                {
                    foreach (var node in _pendingUnreachable)
                    {
                        Down(node.Address);
                    }
                    _pendingUnreachable = ImmutableHashSet.Create <UniqueAddress>();
                }
                return;
            }

            var unreachableTimeout = message as AutoDown.UnreachableTimeout;

            if (unreachableTimeout != null)
            {
                if (_scheduledUnreachable.ContainsKey(unreachableTimeout.Node))
                {
                    _scheduledUnreachable = _scheduledUnreachable.Remove(unreachableTimeout.Node);
                    DownOrAddPending(unreachableTimeout.Node);
                }
                return;
            }
        }
示例#35
0
        /// <summary>
        /// If given <param name="type"/> is an <see cref="EcmaType"/> precompute its mangled type name
        /// along with all the other types from the same module as <param name="type"/>.
        /// Otherwise, it is a constructed type and to the EcmaType's mangled name we add a suffix to
        /// show what kind of constructed type it is (e.g. appending __Array for an array type).
        /// </summary>
        /// <param name="type">Type to mangled</param>
        /// <returns>Mangled name for <param name="type"/>.</returns>
        private string ComputeMangledTypeName(TypeDesc type)
        {
            if (type is EcmaType)
            {
                EcmaType ecmaType = (EcmaType)type;

                string prependAssemblyName = SanitizeName(((EcmaAssembly)ecmaType.EcmaModule).GetName().Name);

                var deduplicator = new HashSet <string>();

                // Add consistent names for all types in the module, independent on the order in which
                // they are compiled
                lock (this)
                {
                    if (!_mangledTypeNames.ContainsKey(type))
                    {
                        foreach (MetadataType t in ((EcmaType)type).EcmaModule.GetAllTypes())
                        {
                            string name = t.GetFullName();

                            // Include encapsulating type
                            DefType containingType = t.ContainingType;
                            while (containingType != null)
                            {
                                name           = containingType.GetFullName() + "_" + name;
                                containingType = containingType.ContainingType;
                            }

                            name = SanitizeName(name, true);
                            name = prependAssemblyName + "_" + name;

                            // Ensure that name is unique and update our tables accordingly.
                            name = DisambiguateName(name, deduplicator);
                            deduplicator.Add(name);
                            _mangledTypeNames = _mangledTypeNames.Add(t, name);
                        }
                    }
                }

                return(_mangledTypeNames[type]);
            }

            string mangledName;

            switch (type.Category)
            {
            case TypeFlags.Array:
            case TypeFlags.SzArray:
                mangledName = GetMangledTypeName(((ArrayType)type).ElementType) + "__";

                if (type.IsMdArray)
                {
                    mangledName += NestMangledName("ArrayRank" + ((ArrayType)type).Rank.ToStringInvariant());
                }
                else
                {
                    mangledName += NestMangledName("Array");
                }
                break;

            case TypeFlags.ByRef:
                mangledName = GetMangledTypeName(((ByRefType)type).ParameterType) + NestMangledName("ByRef");
                break;

            case TypeFlags.Pointer:
                mangledName = GetMangledTypeName(((PointerType)type).ParameterType) + NestMangledName("Pointer");
                break;

            default:
                // Case of a generic type. If `type' is a type definition we use the type name
                // for mangling, otherwise we use the mangling of the type and its generic type
                // parameters, e.g. A <B> becomes A_<___B_>_ in RyuJIT compilation, or A_A___B_V_
                // in C++ compilation.
                var typeDefinition = type.GetTypeDefinition();
                if (typeDefinition != type)
                {
                    mangledName = GetMangledTypeName(typeDefinition);

                    var    inst = type.Instantiation;
                    string mangledInstantiation = "";
                    for (int i = 0; i < inst.Length; i++)
                    {
                        string instArgName = GetMangledTypeName(inst[i]);
                        if (i > 0)
                        {
                            mangledInstantiation += "__";
                        }

                        mangledInstantiation += instArgName;
                    }
                    mangledName += NestMangledName(mangledInstantiation);
                }
                else
                {
                    mangledName = SanitizeName(((DefType)type).GetFullName(), true);
                }
                break;
            }

            lock (this)
            {
                // Ensure that name is unique and update our tables accordingly.
                if (!_mangledTypeNames.ContainsKey(type))
                {
                    _mangledTypeNames = _mangledTypeNames.Add(type, mangledName);
                }
            }

            return(mangledName);
        }
示例#36
0
        private Transaction GetPreviousTransaction(Block block, int txIndex, TxOutputKey prevTxOutputKey, ImmutableDictionary<UInt256, UnspentTx> utxo, ImmutableDictionary<UInt256, ImmutableHashSet<int>> newTransactions)
        {
            if (newTransactions.ContainsKey(prevTxOutputKey.TxHash))
            {
                var eligible = newTransactions[prevTxOutputKey.TxHash].Where(x => x < txIndex).ToList();
                if (eligible.Count > 0)
                {
                    var max = eligible.Max();

                    if (max >= block.Transactions.Length)
                        throw new Exception();

                    var prevTx1 = block.Transactions[max];
                    if (prevTx1.Hash != prevTxOutputKey.TxHash)
                        throw new Exception();

                    return prevTx1;
                }
            }

            // find previous transaction
            if (!utxo.ContainsKey(prevTxOutputKey.TxHash))
                throw new MissingDataException(DataType.Transaction, prevTxOutputKey.TxHash);

            var prevTxKey = utxo[prevTxOutputKey.TxHash].ToTxKey();

            var prevTx2 = this.CacheContext.GetTransaction(prevTxKey);
            if (prevTx2.Hash != prevTxOutputKey.TxHash)
                throw new Exception();

            return prevTx2;
        }