private static void AddEvent(string command) { var currentEvent = new Event(DateTime.Now, "title", "location"); ///GetParameters(command, "AddEvent", out date, out title, out location); var events = new MultiDictionary<string, Event>(true); ///added that to make it stop crashing too events.Add("title", currentEvent); }
public Catalog() { this.name = new MultiDictionary<string, Content>(true); this.price = new OrderedBag<Content>(); this.producer = new MultiDictionary<string, Content>(true); this.nameAndProducer = new MultiDictionary<Tuple<string, string>, Content>(true); }
static void Main() { PhoneBookByName = new MultiDictionary<string, Entry>(true); PhoneBookByNameAndTown = new MultiDictionary<Tuple<string, string>, Entry>(true); using (StreamReader phonesReader = new StreamReader(@"../../Phones.txt")) { string phoneInfo = phonesReader.ReadLine(); while (phoneInfo != null) { ParsePhoneInfo(phoneInfo); phoneInfo = phonesReader.ReadLine(); } } using (StreamReader commandsReader = new StreamReader(@"../../commands.txt")) { string command = commandsReader.ReadLine(); while (command != null) { List<Entry> enriesFound = ExecuteCommand(command); // warning printing can take a long time // PrintEntries(command, enriesFound); // Console.ReadLine(); command = commandsReader.ReadLine(); } } }
private static void ReadContactsFromFile(string file, MultiDictionary<string, string> contactsName, MultiDictionary<string, string> contactsTown) { StreamReader reader = new StreamReader(file); string line = reader.ReadLine(); using (reader) { while (line != null) { var details = line.Split('|'); string names = details[0].Trim(); string town = details[1].Trim(); string phone = details[2].Trim(); contactsTown.Add(town, phone); var namesSeparated = names.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (var name in namesSeparated) { contactsName.Add(name, phone); } line = reader.ReadLine(); } } }
private MultiDictionary<string, TypeParameterSymbol> CreateTypeParameterMap() { var map = new MultiDictionary<string, TypeParameterSymbol>(); switch (_crefSyntax.Kind()) { case SyntaxKind.TypeCref: { AddTypeParameters(((TypeCrefSyntax)_crefSyntax).Type, map); break; } case SyntaxKind.QualifiedCref: { QualifiedCrefSyntax qualifiedCrefSyntax = ((QualifiedCrefSyntax)_crefSyntax); AddTypeParameters(qualifiedCrefSyntax.Member, map); AddTypeParameters(qualifiedCrefSyntax.Container, map); break; } case SyntaxKind.NameMemberCref: case SyntaxKind.IndexerMemberCref: case SyntaxKind.OperatorMemberCref: case SyntaxKind.ConversionOperatorMemberCref: { AddTypeParameters((MemberCrefSyntax)_crefSyntax, map); break; } default: { throw ExceptionUtilities.UnexpectedValue(_crefSyntax.Kind()); } } return map; }
public PhoneBook() { this.FirstNames = new MultiDictionary<string, Record>(true); this.MiddleNames = new MultiDictionary<string, Record>(true); this.LastNames = new MultiDictionary<string, Record>(true); this.Towns = new MultiDictionary<string, Record>(true); }
private readonly MultiDictionary<ISentenceForm, Fact> _sentencesByForm; //TODO: Immutable #endregion Fields #region Constructors private ImmutableConstantChecker(ImmutableSentenceFormModel sentenceModel, MultiDictionary<ISentenceForm, Fact> sentencesByForm) { Debug.Assert(sentenceModel.ConstantSentenceForms.IsSupersetOf(sentencesByForm.Keys)); _sentenceModel = sentenceModel; _sentencesByForm = sentencesByForm; _allSentences = sentencesByForm.SelectMany(s => s.Value).ToImmutableHashSet(); }
private MultiDictionary<string, TypeParameterSymbol> CreateTypeParameterMap() { var map = new MultiDictionary<string, TypeParameterSymbol>(); switch (_crefSyntax.Kind()) { case SyntaxKind.TypeCref: { AddTypeParameters(((TypeCrefSyntax)_crefSyntax).Type, map); break; } case SyntaxKind.QualifiedCref: { QualifiedCrefSyntax qualifiedCrefSyntax = ((QualifiedCrefSyntax)_crefSyntax); AddTypeParameters(qualifiedCrefSyntax.Member, map); AddTypeParameters(qualifiedCrefSyntax.Container, map); break; } case SyntaxKind.NameMemberCref: case SyntaxKind.IndexerMemberCref: case SyntaxKind.OperatorMemberCref: case SyntaxKind.ConversionOperatorMemberCref: { AddTypeParameters((MemberCrefSyntax)_crefSyntax, map); break; } default: { Debug.Assert(false, "Unexpected cref syntax kind " + _crefSyntax.Kind()); break; } } return map; }
public IndexedArgInstances(List<ArgInstance> instances) { _mandatoryFullNames = new HashSet<string>(); _argInstancesByName = new MultiDictionary<string, ArgInstance>(); HashSet<string> tempNames = new HashSet<string>(); foreach (ArgInstance currentInstance in instances) { if (currentInstance.Arg.IsMandatory) { _mandatoryFullNames.Add(currentInstance.FullName); } tempNames.Clear(); tempNames.Add(currentInstance.Name); tempNames.Add(currentInstance.FullName); if (currentInstance.ShortName != null) { tempNames.Add(currentInstance.ShortName); } foreach (string name in tempNames) { _argInstancesByName.Add(name, currentInstance); } } }
public void RefreshSkillShop(int _idx) { m_CurNpcIdx = _idx; AsUserEntity user = AsUserInfo.Instance.GetCurrentUserEntity(); eCLASS __class = user.GetProperty<eCLASS>(eComponentProperty.CLASS); m_dicLearnedSkill = SkillBook.Instance.dicCurSkill; List<Tbl_SkillBook_Record> list = AsTableManager.Instance.GetTbl_SkillBook_RecordsByClass(_idx, __class); m_mdicSkillBookBySkillIdx = TransferToIdxMultidic(list); m_ChoiceTypeDic.Clear(); m_BaseTypeDic.Clear(); foreach(int key in m_mdicSkillBookBySkillIdx.Keys) { foreach(Tbl_SkillBook_Record record in m_mdicSkillBookBySkillIdx[key]) { Tbl_Skill_Record skill = AsTableManager.Instance.GetTbl_Skill_Record(record.Skill1_Index); if(skill.Skill_Type != eSKILL_TYPE.Base) DecideSkillGoodsGroup(record); } } SortShopDictionary(); }
private void AddTypeParameters(TypeSyntax typeSyntax, MultiDictionary<string, TypeParameterSymbol> map) { switch (typeSyntax.Kind()) { case SyntaxKind.AliasQualifiedName: AddTypeParameters(((AliasQualifiedNameSyntax)typeSyntax).Name, map); break; case SyntaxKind.QualifiedName: // NOTE: Dev11 does not warn about duplication, it just matches parameter types to the // *last* type parameter with the same name. That's why we're iterating backwards. QualifiedNameSyntax qualifiedNameSyntax = (QualifiedNameSyntax)typeSyntax; AddTypeParameters(qualifiedNameSyntax.Right, map); AddTypeParameters(qualifiedNameSyntax.Left, map); break; case SyntaxKind.GenericName: AddTypeParameters((GenericNameSyntax)typeSyntax, map); break; case SyntaxKind.IdentifierName: case SyntaxKind.PredefinedType: break; default: Debug.Assert(false, "Unexpected type syntax kind " + typeSyntax.Kind()); break; } }
// generate nodes for symbols that share the same name, and all their descendants private static void GenerateSourceNodes( string name, int parentIndex, MultiDictionary<string, ISymbol>.ValueSet symbolsWithSameName, List<Node> list, Action<ISymbol, MultiDictionary<string, ISymbol>> lookup) { var node = new Node(name, parentIndex); var nodeIndex = list.Count; list.Add(node); var symbolMap = AllocateSymbolMap(); try { // Add all child members foreach (var symbol in symbolsWithSameName) { lookup(symbol, symbolMap); } foreach (var kvp in symbolMap) { GenerateSourceNodes(kvp.Key, nodeIndex, kvp.Value, list, lookup); } } finally { FreeSymbolMap(symbolMap); } }
public PhonebookRepository() { this.dictByFirstName = new MultiDictionary<string, PhonebookEntry>(true); this.dictByMiddleName = new MultiDictionary<string, PhonebookEntry>(true); this.dictByLastName = new MultiDictionary<string, PhonebookEntry>(true); this.dictByNickname = new MultiDictionary<string, PhonebookEntry>(true); }
public void Remove() { MultiDictionary<string, string> dictionary = new MultiDictionary<string, string>(StringComparer.OrdinalIgnoreCase); dictionary.Add("x", "x1"); dictionary.Add("x", "x2"); dictionary.Add("y", "y1"); Assert.Equal(true, dictionary.Remove("x", "x1")); Assert.Equal(2, dictionary.KeyCount); Assert.Equal(2, dictionary.ValueCount); Assert.Equal(true, dictionary.Remove("x", "x2")); Assert.Equal(1, dictionary.KeyCount); Assert.Equal(1, dictionary.ValueCount); Assert.Equal(true, dictionary.Remove("y", "y1")); Assert.Equal(0, dictionary.KeyCount); Assert.Equal(0, dictionary.ValueCount); dictionary.Add("x", "x1"); dictionary.Add("x", "x2"); Assert.Equal(true, dictionary.Remove("x", "x2")); Assert.Equal(1, dictionary.KeyCount); Assert.Equal(1, dictionary.ValueCount); }
public Phonebook() { this.byFirstName = new MultiDictionary<string, PhonebookEntry>(AllowDuplicates); this.byMiddleName = new MultiDictionary<string, PhonebookEntry>(AllowDuplicates); this.byLastName = new MultiDictionary<string, PhonebookEntry>(AllowDuplicates); this.byNickname = new MultiDictionary<string, PhonebookEntry>(AllowDuplicates); }
public ShoppingCenter() { productsByName = new MultiDictionary<string, Product>(true); nameAndProducer = new MultiDictionary<string, Product>(true); productsByPrice = new OrderedMultiDictionary<decimal, Product>(true); productsByProducer = new MultiDictionary<string, Product>(true); }
static void Main() { #if DEBUG Console.SetIn(new System.IO.StreamReader("../../input.txt")); #endif var input = Console.ReadLine(); // Task 4 var set = new MultiDictionary<char, int>(true); for (int i = 0; i < input.Length; i++) set[input[i]].Add(i); var result = Factorial(input.Length); foreach (var pair in set) result /= Factorial(pair.Value.Count); // Catalan Numbers int n = input.Length; double number = 1; for (int i = 2; i <= n; i++) number *= (4 * i - 2) / (1.0 + i); Console.WriteLine((BigInteger)number * result); }
internal WithPrimaryConstructorParametersBinder(MethodSymbol primaryCtor, Binder next) : base(next) { Debug.Assert((object)primaryCtor != null); this.primaryCtor = primaryCtor; var parameters = primaryCtor.Parameters; var definitionMap = new SmallDictionary<string, ParameterSymbol>(); for (int i = parameters.Length - 1; i >= 0; i--) { var parameter = parameters[i]; definitionMap[parameter.Name] = parameter; } this.definitionMap = definitionMap; var parameterMap = new MultiDictionary<string, ParameterSymbol>(parameters.Length, EqualityComparer<string>.Default); foreach (var parameter in parameters) { parameterMap.Add(parameter.Name, parameter); } this.parameterMap = parameterMap; }
public Data(int numberOfSectors) { carros_inpark = new Dictionary<IVehicle, string>(); park = new Dictionary<string, IVehicle>(); números = new Dictionary<string, IVehicle>(); d = new Dictionary<IVehicle, DateTime>(); ow = new MultiDictionary<string, IVehicle>(false); count = new int[numberOfSectors]; }
protected FastInvokerBase(Type type) { ObjectType = type; MethodNameCache = new MultiDictionary<string, MethodInfo>(false); type.GetMethods(_methodBindingFlags).Each(method => MethodNameCache.Add(method.Name, method)); }
private static void ListEvents(string command) { int pipeIndex = command.IndexOf('|'); var events = new MultiDictionary<string, Event>(true); /// added that to make it stop crashing too DateTime date = GetDate(command, "ListEvents"); string countString = command.Substring(pipeIndex + 1); int count = int.Parse(countString); /// events.ListEvents(date,count); commented that to make it build }
public PhoneBook(List<PhoneRecord> phoneRecords) { names = new MultiDictionary<string, PhoneRecord>(true); towns = new MultiDictionary<string, PhoneRecord>(true); phones = new MultiDictionary<string, PhoneRecord>(true); FillLists(phoneRecords); }
private readonly OrderedMultiDictionary<string, Product> productsByTitleAndPrice; // title|price #endregion Fields #region Constructors public Database() { this.productsById = new Dictionary<string, Product>(); this.productsByTitle = new MultiDictionary<string, Product>(true); this.productsByTitleAndPrice = new OrderedMultiDictionary<string, Product>(true); this.productsBySupplierAndPrice = new OrderedMultiDictionary<string, Product>(true); this.productsByPrice = new OrderedMultiDictionary<decimal, Product>(true); }
public Catalog() { bool allowDuplicateValues = true; this.title = new OrderedMultiDictionary<string, IContent>(allowDuplicateValues); this.url = new MultiDictionary<string, IContent>(allowDuplicateValues); }
public TicketCatalog() { this.allTickets = new Dictionary<string, Ticket>(); this.allTicketsByRoute = new MultiDictionary<string, Ticket>(true); this.allTicketsByDepartureDateTime = new OrderedMultiDictionary<DateTime, Ticket>(true); this.AirTicketsCount = 0; this.BusTicketsCount = 0; this.TrainTicketsCount = 0; }
public VehicleParkData(int numberOfSectors) { this.parkedCarsInSectroAndPlace = new Dictionary<IVehicle, string>(); this.parkedSectorsAndPlaces = new Dictionary<string, IVehicle>(); this.parkedLicensePlates = new Dictionary<string, IVehicle>(); this.expectedTimePerVehicle = new Dictionary<IVehicle, DateTime>(); this.ownersAndTheirVehicles = new MultiDictionary<string, IVehicle>(false); this.emptySlotsPerSector = new int[numberOfSectors]; }
public ParseResult CreateParseResult(bool successfull, params string[] keyValues) { MultiDictionary<string, string> parsedValues = new MultiDictionary<string, string>(); for (int i = 0; i < keyValues.Length / 2; ++i) { parsedValues.Add(keyValues[i * 2], keyValues[i * 2 + 1]); } return new ParseResult(successfull, parsedValues, ExecutionLog.CreateErrorLog()); }
public PhoneBook() { FirstNames = new MultiDictionary<string, PhoneBookEntry>(true); MiddleNames = new MultiDictionary<string, PhoneBookEntry>(true); LastNames = new MultiDictionary<string, PhoneBookEntry>(true); NickNames = new MultiDictionary<string, PhoneBookEntry>(true); Towns = new MultiDictionary<string, PhoneBookEntry>(true); }
/// <summary> /// Contant sentences are those that do not have a dependency on 'true' or 'does' facts /// </summary> /// <param name="sentenceForms"></param> /// <param name="dependencyGraph"></param> /// <returns></returns> private static ImmutableHashSet<ISentenceForm> GetConstantSentenceForms(ImmutableHashSet<ISentenceForm> sentenceForms, MultiDictionary<ISentenceForm, ISentenceForm> dependencyGraph) { MultiDictionary<ISentenceForm, ISentenceForm> augmentedGraph = AugmentGraphWithLanguageRules(dependencyGraph, sentenceForms); ImmutableHashSet<ISentenceForm> changingSentenceForms = DependencyGraphs.GetMatchingAndDownstream(sentenceForms, augmentedGraph, d => SentenceForms.TruePred(d) || SentenceForms.DoesPred(d)); return sentenceForms.SymmetricExcept(changingSentenceForms).ToImmutableHashSet(); }
public WithQueryLambdaParametersBinder(LambdaSymbol lambdaSymbol, RangeVariableMap rangeVariableMap, Binder next) : base(lambdaSymbol, next) { _rangeVariableMap = rangeVariableMap; _parameterMap = new MultiDictionary<string, RangeVariableSymbol>(); foreach (var qv in rangeVariableMap.Keys) { _parameterMap.Add(qv.Name, qv); } }
/// <summary> /// Checks is multi dictionary is not empty. /// </summary> /// <typeparam name="TKey">Type of MultiDictionary key</typeparam> /// <typeparam name="TValue">Type of MultiDictionary value</typeparam> /// <param name="source">this</param> /// <returns>True if not empty, False otherwise</returns> public static bool IsNotEmpty <TKey, TValue>(this MultiDictionary <TKey, TValue> source) { Preconditions.IsNotNull(source, () => new ArgumentNullException("source")); return(!source.IsEmpty); }
/// <summary> /// Creates a new Graph Collection. /// </summary> public GraphCollection() { _graphs = new MultiDictionary <Uri, IGraph>(u => (u != null ? u.GetEnhancedHashCode() : DefaultGraphID), true, new UriComparer(), MultiDictionaryMode.AVL); }
private ImmutableArray <BuilderNode> GenerateUnsortedNodes(ArrayBuilder <ExtensionMethodInfo> complexBuilder, MultiDictionary <string, ExtensionMethodInfo> simpleTypeNameToMethodMap) { var unsortedNodes = ArrayBuilder <BuilderNode> .GetInstance(); unsortedNodes.Add(BuilderNode.RootNode); AddUnsortedNodes(unsortedNodes, simpleTypeNameToMethodMap, complexBuilder, parentNode: _rootNode, parentIndex: 0, fullyQualifiedContainerName: _containsExtensionsMethod ? "" : null); return(unsortedNodes.ToImmutableAndFree()); }
/// <summary> /// Compare the root elements and, if they are equal, match up children by shallow equality, recursing on each pair. /// </summary> /// <returns>True if the elements are equal, false otherwise (in which case, firstMismatch will try to indicate a point of disagreement).</returns> private static bool CheckEqual(XElement expectedRoot, XElement actualRoot, IEqualityComparer <XElement> shallowComparer, out Tuple <XElement, XElement> firstMismatch) { Assert.NotNull(expectedRoot); Assert.NotNull(actualRoot); Assert.NotNull(shallowComparer); Tuple <XElement, XElement> rootPair = new Tuple <XElement, XElement>(expectedRoot, actualRoot); if (!shallowComparer.Equals(expectedRoot, actualRoot)) { firstMismatch = rootPair; return(false); } Stack <Tuple <XElement, XElement> > stack = new Stack <Tuple <XElement, XElement> >(); stack.Push(rootPair); while (stack.Count > 0) { Tuple <XElement, XElement> pair = stack.Pop(); firstMismatch = pair; // Will be overwritten if this pair is a match. Debug.Assert(shallowComparer.Equals(pair.Item1, pair.Item2)); // Shouldn't have been pushed otherwise. XElement[] children1 = pair.Item1.Elements().ToArray(); MultiDictionary <XElement, XElement> children2Dict = new MultiDictionary <XElement, XElement>(shallowComparer); int children2Count = 0; foreach (XElement child in pair.Item2.Elements()) { children2Dict.Add(child, child); children2Count++; } if (children1.Length != children2Count) { return(false); } HashSet <XElement> children2Used = new HashSet <XElement>(ReferenceEqualityComparer.Instance); foreach (XElement child1 in children1) { XElement child2 = null; foreach (var candidate in children2Dict[child1]) { if (!children2Used.Contains(candidate)) { child2 = candidate; break; } } if (child2 == null) { return(false); } else { children2Used.Add(child2); stack.Push(new Tuple <XElement, XElement>(child1, child2)); } } if (children2Used.Count < children1.Length) { return(false); } } firstMismatch = null; return(true); }
public BiDictionary(bool allowDuplicateValues) { this.byKey1 = new MultiDictionary <TKey1, Entry>(allowDuplicateValues); this.byKey2 = new MultiDictionary <TKey2, Entry>(allowDuplicateValues); this.byKey1Key2 = new MultiDictionary <Tuple <TKey1, TKey2>, Entry>(allowDuplicateValues); }
public SqlObjectsIndex() { ConceptsBySqlName = new MultiDictionary <string, IConceptInfo>(StringComparer.InvariantCultureIgnoreCase); }
/// <summary> /// Transfers the CXSMILES state onto the CDK atom/molecule data-structures. /// </summary> /// <param name="bldr">chem-object builder</param> /// <param name="atoms">atoms parsed from the molecule or reaction. Reaction molecules are list left to right.</param> /// <param name="atomToMol">look-up of atoms to molecules when connectivity/sgroups need modification</param> /// <param name="cxstate">the CXSMILES state to read from</param> private void AssignCxSmilesInfo(IChemObjectBuilder bldr, IChemObject chemObj, List <IAtom> atoms, Dictionary <IAtom, IAtomContainer> atomToMol, CxSmilesState cxstate) { // atom-labels - must be done first as we replace atoms if (cxstate.atomLabels != null) { foreach (var e in cxstate.atomLabels) { // bounds check if (e.Key >= atoms.Count) { continue; } var old = atoms[e.Key]; var pseudo = bldr.NewPseudoAtom(); var val = e.Value; // specialised label handling if (val.EndsWith("_p", StringComparison.Ordinal)) // pseudo label { val = val.Substring(0, val.Length - 2); } else if (val.StartsWith("_AP", StringComparison.Ordinal)) // attachment point { pseudo.AttachPointNum = ParseIntSafe(val.Substring(3)); } pseudo.Label = val; pseudo.AtomicNumber = 0; pseudo.ImplicitHydrogenCount = 0; var mol = atomToMol[old]; AtomContainerManipulator.ReplaceAtomByAtom(mol, old, pseudo); atomToMol.Add(pseudo, mol); atoms[e.Key] = pseudo; } } // atom-values - set as comment, mirrors Molfile reading behavior if (cxstate.atomValues != null) { foreach (var e in cxstate.atomValues) { atoms[e.Key].SetProperty(CDKPropertyName.Comment, e.Value); } } // atom-coordinates if (cxstate.atomCoords != null) { var numAtoms = atoms.Count; var numCoords = cxstate.atomCoords.Count; var lim = Math.Min(numAtoms, numCoords); if (cxstate.coordFlag) { for (int i = 0; i < lim; i++) { atoms[i].Point3D = new Vector3( cxstate.atomCoords[i][0], cxstate.atomCoords[i][1], cxstate.atomCoords[i][2]); } } else { for (int i = 0; i < lim; i++) { atoms[i].Point2D = new Vector2( cxstate.atomCoords[i][0], cxstate.atomCoords[i][1]); } } } // atom radicals if (cxstate.atomRads != null) { foreach (var e in cxstate.atomRads) { // bounds check if (e.Key >= atoms.Count) { continue; } int count = 0; var aa = e.Value; switch (e.Value) { case CxSmilesState.Radical.Monovalent: count = 1; break; // no distinction in CDK between singled/triplet case CxSmilesState.Radical.Divalent: case CxSmilesState.Radical.DivalentSinglet: case CxSmilesState.Radical.DivalentTriplet: count = 2; break; // no distinction in CDK between doublet/quartet case CxSmilesState.Radical.Trivalent: case CxSmilesState.Radical.TrivalentDoublet: case CxSmilesState.Radical.TrivalentQuartet: count = 3; break; } var atom = atoms[e.Key]; var mol = atomToMol[atom]; while (count-- > 0) { mol.SingleElectrons.Add(bldr.NewSingleElectron(atom)); } } } var sgroupMap = new MultiDictionary <IAtomContainer, Sgroup>(); // positional-variation if (cxstate.positionVar != null) { foreach (var e in cxstate.positionVar) { var sgroup = new Sgroup { Type = SgroupType.ExtMulticenter }; var beg = atoms[e.Key]; var mol = atomToMol[beg]; var bonds = mol.GetConnectedBonds(beg); if (bonds.Count() == 0) { continue; // bad } sgroup.Add(beg); sgroup.Add(bonds.First()); foreach (var endpt in e.Value) { sgroup.Add(atoms[endpt]); } sgroupMap.Add(mol, sgroup); } } // data sgroups if (cxstate.dataSgroups != null) { foreach (var dsgroup in cxstate.dataSgroups) { if (dsgroup.Field != null && dsgroup.Field.StartsWith("cdk:", StringComparison.Ordinal)) { chemObj.SetProperty(dsgroup.Field, dsgroup.Value); } } } // polymer Sgroups if (cxstate.sgroups != null) { foreach (var psgroup in cxstate.sgroups) { var sgroup = new Sgroup(); var atomset = new HashSet <IAtom>(); IAtomContainer mol = null; foreach (var idx in psgroup.AtomSet) { if (idx >= atoms.Count) { continue; } var atom = atoms[idx]; var amol = atomToMol[atom]; if (mol == null) { mol = amol; } else if (amol != mol) { goto C_PolySgroup; } atomset.Add(atom); } if (mol == null) { continue; } foreach (var atom in atomset) { foreach (var bond in mol.GetConnectedBonds(atom)) { if (!atomset.Contains(bond.GetOther(atom))) { sgroup.Add(bond); } } sgroup.Add(atom); } sgroup.Subscript = psgroup.Subscript; sgroup.PutValue(SgroupKey.CtabConnectivity, psgroup.Supscript); switch (psgroup.Type) { case "n": sgroup.Type = SgroupType.CtabStructureRepeatUnit; break; case "mon": sgroup.Type = SgroupType.CtabMonomer; break; case "mer": sgroup.Type = SgroupType.CtabMer; break; case "co": sgroup.Type = SgroupType.CtabCopolymer; break; case "xl": sgroup.Type = SgroupType.CtabCrossLink; break; case "mod": sgroup.Type = SgroupType.CtabModified; break; case "mix": sgroup.Type = SgroupType.CtabMixture; break; case "f": sgroup.Type = SgroupType.CtabFormulation; break; case "any": sgroup.Type = SgroupType.CtabAnyPolymer; break; case "gen": sgroup.Type = SgroupType.CtabGeneric; break; case "c": sgroup.Type = SgroupType.CtabComponent; break; case "grf": sgroup.Type = SgroupType.CtabGraft; break; case "alt": sgroup.Type = SgroupType.CtabCopolymer; sgroup.PutValue(SgroupKey.CtabSubType, "ALT"); break; case "ran": sgroup.Type = SgroupType.CtabCopolymer; sgroup.PutValue(SgroupKey.CtabSubType, "RAN"); break; case "blk": sgroup.Type = SgroupType.CtabCopolymer; sgroup.PutValue(SgroupKey.CtabSubType, "BLO"); break; } sgroupMap.Add(mol, sgroup); C_PolySgroup: ; } } // assign Sgroups foreach (var e in sgroupMap) { e.Key.SetCtabSgroups(new List <Sgroup>(e.Value)); } }
private async Task AddLocationSpan(Location location, Solution solution, HashSet <ValueTuple <Document, TextSpan> > spanSet, MultiDictionary <Document, HighlightSpan> tagList, HighlightSpanKind kind, CancellationToken cancellationToken) { var span = await GetLocationSpanAsync(solution, location, cancellationToken).ConfigureAwait(false); if (span != null && !spanSet.Contains(span.Value)) { spanSet.Add(span.Value); tagList.Add(span.Value.Item1, new HighlightSpan(span.Value.Item2, kind)); } }
protected override void AssignOutParameters( SyntaxEditor editor, SyntaxNode container, MultiDictionary < SyntaxNode, (SyntaxNode exprOrStatement, ImmutableArray <IParameterSymbol> unassignedParameters)
public Orders() { this.consumers = new MultiDictionary <string, Order>(true); this.ordersByPrices = new OrderedMultiDictionary <double, Order>(true); this.allPrices = new SortedSet <double>(); }
private async Task <IEnumerable <DocumentHighlights> > CreateSpansAsync( Solution solution, ISymbol symbol, IEnumerable <ReferencedSymbol> references, IEnumerable <Location> additionalReferences, IImmutableSet <Document> documentToSearch, CancellationToken cancellationToken) { var spanSet = new HashSet <ValueTuple <Document, TextSpan> >(); var tagMap = new MultiDictionary <Document, HighlightSpan>(); bool addAllDefinitions = true; // Add definitions // Filter out definitions that cannot be highlighted. e.g: alias symbols defined via project property pages. if (symbol.Kind == SymbolKind.Alias && symbol.Locations.Length > 0) { addAllDefinitions = false; if (symbol.Locations.First().IsInSource) { // For alias symbol we want to get the tag only for the alias definition, not the target symbol's definition. await AddLocationSpan(symbol.Locations.First(), solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false); } } // Add references and definitions foreach (var reference in references) { if (addAllDefinitions && ShouldIncludeDefinition(reference.Definition)) { foreach (var location in reference.Definition.Locations) { if (location.IsInSource) { var document = solution.GetDocument(location.SourceTree); // GetDocument will return null for locations in #load'ed trees. // TODO: Remove this check and add logic to fetch the #load'ed tree's // Document once https://github.com/dotnet/roslyn/issues/5260 is fixed. if (document == null) { Debug.Assert(solution.Workspace.Kind == "Interactive"); continue; } if (documentToSearch.Contains(document)) { await AddLocationSpan(location, solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false); } } } } foreach (var referenceLocation in reference.Locations) { var referenceKind = referenceLocation.IsWrittenTo ? HighlightSpanKind.WrittenReference : HighlightSpanKind.Reference; await AddLocationSpan(referenceLocation.Location, solution, spanSet, tagMap, referenceKind, cancellationToken).ConfigureAwait(false); } } // Add additional references foreach (var location in additionalReferences) { await AddLocationSpan(location, solution, spanSet, tagMap, HighlightSpanKind.Reference, cancellationToken).ConfigureAwait(false); } var list = new List <DocumentHighlights>(tagMap.Count); foreach (var kvp in tagMap) { var spans = new List <HighlightSpan>(kvp.Value.Count); foreach (var span in kvp.Value) { spans.Add(span); } list.Add(new DocumentHighlights(kvp.Key, spans)); } return(list); }
private static void FreeSymbolMap(MultiDictionary <string, ISymbol> symbolMap) { symbolMap.Clear(); s_symbolMapPool.Free(symbolMap); }
public Phonebook() { this.recordsByName = new MultiDictionary <HashSet <string>, PhoneRecord>(true); this.recordsByTown = new MultiDictionary <string, PhoneRecord>(true); }
private static Symbol FindExplicitlyImplementedMember( Symbol implementingMember, TypeSymbol explicitInterfaceType, string interfaceMemberName, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax, DiagnosticBag diagnostics) { if ((object)explicitInterfaceType == null) { return(null); } var memberLocation = implementingMember.Locations[0]; var containingType = implementingMember.ContainingType; switch (containingType.TypeKind) { case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: break; default: diagnostics.Add(ErrorCode.ERR_ExplicitInterfaceImplementationInNonClassOrStruct, memberLocation, implementingMember); return(null); } if (!explicitInterfaceType.IsInterfaceType()) { //we'd like to highlight just the type part of the name var explicitInterfaceSyntax = explicitInterfaceSpecifierSyntax.Name; var location = new SourceLocation(explicitInterfaceSyntax); diagnostics.Add(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, location, explicitInterfaceType); return(null); } var explicitInterfaceNamedType = (NamedTypeSymbol)explicitInterfaceType; // 13.4.1: "For an explicit interface member implementation to be valid, the class or struct must name an // interface in its base class list that contains a member ..." MultiDictionary <NamedTypeSymbol, NamedTypeSymbol> .ValueSet set = containingType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics[explicitInterfaceNamedType]; int setCount = set.Count; if (setCount == 0 || !set.Contains(explicitInterfaceNamedType, TypeSymbol.EqualsObliviousNullableModifierMatchesAny)) { //we'd like to highlight just the type part of the name var explicitInterfaceSyntax = explicitInterfaceSpecifierSyntax.Name; var location = new SourceLocation(explicitInterfaceSyntax); if (setCount > 0 && set.Contains(explicitInterfaceNamedType, TypeSymbol.EqualsIgnoringNullableComparer)) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInExplicitlyImplementedInterface, location); } else { diagnostics.Add(ErrorCode.ERR_ClassDoesntImplementInterface, location, implementingMember, explicitInterfaceNamedType); } //do a lookup anyway } var hasParamsParam = implementingMember.HasParamsParameter(); // Setting this flag to true does not imply that an interface member has been successfully implemented. // It just indicates that a corresponding interface member has been found (there may still be errors). var foundMatchingMember = false; Symbol implementedMember = null; foreach (Symbol interfaceMember in explicitInterfaceNamedType.GetMembers(interfaceMemberName)) { // At this point, we know that explicitInterfaceNamedType is an interface. // However, metadata interface members can be static - we ignore them, as does Dev10. if (interfaceMember.Kind != implementingMember.Kind || !interfaceMember.IsImplementableInterfaceMember()) { continue; } if (MemberSignatureComparer.ExplicitImplementationComparer.Equals(implementingMember, interfaceMember)) { foundMatchingMember = true; // Cannot implement accessor directly unless // the accessor is from an indexed property. if (interfaceMember.IsAccessor() && !((MethodSymbol)interfaceMember).IsIndexedPropertyAccessor()) { diagnostics.Add(ErrorCode.ERR_ExplicitMethodImplAccessor, memberLocation, implementingMember, interfaceMember); } else { if (interfaceMember.MustCallMethodsDirectly()) { diagnostics.Add(ErrorCode.ERR_BogusExplicitImpl, memberLocation, implementingMember, interfaceMember); } else if (hasParamsParam && !interfaceMember.HasParamsParameter()) { // Note: no error for !hasParamsParam && interfaceMethod.HasParamsParameter() // Still counts as an implementation. diagnostics.Add(ErrorCode.ERR_ExplicitImplParams, memberLocation, implementingMember, interfaceMember); } implementedMember = interfaceMember; break; } } } if (!foundMatchingMember) { // CONSIDER: we may wish to suppress this error in the event that another error // has been reported about the signature. diagnostics.Add(ErrorCode.ERR_InterfaceMemberNotFound, memberLocation, implementingMember); } // Make sure implemented member is accessible if ((object)implementedMember != null) { HashSet <DiagnosticInfo> useSiteDiagnostics = null; if (!AccessCheck.IsSymbolAccessible(implementedMember, implementingMember.ContainingType, ref useSiteDiagnostics, throughTypeOpt: null)) { diagnostics.Add(ErrorCode.ERR_BadAccess, memberLocation, implementedMember); } else { switch (implementedMember.Kind) { case SymbolKind.Property: var propertySymbol = (PropertySymbol)implementedMember; checkAccessorIsAccessibleIfImplementable(propertySymbol.GetMethod); checkAccessorIsAccessibleIfImplementable(propertySymbol.SetMethod); break; case SymbolKind.Event: var eventSymbol = (EventSymbol)implementedMember; checkAccessorIsAccessibleIfImplementable(eventSymbol.AddMethod); checkAccessorIsAccessibleIfImplementable(eventSymbol.RemoveMethod); break; } void checkAccessorIsAccessibleIfImplementable(MethodSymbol accessor) { if (accessor.IsImplementable() && !AccessCheck.IsSymbolAccessible(accessor, implementingMember.ContainingType, ref useSiteDiagnostics, throughTypeOpt: null)) { diagnostics.Add(ErrorCode.ERR_BadAccess, memberLocation, accessor); } } } diagnostics.Add(memberLocation, useSiteDiagnostics); } return(implementedMember); }
public Catalog() { this.title = new OrderedMultiDictionary <string, IContent>(true); this.url = new MultiDictionary <string, IContent>(true); }
/// <summary> /// Optimizes local functions such that if a local function only references other local functions without closures, it itself doesn't need a closure. /// </summary> private void RemoveUnneededReferences() { // Note: methodGraph is the inverse of the dependency graph var methodGraph = new MultiDictionary <MethodSymbol, MethodSymbol>(); var capturesThis = new HashSet <MethodSymbol>(); var capturesVariable = new HashSet <MethodSymbol>(); var visitStack = new Stack <MethodSymbol>(); foreach (var methodKvp in CapturedVariablesByLambda) { foreach (var value in methodKvp.Value) { var method = value as MethodSymbol; if (method != null) { methodGraph.Add(method, methodKvp.Key); } else if (value == _topLevelMethod.ThisParameter) { if (capturesThis.Add(methodKvp.Key)) { visitStack.Push(methodKvp.Key); } } else if (capturesVariable.Add(methodKvp.Key) && !capturesThis.Contains(methodKvp.Key)) // if capturesThis contains methodKvp, it's already in the stack. { visitStack.Push(methodKvp.Key); } } } while (visitStack.Count > 0) { var current = visitStack.Pop(); var setToAddTo = capturesVariable.Contains(current) ? capturesVariable : capturesThis; foreach (var capturesCurrent in methodGraph[current]) { if (setToAddTo.Add(capturesCurrent)) { visitStack.Push(capturesCurrent); } } } var capturedVariablesNew = new MultiDictionary <Symbol, CSharpSyntaxNode>(); foreach (var old in CapturedVariables) { var method = old.Key as MethodSymbol; // don't add if it's a method that only captures 'this' if (method == null || capturesVariable.Contains(method)) { foreach (var oldValue in old.Value) { capturedVariablesNew.Add(old.Key, oldValue); } } } CapturedVariables = capturedVariablesNew; var capturedVariablesByLambdaNew = new MultiDictionary <MethodSymbol, Symbol>(); foreach (var old in CapturedVariablesByLambda) { if (capturesVariable.Contains(old.Key)) { foreach (var oldValue in old.Value) { capturedVariablesByLambdaNew.Add(old.Key, oldValue); } } else if (capturesThis.Contains(old.Key)) { capturedVariablesByLambdaNew.Add(old.Key, _topLevelMethod.ThisParameter); } } CapturedVariablesByLambda = capturedVariablesByLambdaNew; }
private void ProcessProjectChange(Solution solution, ProjectId projectId) { this.AssertIsForeground(); // Remove anything we have associated with this project. _projectToInstalledPackageAndVersion.TryRemove(projectId, out var projectState); var project = solution.GetProject(projectId); if (project == null) { // Project was removed. Nothing needs to be done. return; } // We really only need to know the NuGet status for managed language projects. // Also, the NuGet APIs may throw on some projects that don't implement the // full set of DTE APIs they expect. So we filter down to just C# and VB here // as we know these languages are safe to build up this index for. if (project.Language != LanguageNames.CSharp && project.Language != LanguageNames.VisualBasic) { return; } // Project was changed in some way. Let's go find the set of installed packages for it. var dteProject = _workspace.TryGetDTEProject(projectId); if (dteProject == null) { // Don't have a DTE project for this project ID. not something we can query NuGet for. return; } var installedPackages = new MultiDictionary <string, string>(); var isEnabled = false; // Calling into NuGet. Assume they may fail for any reason. try { var installedPackageMetadata = _packageServices.GetInstalledPackages(dteProject); foreach (var metadata in installedPackageMetadata) { if (metadata.VersionString != null) { installedPackages.Add(metadata.Id, metadata.VersionString); } } isEnabled = true; } catch (ArgumentException e) when(IsKnownNugetIssue(e)) { // Nuget may throw an ArgumentException when there is something about the project // they do not like/support. } catch (InvalidOperationException e) when(e.StackTrace.Contains("NuGet.PackageManagement.VisualStudio.NetCorePackageReferenceProject.GetPackageSpecsAsync")) { // NuGet throws an InvalidOperationException if details // for the project fail to load. We don't need to report // these, and can assume that this will work on a future // project change // This should be removed with https://github.com/dotnet/roslyn/issues/33187 } catch (Exception e) when(FatalError.ReportWithoutCrash(e)) { } var state = new ProjectState(isEnabled, installedPackages); _projectToInstalledPackageAndVersion.AddOrUpdate( projectId, state, (_1, _2) => state); }
internal PEEventSymbol( PEModuleSymbol moduleSymbol, PENamedTypeSymbol containingType, EventDefinitionHandle handle, PEMethodSymbol addMethod, PEMethodSymbol removeMethod, MultiDictionary <string, PEFieldSymbol> privateFieldNameToSymbols) { Debug.Assert((object)moduleSymbol != null); Debug.Assert((object)containingType != null); Debug.Assert(!handle.IsNil); Debug.Assert((object)addMethod != null); Debug.Assert((object)removeMethod != null); _addMethod = addMethod; _removeMethod = removeMethod; _handle = handle; _containingType = containingType; EventAttributes mdFlags = 0; EntityHandle eventType = default(EntityHandle); try { var module = moduleSymbol.Module; module.GetEventDefPropsOrThrow(handle, out _name, out mdFlags, out eventType); } catch (BadImageFormatException mrEx) { if ((object)_name == null) { _name = string.Empty; } _lazyUseSiteDiagnostic = new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this); if (eventType.IsNil) { _eventType = TypeSymbolWithAnnotations.Create(containingType, new UnsupportedMetadataTypeSymbol(mrEx)); } } TypeSymbol originalEventType = _eventType.TypeSymbol; if (_eventType.IsNull) { var metadataDecoder = new MetadataDecoder(moduleSymbol, containingType); originalEventType = metadataDecoder.GetTypeOfToken(eventType); const int targetSymbolCustomModifierCount = 0; var typeSymbol = DynamicTypeDecoder.TransformType(originalEventType, targetSymbolCustomModifierCount, handle, moduleSymbol); // We start without annotation (they will be decoded below) var type = TypeSymbolWithAnnotations.Create(nonNullTypesContext: containingType, typeSymbol); // Decode nullable before tuple types to avoid converting between // NamedTypeSymbol and TupleTypeSymbol unnecessarily. type = NullableTypeDecoder.TransformType(type, handle, moduleSymbol); type = TupleTypeDecoder.DecodeTupleTypesIfApplicable(type, handle, moduleSymbol); _eventType = type; } // IsWindowsRuntimeEvent checks the signatures, so we just have to check the accessors. bool isWindowsRuntimeEvent = IsWindowsRuntimeEvent; bool callMethodsDirectly = isWindowsRuntimeEvent ? !DoModifiersMatch(_addMethod, _removeMethod) : !DoSignaturesMatch(moduleSymbol, originalEventType, _addMethod, _removeMethod); if (callMethodsDirectly) { _flags |= Flags.CallMethodsDirectly; } else { _addMethod.SetAssociatedEvent(this, MethodKind.EventAdd); _removeMethod.SetAssociatedEvent(this, MethodKind.EventRemove); PEFieldSymbol associatedField = GetAssociatedField(privateFieldNameToSymbols, isWindowsRuntimeEvent); if ((object)associatedField != null) { _associatedFieldOpt = associatedField; associatedField.SetAssociatedEvent(this); } } if ((mdFlags & EventAttributes.SpecialName) != 0) { _flags |= Flags.IsSpecialName; } if ((mdFlags & EventAttributes.RTSpecialName) != 0) { _flags |= Flags.IsRuntimeSpecialName; } }
public static StoreMulti <Tuple <T, TG>, TK> GetDictMulti <T, TG, TK>(List <Tuple <T, TG> > entries, string primaryKeyName1, string primaryKeyName2) { if (entries.Count == 0) { return(null); } // TODO: Add new config option "Verify data against DB" if (!SQLConnector.Enabled) { return(null); } var tableAttrs = (DBTableNameAttribute[])typeof(TK).GetCustomAttributes(typeof(DBTableNameAttribute), false); if (tableAttrs.Length <= 0) { return(null); } var tableName = tableAttrs[0].Name; var fields = Utilities.GetFieldsAndAttribute <TK, DBFieldNameAttribute>(); fields.RemoveAll(field => field.Item2.Name == null); var fieldCount = 2; var fieldNames = new StringBuilder(); fieldNames.Append(primaryKeyName1 + ","); fieldNames.Append(primaryKeyName2 + ","); foreach (var field in fields) { fieldNames.Append(field.Item2); fieldNames.Append(","); fieldCount += field.Item2.Count; } // WHERE (a = x1 AND b = y1) OR (a = x2 AND b = y2) OR ... var whereClause = new StringBuilder(); var ji = 0; foreach (var tuple in entries) { ji += 1; whereClause.Append("(") .Append(primaryKeyName1) .Append(" = ") .Append(tuple.Item1) .Append(" AND ") .Append(primaryKeyName2) .Append(" = ") .Append(tuple.Item2) .Append(")"); if (ji != entries.Count) { whereClause.Append(" OR "); } } var query = string.Format("SELECT {0} FROM {1}.{2} WHERE {3}", fieldNames.ToString().TrimEnd(','), Settings.TDBDatabase, tableName, whereClause); var dict = new MultiDictionary <Tuple <T, TG>, TK>(true); using (var reader = SQLConnector.ExecuteQuery(query)) { if (reader == null) { return(null); } while (reader.Read()) { var instance = (TK)Activator.CreateInstance(typeof(TK)); var values = new object[fieldCount]; var count = reader.GetValues(values); if (count != fieldCount) { throw new InvalidConstraintException( "Number of fields from DB is different of the number of fields with DBFieldName attribute"); } var i = 2; foreach (var field in fields) { #if __MonoCS__ // Mono does not support __makeref (only added in the upcoming 2.12 version) if (values[i] is DBNull && field.Item1.FieldType == typeof(string)) { field.Item1.SetValue(instance, string.Empty); } else if (field.Item1.FieldType.BaseType == typeof(Enum)) { field.Item1.SetValue(instance, Enum.Parse(field.Item1.FieldType, values[i].ToString())); } else if (field.Item1.FieldType.BaseType == typeof(Array)) { var arr = Array.CreateInstance(field.Item1.FieldType.GetElementType(), field.Item2.Count); for (var j = 0; j < arr.Length; j++) { var elemType = arr.GetType().GetElementType(); var val = Convert.ChangeType(values[i + j], elemType); arr.SetValue(val, j); } field.Item1.SetValue(instance, arr); } else if (field.Item1.FieldType == typeof(bool)) { field.Item1.SetValue(instance, Convert.ToBoolean(values[i])); } else { field.Item1.SetValue(instance, values[i]); } #else if (values[i] is DBNull && field.Item1.FieldType == typeof(string)) { field.Item1.SetValueDirect(__makeref(instance), string.Empty); } else if (field.Item1.FieldType.BaseType == typeof(Enum)) { field.Item1.SetValueDirect(__makeref(instance), Enum.Parse(field.Item1.FieldType, values[i].ToString())); } else if (field.Item1.FieldType.BaseType == typeof(Array)) { var arr = Array.CreateInstance(field.Item1.FieldType.GetElementType(), field.Item2.Count); for (var j = 0; j < arr.Length; j++) { var elemType = arr.GetType().GetElementType(); var val = Convert.ChangeType(values[i + j], elemType); arr.SetValue(val, j); } field.Item1.SetValueDirect(__makeref(instance), arr); } else if (field.Item1.FieldType == typeof(bool)) { field.Item1.SetValueDirect(__makeref(instance), Convert.ToBoolean(values[i])); } else { field.Item1.SetValueDirect(__makeref(instance), values[i]); } #endif i += field.Item2.Count; } var key = Tuple.Create((T)values[0], (TG)values[1]); if (!dict.ContainsKey(key)) { dict.Add(key, instance); } } } return(new StoreMulti <Tuple <T, TG>, TK>(dict)); }
public StoreMulti() { Types = new List <SQLOutput>(); Enabled = true; _dictionary = new MultiDictionary <T, Tuple <TK, TimeSpan?> >(true); }
protected override void CheckInterfaces(BindingDiagnosticBag diagnostics) { // Check declared interfaces and all base interfaces. This is necessary // since references to all interfaces will be emitted to metadata // and it's possible to define derived interfaces with weaker // constraints than the base interfaces, at least in metadata. var interfaces = this.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics; if (interfaces.IsEmpty) { // nothing to verify return; } // Check constraints on the first declaration with explicit bases. var singleDeclaration = this.FirstDeclarationWithExplicitBases(); if (singleDeclaration != null) { var corLibrary = this.ContainingAssembly.CorLibrary; var conversions = new TypeConversions(corLibrary); var location = singleDeclaration.NameLocation; foreach (var pair in interfaces) { MultiDictionary <NamedTypeSymbol, NamedTypeSymbol> .ValueSet set = pair.Value; foreach (var @interface in set) { @interface.CheckAllConstraints(DeclaringCompilation, conversions, location, diagnostics); } if (set.Count > 1) { NamedTypeSymbol other = pair.Key; foreach (var @interface in set) { if ((object)other == @interface) { continue; } // InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics populates the set with interfaces that match by CLR signature. Debug.Assert(!other.Equals(@interface, TypeCompareKind.ConsiderEverything)); Debug.Assert(other.Equals(@interface, TypeCompareKind.CLRSignatureCompareOptions)); if (other.Equals(@interface, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { if (!other.Equals(@interface, TypeCompareKind.ObliviousNullableModifierMatchesAny)) { diagnostics.Add(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, location, @interface, this); } } else if (other.Equals(@interface, TypeCompareKind.IgnoreTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { diagnostics.Add(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, location, @interface, other, this); } else { diagnostics.Add(ErrorCode.ERR_DuplicateInterfaceWithDifferencesInBaseList, location, @interface, other, this); } } } } } }
protected IConceptInfo ParseNextConcept(TokenReader tokenReader, Stack <IConceptInfo> context, MultiDictionary <string, IConceptParser> conceptParsers) { var errorReports = new List <Func <string> >(); List <Interpretation> possibleInterpretations = new List <Interpretation>(); var keywordReader = new TokenReader(tokenReader).ReadText(); // Peek, without changing the original tokenReader's position. var keyword = keywordReader.IsError ? null : keywordReader.Value; if (keyword != null) { foreach (var conceptParser in conceptParsers.Get(keyword)) { TokenReader nextPosition = new TokenReader(tokenReader); var conceptInfoOrError = conceptParser.Parse(nextPosition, context); if (!conceptInfoOrError.IsError) { possibleInterpretations.Add(new Interpretation { ConceptInfo = conceptInfoOrError.Value, NextPosition = nextPosition }); } else if (!string.IsNullOrEmpty(conceptInfoOrError.Error)) // Empty error means that this parser is not for this keyword. { errorReports.Add(() => string.Format("{0}: {1}\r\n{2}", conceptParser.GetType().Name, conceptInfoOrError.Error, tokenReader.ReportPosition())); } } } if (possibleInterpretations.Count == 0) { if (errorReports.Count > 0) { string errorsReport = string.Join("\r\n", errorReports.Select(x => x.Invoke())).Limit(500, "..."); throw new DslSyntaxException($"Invalid parameters after keyword '{keyword}'. {tokenReader.ReportPosition()}\r\n\r\nPossible causes:\r\n{errorsReport}"); } else if (!string.IsNullOrEmpty(keyword)) { throw new DslSyntaxException($"Unrecognized concept keyword '{keyword}'. {tokenReader.ReportPosition()}"); } else { throw new DslSyntaxException($"Invalid DSL script syntax. {tokenReader.ReportPosition()}"); } } int largest = possibleInterpretations.Max(i => i.NextPosition.PositionInTokenList); possibleInterpretations.RemoveAll(i => i.NextPosition.PositionInTokenList < largest); if (possibleInterpretations.Count > 1) { string msg = "Ambiguous syntax. " + tokenReader.ReportPosition() + "\r\n Possible interpretations: " + string.Join(", ", possibleInterpretations.Select(i => i.ConceptInfo.GetType().Name)) + "."; throw new DslSyntaxException(msg); } tokenReader.CopyFrom(possibleInterpretations.Single().NextPosition); return(possibleInterpretations.Single().ConceptInfo); }
/// <summary> /// Optimizes local functions such that if a local function only references other local functions /// that capture no variables, we don't need to create capture environments for any of them. /// </summary> private void RemoveUnneededReferences(ParameterSymbol thisParam) { var methodGraph = new MultiDictionary <MethodSymbol, MethodSymbol>(); var capturesThis = new HashSet <MethodSymbol>(); var capturesVariable = new HashSet <MethodSymbol>(); var visitStack = new Stack <MethodSymbol>(); VisitClosures(ScopeTree, (scope, closure) => { foreach (var capture in closure.CapturedVariables) { if (capture is MethodSymbol localFunc) { methodGraph.Add(localFunc, closure.OriginalMethodSymbol); } else if (capture == thisParam) { if (capturesThis.Add(closure.OriginalMethodSymbol)) { visitStack.Push(closure.OriginalMethodSymbol); } } else if (capturesVariable.Add(closure.OriginalMethodSymbol) && !capturesThis.Contains(closure.OriginalMethodSymbol)) { visitStack.Push(closure.OriginalMethodSymbol); } } }); while (visitStack.Count > 0) { var current = visitStack.Pop(); var setToAddTo = capturesVariable.Contains(current) ? capturesVariable : capturesThis; foreach (var capturesCurrent in methodGraph[current]) { if (setToAddTo.Add(capturesCurrent)) { visitStack.Push(capturesCurrent); } } } // True if there are any closures in the tree which // capture 'this' and another variable bool captureMoreThanThis = false; VisitClosures(ScopeTree, (scope, closure) => { if (!capturesVariable.Contains(closure.OriginalMethodSymbol)) { closure.CapturedVariables.Clear(); } if (capturesThis.Contains(closure.OriginalMethodSymbol)) { closure.CapturedVariables.Add(thisParam); if (closure.CapturedVariables.Count > 1) { captureMoreThanThis |= true; } } }); if (!captureMoreThanThis && capturesThis.Count > 0) { // If we have closures which capture 'this', and nothing else, we can // remove 'this' from the declared variables list, since we don't need // to create an environment to hold 'this' (since we can emit the // lowered methods directly onto the containing class) bool removed = ScopeTree.DeclaredVariables.Remove(thisParam); Debug.Assert(removed); } }
public StoreMulti(string type) { Type = type; Enabled = ProcessFlags(Type, Flags); _dictionary = Enabled ? new MultiDictionary <T, Tuple <TK, TimeSpan?> >(true) : null; }
/// <summary> /// This macro implements InitializationConcept (singleton) instead of AutoInheritRowPermissionsInfo, /// in order to allow creating the new concepts in a single iteration. /// </summary> public IEnumerable <IConceptInfo> CreateNewConcepts(InitializationConcept conceptInfo, IDslModel existingConcepts) { var autoInheritModules = new HashSet <string>( existingConcepts.FindByType <AutoInheritRowPermissionsInfo>().Select(airp => airp.Module.Name)); var autoInheritExtensionsByBase = new MultiDictionary <string, DataStructureExtendsInfo>(); var autoInheritExtensions = existingConcepts.FindByType <DataStructureExtendsInfo>() .Where(e => autoInheritModules.Contains(e.Extension.Module.Name)); foreach (var autoInheritExtension in autoInheritExtensions) { autoInheritExtensionsByBase.Add(autoInheritExtension.Base.GetKey(), autoInheritExtension); } var autoInheritDetailsByMaster = new MultiDictionary <string, ReferenceDetailInfo>(); var autoInheritDetails = existingConcepts.FindByType <ReferenceDetailInfo>() .Where(d => autoInheritModules.Contains(d.Reference.DataStructure.Module.Name)); foreach (var autoInheritDetail in autoInheritDetails) { autoInheritDetailsByMaster.Add(autoInheritDetail.Reference.Referenced.GetKey(), autoInheritDetail); } var rowPermissionsRead = existingConcepts.FindByType <RowPermissionsReadInfo>(); var rowPermissionsWrite = existingConcepts.FindByType <RowPermissionsWriteInfo>(); var allDataStructuresWithRowPermissions = new HashSet <string>( rowPermissionsRead.Select(rp => rp.Source.GetKey()) .Union(rowPermissionsWrite.Select(rp => rp.Source.GetKey())).ToList()); var newConcepts = new List <IConceptInfo>(); var newDataStructuresWithRowPermissions = new List <string>(allDataStructuresWithRowPermissions); while (newDataStructuresWithRowPermissions.Count > 0) { var newInheritences = new List <IConceptInfo>(); newInheritences.AddRange(newDataStructuresWithRowPermissions .SelectMany(ds => autoInheritExtensionsByBase.Get(ds)) .SelectMany(extension => { var rpFilters = new RowPermissionsPluginableFiltersInfo { DataStructure = extension.Extension }; var rpInherit = new RowPermissionsInheritFromBaseInfo { RowPermissionsFilters = rpFilters }; return(new IConceptInfo[] { rpFilters, rpInherit }); })); newInheritences.AddRange(newDataStructuresWithRowPermissions .SelectMany(ds => autoInheritDetailsByMaster.Get(ds)) .SelectMany(detail => { var rpFilters = new RowPermissionsPluginableFiltersInfo { DataStructure = detail.Reference.DataStructure }; var rpInherit = new RowPermissionsInheritFromReferenceInfo { RowPermissionsFilters = rpFilters, ReferenceProperty = detail.Reference }; return(new IConceptInfo[] { rpFilters, rpInherit }); })); newConcepts.AddRange(newInheritences); newDataStructuresWithRowPermissions = newInheritences.OfType <RowPermissionsPluginableFiltersInfo>() .Select(rpFilters => rpFilters.DataStructure.GetKey()) .Where(dataStructure => !allDataStructuresWithRowPermissions.Contains(dataStructure)) .ToList(); foreach (var dataStructure in newDataStructuresWithRowPermissions) { allDataStructuresWithRowPermissions.Add(dataStructure); } } ; return(newConcepts); }
public void Given_NoParent_When_InsertLine_Returns_MultiDictionary_WithLineInserted(MultiDictionary lineToInsert) { _sut.InsertLine(lineToInsert); _sut.Lines[lineToInsert.Code].Should().Be(lineToInsert); }
public StoreMulti(List <SQLOutput> types) { Types = types; Enabled = ProcessFlags(); _dictionary = Enabled ? new MultiDictionary <T, Tuple <TK, TimeSpan?> >(true) : null; }
public void Given_CorrectParent_When_InsertLine_LineInsertedInTheParentCollection(MultiDictionary lineToInsert, MultiDictionary parentLine) { _sut.InsertLine(parentLine); _sut.InsertLine(lineToInsert, parentLine); _sut.Lines[parentLine.Code].Lines[lineToInsert.Code].Should().Be(lineToInsert); }
public EventCalendar() { this.allEvents = new OrderedMultiDictionary <DateTime, Event>(true); this.eventsByTitle = new MultiDictionary <string, Event>(true); }
public void Given_3Levels_When_InsertLine_LineProperlyInserted(MultiDictionary level0Line, MultiDictionary level1Line, MultiDictionary level2Line) { _sut.InsertLine(level0Line); _sut.InsertLine(level1Line, level0Line); _sut.InsertLine(level2Line, level1Line); var result = _sut.Lines[level0Line.Code].Lines[level1Line.Code].Lines[level2Line.Code]; result.Should().Be(level2Line); }