public static BitArray DetermineBitArrayOfBasesInput(string input, BidirectionalDictionary<string, BitArray> codecDomain, Dictionary<Constants.ColumnsFromSkipChars, string> byProductsBySkipChars) { BitArray bitArrayOfInput = new BitArray(0); var inputIndeces = new InputIndeces(); while (inputIndeces.InputCharIndex < input.Length) { var inputPart = input.Substring(inputIndeces.InputCharIndex, 1); if ("^".Equals(inputPart)) { RecordReadStartingFactAndItsQual(input, byProductsBySkipChars, inputIndeces); } else if ("$".Equals(inputPart)) { RecordReadEndingFact(byProductsBySkipChars, inputIndeces); } // It is very important that the case "+" is preceded by case "^" because read mapping quality can contain symbol "+". else if ("+".Equals(inputPart)) { RecordExtraNucleotidesFact(input, byProductsBySkipChars, inputIndeces); } // It is very important that the case "-" is preceded by case "^" because read mapping quality can contain symbol "-". else if ("-".Equals(inputPart)) { RecordMissingNucleotidesFact(input, byProductsBySkipChars, inputIndeces); } else { bitArrayOfInput = UpdateBitArray(codecDomain, bitArrayOfInput, inputIndeces, inputPart); } } return bitArrayOfInput; }
public static string DecodeInputBools(bool[] bools, BidirectionalDictionary<string, BitArray> codecDomain, int codecBitStringLength) { string result = ""; bool[] boolsOfEncodedSign = new bool[codecBitStringLength]; int indexOfBoolsOfEncodedSign = 0; int falseCounter = 0; for (int index = 0; index < bools.Length; index++) { bool actualValue = bools[index]; boolsOfEncodedSign[indexOfBoolsOfEncodedSign] = actualValue; indexOfBoolsOfEncodedSign++; if (!actualValue) { falseCounter++; } else { falseCounter = 0; } if ((indexOfBoolsOfEncodedSign % codecBitStringLength) == 0) { if (falseCounter == codecBitStringLength) { // If there are as many 'false's of BitArray as codecBitStringLength then these are only the trailing zeros. break; } result = DecodeUnitOfInputBits(codecDomain, codecBitStringLength, result, ref boolsOfEncodedSign, ref indexOfBoolsOfEncodedSign, ref falseCounter); } } return result; }
public string GetReference(object context, object value) { BidirectionalDictionary <string, object> mappings = this.GetMappings(context); string first; if (!mappings.TryGetBySecond(value, out first)) { ++this._referenceCount; first = this._referenceCount.ToString((IFormatProvider)CultureInfo.InvariantCulture); mappings.Set(first, value); } return(first); }
public string GetReference(object context, object value) { BidirectionalDictionary <string, object> mappings = GetMappings(context); if (!mappings.TryGetBySecond(value, out string reference)) { _referenceCount++; reference = _referenceCount.ToString(CultureInfo.InvariantCulture); mappings.Set(reference, value); } return(reference); }
// Token: 0x06000ED8 RID: 3800 RVA: 0x00055A60 File Offset: 0x00053C60 public string GetReference(object context, object value) { BidirectionalDictionary <string, object> mappings = this.GetMappings(context); string text; if (!mappings.TryGetBySecond(value, out text)) { this._referenceCount++; text = this._referenceCount.ToString(CultureInfo.InvariantCulture); mappings.Set(text, value); } return(text); }
private static void ReportIssues(SymbolAnalysisContext context, HashSet <ISymbol> usedSymbols, HashSet <ISymbol> declaredPrivateSymbols, HashSet <ISymbol> emptyConstructors, BidirectionalDictionary <ISymbol, SyntaxNode> fieldLikeSymbols) { var unusedSymbols = declaredPrivateSymbols .Except(usedSymbols.Union(emptyConstructors)) .ToList(); var alreadyReportedFieldLikeSymbols = new HashSet <ISymbol>(); var unusedSymbolSyntaxPairs = unusedSymbols .SelectMany(unusedSymbol => unusedSymbol.DeclaringSyntaxReferences .Select(r => new { Syntax = r.GetSyntax(), Symbol = unusedSymbol })); foreach (var unused in unusedSymbolSyntaxPairs) { var location = unused.Syntax.GetLocation(); var canBeFieldLike = unused.Symbol is IFieldSymbol || unused.Symbol is IEventSymbol; if (canBeFieldLike) { if (alreadyReportedFieldLikeSymbols.Contains(unused.Symbol)) { continue; } var variableDeclaration = GetVariableDeclaration(unused.Syntax); if (variableDeclaration == null) { continue; } var declarations = variableDeclaration.Variables .Select(v => fieldLikeSymbols.GetByB(v)) .ToList(); if (declarations.All(d => unusedSymbols.Contains(d))) { location = unused.Syntax.Parent.Parent.GetLocation(); alreadyReportedFieldLikeSymbols.UnionWith(declarations); } } context.ReportDiagnosticIfNonGenerated(Diagnostic.Create(Rule, location), context.Compilation); } }
/// <summary> /// Constructs a new instance of default pluralization service /// used in Entity Framework. /// </summary> public EnglishPluralizationService() { _userDictionary = new BidirectionalDictionary<string, string>(); _irregularPluralsPluralizationService = new StringBidirectionalDictionary(_irregularPluralsList); _assimilatedClassicalInflectionPluralizationService = new StringBidirectionalDictionary(_assimilatedClassicalInflectionList); _oSuffixPluralizationService = new StringBidirectionalDictionary(_oSuffixList); _classicalInflectionPluralizationService = new StringBidirectionalDictionary(_classicalInflectionList); _wordsEndingWithSePluralizationService = new StringBidirectionalDictionary(_wordsEndingWithSeList); _wordsEndingWithSisPluralizationService = new StringBidirectionalDictionary(_wordsEndingWithSisList); // verb _irregularVerbPluralizationService = new StringBidirectionalDictionary(_irregularVerbList); _knownSingluarWords = new List<string>(_irregularPluralsList.Keys.Concat(_assimilatedClassicalInflectionList.Keys).Concat(_oSuffixList.Keys).Concat(_classicalInflectionList.Keys).Concat(_irregularVerbList.Keys).Concat(_uninflectiveWords).Except(_knownConflictingPluralList)); // see the _knowConflictingPluralList comment above _knownPluralWords = new List<string>(_irregularPluralsList.Values.Concat(_assimilatedClassicalInflectionList.Values).Concat(_oSuffixList.Values).Concat(_classicalInflectionList.Values).Concat(_irregularVerbList.Values).Concat(_uninflectiveWords)); }
public void IndexAssignDuplicateChecking() { var dict = new BidirectionalDictionary <char, int>(); dict.Add('A', 1); dict['A'] = 2; Assert.AreEqual(2, dict['A']); Assert.AreEqual('A', dict[2]); // TODO: The old 1 should be removed Assert.False(dict.ContainsKey(1)); Assert.AreEqual(1, dict.Count); }
public GraphVisualizationInfoView() { InitializeComponent(); this.shapeInfoShapeMapping = new BidirectionalDictionary<IShapeInfo, IShape>(); this.connectionInfoConnectionMapping = new BidirectionalDictionary<IConnectionInfo, IConnection>(); this.connectionPenStyle = new LinePenStyle(); this.connectionPenStyle.EndCap = LineCap.ArrowAnchor; PasteTool pasteTool = (PasteTool)this.Controller.Tools.Where(t => t.Name == ControllerBase.PasteToolName).FirstOrDefault(); CopyTool copyTool = (CopyTool)this.Controller.Tools.Where(t => t.Name == ControllerBase.CopyToolName).FirstOrDefault(); HeuristicLab.Netron.Controller controller = this.Controller as HeuristicLab.Netron.Controller; if (controller != null) { if (pasteTool != null) controller.RemoveTool(pasteTool); if (copyTool != null) controller.RemoveTool(copyTool); } }
public object ParseEnumName(string enumText, bool isNullable, bool disallowValue, Type t) { if (enumText == String.Empty && isNullable) { return(null); } string finalEnumText; BidirectionalDictionary <string, string> map = EnumMemberNamesPerType.Get(t); string resolvedEnumName; if (TryResolvedEnumName(map, enumText, out resolvedEnumName)) { finalEnumText = resolvedEnumName; } else if (enumText.IndexOf(',') != -1) { string[] names = enumText.Split(','); for (int i = 0; i < names.Length; i++) { string name = names[i].Trim(); names[i] = TryResolvedEnumName(map, name, out resolvedEnumName) ? resolvedEnumName : name; } finalEnumText = String.Join(", ", names); } else { finalEnumText = enumText; if (disallowValue) { bool isNumber = Int32.TryParse(finalEnumText, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out int _); if (isNumber) { throw new FormatException("Integer string '{0}' is not allowed.".FormatWith(CultureInfo.InvariantCulture, enumText)); } } } return(Enum.Parse(t, finalEnumText, true)); }
/// <summary> /// A cached representation of the Enum string representation to respect per Enum field name. /// </summary> /// <param name="t">The type of the Enum.</param> /// <returns>A map of enum field name to either the field name, or the configured enum member name (<see cref="EnumMemberAttribute"/>).</returns> private BidirectionalDictionary <string, string> GetEnumNameMap(Type t) { BidirectionalDictionary <string, string> map; if (!_enumMemberNamesPerType.TryGetValue(t, out map)) { lock (_enumMemberNamesPerType) { if (_enumMemberNamesPerType.TryGetValue(t, out map)) { return(map); } map = new BidirectionalDictionary <string, string>( StringComparer.OrdinalIgnoreCase, StringComparer.OrdinalIgnoreCase); foreach (FieldInfo f in t.GetFields()) { string n1 = f.Name; string n2; #if !NET20 n2 = f.GetCustomAttributes(typeof(EnumMemberAttribute), true) .Cast <EnumMemberAttribute>() .Select(a => a.Value) .SingleOrDefault() ?? f.Name; #else n2 = f.Name; #endif string s; if (map.TryGetBySecond(n2, out s)) { throw new Exception("Enum name '{0}' already exists on enum '{1}'." .FormatWith(CultureInfo.InvariantCulture, n2, t.Name)); } map.Add(n1, n2); } _enumMemberNamesPerType[t] = map; } } return(map); }
public void TestBidirectionalDictionary() { var dict1 = new BidirectionalDictionary <int, double>(); dict1.Add(4, 2.0); Assert.IsTrue(dict1.ContainsFirst(4) && dict1.ContainsSecond(2)); bool exceptionOnDuplicate = false; try { dict1.Add(4, 3.0); } catch (ArgumentException) { exceptionOnDuplicate = true; } Assert.IsTrue(exceptionOnDuplicate); Assert.IsTrue(dict1.GetByFirst(4) == 2); Assert.IsTrue(dict1.GetBySecond(2) == 4); Assert.IsTrue(dict1.Count == 1); dict1.Clear(); Assert.IsTrue(dict1.Count == 0); var dict2 = new BidirectionalDictionary <ComplexType, int>(new ComplexTypeEqualityComparer()); Assert.IsTrue(!dict2.Any()); dict2.Add(new ComplexType(1), 2); Assert.IsTrue(dict2.Any()); dict2.Add(new ComplexType(2), 1); Assert.IsTrue(dict2.ContainsFirst(new ComplexType(2))); Assert.IsTrue(dict2.ContainsSecond(2)); exceptionOnDuplicate = false; try { dict2.Add(new ComplexType(2), 3); } catch (ArgumentException) { exceptionOnDuplicate = true; } Assert.IsTrue(exceptionOnDuplicate); exceptionOnDuplicate = false; try { dict2.Add(new ComplexType(3), 1); } catch (ArgumentException) { exceptionOnDuplicate = true; } Assert.IsTrue(exceptionOnDuplicate); Assert.IsTrue(dict2.Count == 2); Assert.IsTrue(dict2.GetBySecond(1).Field == 2); Assert.IsTrue(dict2.GetByFirst(new ComplexType(1)) == 2); dict2.Clear(); Assert.IsTrue(!dict2.Any()); }
private BidirectionalDictionary <string, string> GetEnumNameMap(Type t) { BidirectionalDictionary <string, string> bidirectionalDictionary; BidirectionalDictionary <string, string> bidirectionalDictionary1; string str; if (!this._enumMemberNamesPerType.TryGetValue(t, out bidirectionalDictionary)) { object obj = this._enumMemberNamesPerType; Monitor.Enter(obj); try { if (!this._enumMemberNamesPerType.TryGetValue(t, out bidirectionalDictionary)) { bidirectionalDictionary = new BidirectionalDictionary <string, string>(StringComparer.OrdinalIgnoreCase, StringComparer.OrdinalIgnoreCase); FieldInfo[] fields = t.GetFields(); for (int i = 0; i < (int)fields.Length; i++) { FieldInfo fieldInfo = fields[i]; string name = fieldInfo.Name; string str1 = ( from EnumMemberAttribute a in fieldInfo.GetCustomAttributes(typeof(EnumMemberAttribute), true) select a.Value).SingleOrDefault <string>() ?? fieldInfo.Name; if (bidirectionalDictionary.TryGetBySecond(str1, out str)) { throw new Exception("Enum name '{0}' already exists on enum '{1}'.".FormatWith(CultureInfo.InvariantCulture, new object[] { str1, t.Name })); } bidirectionalDictionary.Add(name, str1); } this._enumMemberNamesPerType[t] = bidirectionalDictionary; return(bidirectionalDictionary); } else { bidirectionalDictionary1 = bidirectionalDictionary; } } finally { Monitor.Exit(obj); } return(bidirectionalDictionary1); } return(bidirectionalDictionary); }
public void Item_Set_KeyToEquivalentValue() { var dictionary = new BidirectionalDictionary <int, Foo> (); var key = 42; var value1 = new Foo { Name = "value", Value = "1" }; var value2 = new Foo { Name = "value", Value = "2" }; dictionary.Add(key, value1); dictionary [key] = value2; Assert.AreSame(value2, dictionary [key]); Assert.AreSame(value2, dictionary.Inverse.Keys.First()); }
/// <summary> /// Constructs MapImage instance. /// </summary> /// <param name="map">Map with regions.</param> /// <param name="regionHighlightedImage">Image containing the map in proper format.</param> /// <param name="regionsWithColors"> /// Tuples mapping color of region to corresponding region. Regions must correspond to /// those in the map. /// </param> public MapImageTemplateProcessor(Map map, Image regionHighlightedImage, Dictionary <Color, Region> regionsWithColors) { RegionHighlightedImage = new Bitmap(regionHighlightedImage); if (map.Regions.Count != regionsWithColors.Count) { throw new ArgumentException(); } regionsColorsMapped = new BidirectionalDictionary <Color, Region>(); // initialize color foreach (KeyValuePair <Color, Region> item in regionsWithColors) { regionsColorsMapped.Add(item.Key, item.Value); } }
private static string DecodeUnitOfInputBits(BidirectionalDictionary<string, BitArray> codecDomain, int codecBitStringLength, string actualDecodedString, ref bool[] boolsOfEncodedSign, ref int indexOfBoolsOfEncodedSign, ref int falseCounter) { var bitArrayOfEncodedSign = new BitArray(boolsOfEncodedSign); string decodedSign; if (codecDomain.Reverse.TryGetValue(bitArrayOfEncodedSign, out decodedSign)) { actualDecodedString += decodedSign; } else { throw new ArgumentException("The codecDomain does not contain the unit of input bools!"); } indexOfBoolsOfEncodedSign = 0; boolsOfEncodedSign = new bool[codecBitStringLength]; falseCounter = 0; return actualDecodedString; }
public static BitArray DetermineBitArrayOfInput(string input, BidirectionalDictionary<string, BitArray> codecDomain) { BitArray bitArrayOfInput = new BitArray(0); for (int index = 0; index < input.Length; index++) { var inputPart = input.Substring(index, 1); BitArray bitArrayOfInputPart; if (codecDomain.Forward.TryGetValue(inputPart, out bitArrayOfInputPart)) { bitArrayOfInput = AppendBitArray(bitArrayOfInput, bitArrayOfInputPart); } else { throw new ArgumentException("The input cannot be encoded because it contains invalid part!", inputPart); } } return bitArrayOfInput; }
/// <summary> /// Writes the JSON representation of the object. /// </summary> /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param> /// <param name="value">The value.</param> /// <param name="serializer">The calling serializer.</param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value == null) { writer.WriteNull(); return; } Enum e = (Enum)value; string enumName = e.ToString("G"); if (char.IsNumber(enumName[0]) || enumName[0] == '-') { // enum value has no name so write number writer.WriteValue(value); } else { BidirectionalDictionary <string, string> map = EnumMemberNamesPerType.Get(e.GetType()); string[] names = enumName.Split(','); for (int i = 0; i < names.Length; i++) { string name = names[i].Trim(); string resolvedEnumName; map.TryGetByFirst(name, out resolvedEnumName); resolvedEnumName = resolvedEnumName ?? name; if (CamelCaseText) { resolvedEnumName = StringUtils.ToCamelCase(resolvedEnumName); } names[i] = resolvedEnumName; } string finalName = string.Join(", ", names); writer.WriteValue(finalName); } }
public void Item_Set_EquivalentExistingValue() { var dictionary = new BidirectionalDictionary <int, Foo> (); var key1 = 42; var key2 = 67; var value1 = new Foo { Name = "value", Value = "1" }; var value2 = new Foo { Name = "value", Value = "2" }; dictionary.Add(key1, value1); var ex = Assert.Throws <ArgumentException> (() => dictionary [key2] = value2); Assert.AreEqual("value", ex.ParamName); }
private static IEnumerable <Diagnostic> GetDiagnostics(SymbolUsageCollector usageCollector, ISet <ISymbol> removableSymbols, string accessibility, BidirectionalDictionary <ISymbol, SyntaxNode> fieldLikeSymbols) { var unusedSymbols = removableSymbols .Except(usageCollector.UsedSymbols) .Where(symbol => !MentionedInDebuggerDisplay(symbol)) .ToHashSet(); var propertiesWithUnusedAccessor = removableSymbols .Intersect(usageCollector.UsedSymbols) .OfType <IPropertySymbol>() .Where(usageCollector.PropertyAccess.ContainsKey) .Where(symbol => !MentionedInDebuggerDisplay(symbol)); return(GetDiagnosticsForMembers(unusedSymbols, accessibility, fieldLikeSymbols) .Concat(propertiesWithUnusedAccessor.SelectMany(propertySymbol => GetDiagnosticsForProperty(propertySymbol, usageCollector.PropertyAccess)))); bool MentionedInDebuggerDisplay(ISymbol symbol) => usageCollector.DebuggerDisplayValues.Any(value => value.Contains(symbol.Name)); }
public void SimpleLookup() { var dict = new BidirectionalDictionary <char, int>(); dict.Add('A', 1); Assert.True(dict.ContainsKey('A')); Assert.True(dict.ContainsKey(1)); Assert.False(dict.ContainsKey('B')); Assert.False(dict.ContainsKey(2)); Assert.AreEqual('A', dict[1]); Assert.AreEqual(1, dict['A']); Assert.Throws <KeyNotFoundException>(() => { var _ = dict['B']; }); }
protected sealed override void Initialize(SonarAnalysisContext context) { context.RegisterSymbolAction( c => { var namedType = (INamedTypeSymbol)c.Symbol; if (!namedType.IsClassOrStruct() || namedType.ContainingType != null) { return; } var declarationCollector = new RemovableDeclarationCollector(namedType, c.Compilation); var declaredPrivateSymbols = new HashSet <ISymbol>(); var fieldLikeSymbols = new BidirectionalDictionary <ISymbol, SyntaxNode>(); CollectRemovableNamedTypes(declarationCollector, declaredPrivateSymbols); CollectRemovableFieldLikeDeclarations(declarationCollector, declaredPrivateSymbols, fieldLikeSymbols); CollectRemovableEventsAndProperties(declarationCollector, declaredPrivateSymbols); CollectRemovableMethods(declarationCollector, declaredPrivateSymbols); if (!declaredPrivateSymbols.Any()) { return; } var usedSymbols = new HashSet <ISymbol>(); var emptyConstructors = new HashSet <ISymbol>(); var propertyAccessorAccess = new Dictionary <IPropertySymbol, AccessorAccess>(); CollectUsedSymbols(declarationCollector, usedSymbols, declaredPrivateSymbols, propertyAccessorAccess); CollectUsedSymbolsFromCtorInitializerAndCollectEmptyCtors(declarationCollector, usedSymbols, emptyConstructors); ReportIssues(c, usedSymbols, declaredPrivateSymbols, emptyConstructors, fieldLikeSymbols); ReportUnusedPropertyAccessors(c, usedSymbols, declaredPrivateSymbols, propertyAccessorAccess); }, SymbolKind.NamedType); }
/// <summary> /// A cached representation of the Enum string representation to respect per Enum field name. /// </summary> /// <param name="t">The type of the Enum.</param> /// <returns>A map of enum field name to either the field name, or the configured enum member name (<see cref="EnumMemberAttribute"/>).</returns> private BidirectionalDictionary <string, string> GetEnumNameMap(Type t) { BidirectionalDictionary <string, string> map; if (!_enumMemberNamesPerType.TryGetValue(t, out map)) { lock (_enumMemberNamesPerType) { if (_enumMemberNamesPerType.TryGetValue(t, out map)) { return(map); } map = new BidirectionalDictionary <string, string>( StringComparer.OrdinalIgnoreCase, StringComparer.OrdinalIgnoreCase); foreach (FieldInfo f in t.GetFields()) { string n1 = f.Name; string n2; n2 = f.Name; string s; if (map.TryGetBySecond(n2, out s)) { throw new Exception("Enum name '{0}' already exists on enum '{1}'." .FormatWith(CultureInfo.InvariantCulture, n2, t.Name)); } map.Add(n1, n2); } _enumMemberNamesPerType[t] = map; } } return(map); }
private void Start() { PlayerBoard = new Board(); PlayerBoard.OnMinionAdded += SetupPlayerCardGameObject; // ALERT: This relies on these being called in order PlayerBoard.OnMinionAdded += (c) => { UpdateCardPositionsWrapper(); }; OpponentBoard = new Board(); OpponentBoard.OnMinionAdded += SetupPlayerCardGameObject; // ALERT: This relies on these being called in order OpponentBoard.OnMinionAdded += (c) => { UpdateCardPositionsWrapper(); }; CardGameObjectMap = new BidirectionalDictionary <Card, GameObject>(); playerBoardParent = new GameObject("Player Board").transform; playerBoardParent.SetParent(this.transform); playerBoardParent.localPosition = new Vector3(0, -1f); playerBoardParent.localScale = Vector3.one; opponentBoardParent = new GameObject("Opponent Board").transform; opponentBoardParent.SetParent(this.transform); opponentBoardParent.localPosition = new Vector3(0, 1f); opponentBoardParent.localScale = Vector3.one; }
public void Item_Set_EquivalentExistingKey() { var dictionary = new BidirectionalDictionary <Foo, int> (); var key1 = new Foo { Name = "key", Value = "1" }; var key2 = new Foo { Name = "key", Value = "2" }; var value1 = 42; var value2 = 67; dictionary.Add(key1, value1); dictionary [key2] = value2; Assert.AreSame(key1, dictionary.Keys.First()); Assert.AreSame(key1, dictionary.Inverse [value2]); Assert.AreEqual(value2, dictionary [key1]); Assert.AreEqual(value2, dictionary [key2]); Assert.Throws <KeyNotFoundException> (() => dictionary.Inverse [value1].ToString()); }
private static IEnumerable <Diagnostic> GetDiagnosticsForMembers(HashSet <ISymbol> unusedSymbols, string accessibility, BidirectionalDictionary <ISymbol, SyntaxNode> fieldLikeSymbols) { var alreadyReportedFieldLikeSymbols = new HashSet <ISymbol>(); var unusedSymbolSyntaxPairs = unusedSymbols .SelectMany(symbol => symbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax().ToSyntaxWithSymbol(symbol))); var diagnostics = new List <Diagnostic>(); foreach (var unused in unusedSymbolSyntaxPairs) { var syntaxForLocation = unused.Syntax; // Report the whole field or event declaration when all variables in it are unused. var fieldOrEvent = unused.Symbol is IFieldSymbol || unused.Symbol is IEventSymbol; if (fieldOrEvent) { if (alreadyReportedFieldLikeSymbols.Contains(unused.Symbol)) { continue; } var declarations = GetSiblingDeclarators((VariableDeclaratorSyntax)unused.Syntax) .Select(fieldLikeSymbols.GetByB) .ToList(); if (declarations.All(unusedSymbols.Contains)) { syntaxForLocation = unused.Syntax.Parent.Parent; alreadyReportedFieldLikeSymbols.UnionWith(declarations); } } diagnostics.Add(CreateDiagnostic(syntaxForLocation, unused.Symbol, accessibility)); } return(diagnostics); }
protected override void Initialize(SonarAnalysisContext context) { context.RegisterSymbolAction( c => { var namedType = (INamedTypeSymbol)c.Symbol; if (!namedType.IsClassOrStruct() || namedType.ContainingType != null) { return; } var declarationCollector = new RemovableDeclarationCollector(namedType, c.Compilation); var declaredPrivateSymbols = new HashSet<ISymbol>(); var fieldLikeSymbols = new BidirectionalDictionary<ISymbol, SyntaxNode>(); CollectRemovableNamedTypes(declarationCollector, declaredPrivateSymbols); CollectRemovableFieldLikeDeclarations(declarationCollector, declaredPrivateSymbols, fieldLikeSymbols); CollectRemovableEventsAndProperties(declarationCollector, declaredPrivateSymbols); CollectRemovableMethods(declarationCollector, declaredPrivateSymbols); if (!declaredPrivateSymbols.Any()) { return; } var usedSymbols = new HashSet<ISymbol>(); var emptyConstructors = new HashSet<ISymbol>(); CollectUsedSymbols(declarationCollector, usedSymbols, declaredPrivateSymbols); CollectUsedSymbolsFromCtorInitializerAndCollectEmptyCtors(declarationCollector, usedSymbols, emptyConstructors); ReportIssues(c, usedSymbols, declaredPrivateSymbols, emptyConstructors, fieldLikeSymbols); }, SymbolKind.NamedType); }
private static IEnumerable <Diagnostic> GetDiagnosticsForMembers(ICollection <ISymbol> unusedSymbols, string accessibility, BidirectionalDictionary <ISymbol, SyntaxNode> fieldLikeSymbols) { var alreadyReportedFieldLikeSymbols = new HashSet <ISymbol>(); var unusedSymbolSyntaxPairs = unusedSymbols .SelectMany(symbol => symbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax().ToSyntaxWithSymbol(symbol))); var diagnostics = new List <Diagnostic>(); foreach (var unused in unusedSymbolSyntaxPairs) { var syntaxForLocation = unused.Syntax; var isFieldOrEvent = unused.Symbol.Kind == SymbolKind.Field || unused.Symbol.Kind == SymbolKind.Event; if (isFieldOrEvent && unused.Syntax.IsKind(SyntaxKind.VariableDeclarator)) { if (alreadyReportedFieldLikeSymbols.Contains(unused.Symbol)) { continue; } var declarations = GetSiblingDeclarators(unused.Syntax) .Select(fieldLikeSymbols.GetByB) .ToList(); if (declarations.All(unusedSymbols.Contains)) { syntaxForLocation = unused.Syntax.Parent.Parent; alreadyReportedFieldLikeSymbols.UnionWith(declarations); } } diagnostics.Add(CreateS1144Diagnostic(syntaxForLocation, unused.Symbol)); } return(diagnostics);
/// <summary> /// Initializes a new instance of the <see cref="SaveGraph" /> class. /// </summary> /// <param name="entities">The entities.</param> /// <exception cref="System.ArgumentNullException"> /// entities /// or /// context /// </exception> public SaveGraph(IEnumerable <IEntity> entities) { if (entities == null) { throw new ArgumentNullException("entities"); } Entities = new Dictionary <long, IEntity>(); foreach (IEntity entity in entities) { Entities[entity.Id] = entity; } AcceptedChangeTrackers = new List <IChangeTracker <IMutableIdKey> >( ); CurrentUtcDate = DateTime.UtcNow; State = new Dictionary <string, object>( ); Changes = new Dictionary <long, EntityChanges>( ); Mapping = new BidirectionalDictionary <long, long>( ); EventTargetStateHelper.SetSaveGraph(State, this); }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value == null) { writer.WriteNull(); return; } Enum @enum = (Enum)value; string text = @enum.ToString("G"); if (char.IsNumber(text[0]) || text[0] == '-') { writer.WriteValue(value); return; } BidirectionalDictionary <string, string> enumNameMap = this.GetEnumNameMap(@enum.GetType()); string[] array = text.Split(new char[] { ',' }); for (int i = 0; i < array.Length; i++) { string text2 = array[i].Trim(); string text3; enumNameMap.TryGetByFirst(text2, out text3); text3 = (text3 ?? text2); if (this.CamelCaseText) { text3 = StringUtils.ToCamelCase(text3); } array[i] = text3; } string value2 = string.Join(", ", array); writer.WriteValue(value2); }
private BidirectionalDictionary <string, string> GetEnumNameMap(Type t) { BidirectionalDictionary <string, string> bidirectionalDictionary; if (!this._enumMemberNamesPerType.TryGetValue(t, ref bidirectionalDictionary)) { Dictionary <Type, BidirectionalDictionary <string, string> > enumMemberNamesPerType = this._enumMemberNamesPerType; lock (enumMemberNamesPerType) { if (this._enumMemberNamesPerType.TryGetValue(t, ref bidirectionalDictionary)) { return(bidirectionalDictionary); } bidirectionalDictionary = new BidirectionalDictionary <string, string>(StringComparer.get_OrdinalIgnoreCase(), StringComparer.get_OrdinalIgnoreCase()); FieldInfo[] fields = t.GetFields(); for (int i = 0; i < fields.Length; i++) { FieldInfo fieldInfo = fields[i]; string name = fieldInfo.get_Name(); string text = Enumerable.SingleOrDefault <string>(Enumerable.Select <EnumMemberAttribute, string>(Enumerable.Cast <EnumMemberAttribute>(fieldInfo.GetCustomAttributes(typeof(EnumMemberAttribute), true)), (EnumMemberAttribute a) => a.Value)) ?? fieldInfo.get_Name(); string text2; if (bidirectionalDictionary.TryGetBySecond(text, out text2)) { throw new Exception("Enum name '{0}' already exists on enum '{1}'.".FormatWith(CultureInfo.get_InvariantCulture(), new object[] { text, t.get_Name() })); } bidirectionalDictionary.Add(name, text); } this._enumMemberNamesPerType.set_Item(t, bidirectionalDictionary); } return(bidirectionalDictionary); } return(bidirectionalDictionary); }
public void Set <TFirst, TSecond>(BidirectionalDictionary <TFirst, TSecond> dictionary, TFirst first, TSecond second) { TFirst existingFirst; TSecond existingSecond; if (dictionary.FirstToSecond.TryGetValue(first, out existingSecond)) { if (!existingSecond.Equals(second)) { throw new ArgumentException(dictionary.DuplicateFirstErrorMessage.FormatWith(CultureInfo.InvariantCulture, first)); } } if (dictionary.SecondToFirst.TryGetValue(second, out existingFirst)) { if (!existingFirst.Equals(first)) { throw new ArgumentException(dictionary.DuplicateSecondErrorMessage.FormatWith(CultureInfo.InvariantCulture, second)); } } dictionary.FirstToSecond.Add(first, second); dictionary.SecondToFirst.Add(second, first); }
private BidirectionalDictionary<string, string> GetEnumNameMap(Type t) { BidirectionalDictionary<string, string> bidirectionalDictionary; if (!this._enumMemberNamesPerType.TryGetValue(t, out bidirectionalDictionary)) { lock (this._enumMemberNamesPerType) { if (this._enumMemberNamesPerType.TryGetValue(t, out bidirectionalDictionary)) return bidirectionalDictionary; bidirectionalDictionary = new BidirectionalDictionary<string, string>((IEqualityComparer<string>) StringComparer.OrdinalIgnoreCase, (IEqualityComparer<string>) StringComparer.OrdinalIgnoreCase); foreach (FieldInfo item_0 in t.GetFields()) { string local_2 = item_0.Name; string local_3 = item_0.Name; string local_4; if (bidirectionalDictionary.TryGetBySecond(local_3, out local_4)) throw new InvalidOperationException(StringUtils.FormatWith("Enum name '{0}' already exists on enum '{1}'.", (IFormatProvider) CultureInfo.InvariantCulture, (object) local_3, (object) t.Name)); bidirectionalDictionary.Set(local_2, local_3); } this._enumMemberNamesPerType[t] = bidirectionalDictionary; } } return bidirectionalDictionary; }
private static int CheckInitializedEncoder(BidirectionalDictionary<string, BitArray> codec) { int? fixedLengthOfEncoder = null; foreach (BitArray bitArray in codec.Forward.Values) { if (fixedLengthOfEncoder == null) { fixedLengthOfEncoder = bitArray.Count; } else if (bitArray.Count != fixedLengthOfEncoder) { string exceptionMessage = String.Format("The encoder should contain bit arrays of the same length: {0} " + "but the length of one of them is: {1}! The EncodingResource.resx contains invalid entries.", fixedLengthOfEncoder, bitArray.Count); throw new ArgumentException(exceptionMessage); } } int result = 0; if (fixedLengthOfEncoder.HasValue) { result = fixedLengthOfEncoder.Value; } return result; }
private BidirectionalDictionary <string, string> GetEnumNameMap(Type t) { BidirectionalDictionary <string, string> bidirectionalDictionary; if (!this._enumMemberNamesPerType.TryGetValue(t, out bidirectionalDictionary)) { object enumMemberNamesPerType = this._enumMemberNamesPerType; lock (enumMemberNamesPerType) { if (this._enumMemberNamesPerType.TryGetValue(t, out bidirectionalDictionary)) { return(bidirectionalDictionary); } bidirectionalDictionary = new BidirectionalDictionary <string, string>(StringComparer.OrdinalIgnoreCase, StringComparer.OrdinalIgnoreCase); foreach (FieldInfo fieldInfo in t.GetFields()) { string name = fieldInfo.Name; string text = (from EnumMemberAttribute a in fieldInfo.GetCustomAttributes(typeof(EnumMemberAttribute), true) select a.Value).SingleOrDefault <string>() ?? fieldInfo.Name; string text2; if (bidirectionalDictionary.TryGetBySecond(text, out text2)) { throw new Exception("Enum name '{0}' already exists on enum '{1}'.".FormatWith(CultureInfo.InvariantCulture, new object[] { text, t.Name })); } bidirectionalDictionary.Add(name, text); } this._enumMemberNamesPerType[t] = bidirectionalDictionary; } return(bidirectionalDictionary); } return(bidirectionalDictionary); }
public GraphVisualizationInfoView() { InitializeComponent(); this.shapeInfoShapeMapping = new BidirectionalDictionary <IShapeInfo, IShape>(); this.connectionInfoConnectionMapping = new BidirectionalDictionary <IConnectionInfo, IConnection>(); this.connectionPenStyle = new LinePenStyle(); this.connectionPenStyle.EndCap = LineCap.ArrowAnchor; PasteTool pasteTool = (PasteTool)this.Controller.Tools.Where(t => t.Name == ControllerBase.PasteToolName).FirstOrDefault(); CopyTool copyTool = (CopyTool)this.Controller.Tools.Where(t => t.Name == ControllerBase.CopyToolName).FirstOrDefault(); HeuristicLab.Netron.Controller controller = this.Controller as HeuristicLab.Netron.Controller; if (controller != null) { if (pasteTool != null) { controller.RemoveTool(pasteTool); } if (copyTool != null) { controller.RemoveTool(copyTool); } } }
private static void CreateAnnotationForDiagnostics(System.Collections.Immutable.ImmutableArray<Diagnostic> diagnostics, string annotationKind, BidirectionalDictionary<Diagnostic, SyntaxAnnotation> diagnosticAnnotationPairs) { foreach (var diagnostic in diagnostics) { diagnosticAnnotationPairs.Add(diagnostic, new SyntaxAnnotation(annotationKind)); } }
private static SyntaxNode GetRootWithAnnotatedElements(SyntaxNode root, Dictionary<SyntaxNodeOrToken, Diagnostic> elementDiagnosticPairs, BidirectionalDictionary<Diagnostic, SyntaxAnnotation> diagnosticAnnotationPairs) { var nodes = elementDiagnosticPairs.Keys.Where(k => k.IsNode).Select(k => k.AsNode()); var tokens = elementDiagnosticPairs.Keys.Where(k => k.IsToken).Select(k => k.AsToken()); return root.ReplaceSyntax( nodes, (original, rewritten) => { var annotation = diagnosticAnnotationPairs.GetByA(elementDiagnosticPairs[original]); return rewritten.WithAdditionalAnnotations(annotation); }, tokens, (original, rewritten) => { var annotation = diagnosticAnnotationPairs.GetByA(elementDiagnosticPairs[original]); return rewritten.WithAdditionalAnnotations(annotation); }, null, null); }
private static async Task<SyntaxNode> GetFixedDocumentAsync(FixAllContext fixAllContext, Document document) { var annotationKind = Guid.NewGuid().ToString(); var diagnostics = await fixAllContext.GetDocumentDiagnosticsAsync(document).ConfigureAwait(false); var root = await document.GetSyntaxRootAsync(fixAllContext.CancellationToken).ConfigureAwait(false); var elementDiagnosticPairs = diagnostics .Select(d => new KeyValuePair<SyntaxNodeOrToken, Diagnostic>(GetReportedElement(d, root), d)) .Where(n => !n.Key.IsMissing) .ToDictionary(kv => kv.Key, kv => kv.Value); var diagnosticAnnotationPairs = new BidirectionalDictionary<Diagnostic, SyntaxAnnotation>(); CreateAnnotationForDiagnostics(diagnostics, annotationKind, diagnosticAnnotationPairs); root = GetRootWithAnnotatedElements(root, elementDiagnosticPairs, diagnosticAnnotationPairs); var currentDocument = document.WithSyntaxRoot(root); var annotatedElements = root.GetAnnotatedNodesAndTokens(annotationKind).ToList(); while(annotatedElements.Any()) { var element = annotatedElements.First(); var annotation = element.GetAnnotations(annotationKind).First(); var diagnostic = diagnosticAnnotationPairs.GetByB(annotation); var location = root.GetAnnotatedNodesAndTokens(annotation).FirstOrDefault().GetLocation(); if (location == null) { //annotation is already removed from the tree continue; } var newDiagnostic = Diagnostic.Create( diagnostic.Descriptor, location, diagnostic.AdditionalLocations, diagnostic.Properties); var fixes = new List<CodeAction>(); var context = new CodeFixContext(currentDocument, newDiagnostic, (a, d) => { lock (fixes) { fixes.Add(a); } }, fixAllContext.CancellationToken); await fixAllContext.CodeFixProvider.RegisterCodeFixesAsync(context).ConfigureAwait(false); var action = fixes.FirstOrDefault(fix => fix.EquivalenceKey == fixAllContext.CodeActionEquivalenceKey); if (action != null) { var operations = await action.GetOperationsAsync(fixAllContext.CancellationToken); var solution = operations.OfType<ApplyChangesOperation>().Single().ChangedSolution; currentDocument = solution.GetDocument(document.Id); root = await currentDocument.GetSyntaxRootAsync(fixAllContext.CancellationToken).ConfigureAwait(false); } root = RemoveAnnotationIfExists(root, annotation); currentDocument = document.WithSyntaxRoot(root); annotatedElements = root.GetAnnotatedNodesAndTokens(annotationKind).ToList(); } return await currentDocument.GetSyntaxRootAsync(fixAllContext.CancellationToken).ConfigureAwait(false); }
internal EnglishPluralizationService() { this.Culture = new CultureInfo("en"); this._userDictionary = new BidirectionalDictionary<string, string>(); this._irregularPluralsPluralizationService = new StringBidirectionalDictionary(this._irregularPluralsDictionary); this._assimilatedClassicalInflectionPluralizationService = new StringBidirectionalDictionary(this._assimilatedClassicalInflectionDictionary); this._oSuffixPluralizationService = new StringBidirectionalDictionary(this._oSuffixDictionary); this._classicalInflectionPluralizationService = new StringBidirectionalDictionary(this._classicalInflectionDictionary); this._wordsEndingWithSePluralizationService = new StringBidirectionalDictionary(this._wordsEndingWithSeDictionary); this._wordsEndingWithSisPluralizationService = new StringBidirectionalDictionary(this._wordsEndingWithSisDictionary); this._wordsEndingWithSusPluralizationService = new StringBidirectionalDictionary(this._wordsEndingWithSusDictionary); this._wordsEndingWithInxAnxYnxPluralizationService = new StringBidirectionalDictionary(this._wordsEndingWithInxAnxYnxDictionary); // verb this._irregularVerbPluralizationService = new StringBidirectionalDictionary(this._irregularVerbList); this._knownSingluarWords = new List<string>( _irregularPluralsDictionary.Keys .Concat(_assimilatedClassicalInflectionDictionary.Keys) .Concat(_oSuffixDictionary.Keys) .Concat(_classicalInflectionDictionary.Keys) .Concat(_irregularVerbList.Keys) .Concat(_irregularPluralsDictionary.Keys) .Concat(_wordsEndingWithSeDictionary.Keys) .Concat(_wordsEndingWithSisDictionary.Keys) .Concat(_wordsEndingWithSusDictionary.Keys) .Concat(_wordsEndingWithInxAnxYnxDictionary.Keys) .Concat(_uninflectiveWordList) .Except(this._knownConflictingPluralList)); // see the _knowConflictingPluralList comment above this._knownPluralWords = new List<string>( _irregularPluralsDictionary.Values .Concat(_assimilatedClassicalInflectionDictionary.Values) .Concat(_oSuffixDictionary.Values) .Concat(_classicalInflectionDictionary.Values) .Concat(_irregularVerbList.Values) .Concat(_irregularPluralsDictionary.Values) .Concat(_wordsEndingWithSeDictionary.Values) .Concat(_wordsEndingWithSisDictionary.Values) .Concat(_wordsEndingWithSusDictionary.Values) .Concat(_wordsEndingWithInxAnxYnxDictionary.Values) .Concat(_uninflectiveWordList)); }
private static BitArray UpdateBitArray(BidirectionalDictionary<string, BitArray> codecDomain, BitArray bitArrayOfInput, InputIndeces inputIndeces, string inputPart) { BitArray bitArrayOfInputPart; if (codecDomain.Forward.TryGetValue(inputPart, out bitArrayOfInputPart)) { bitArrayOfInput = AppendBitArray(bitArrayOfInput, bitArrayOfInputPart); inputIndeces.InputCharIndex++; inputIndeces.ReadIndex++; } else { throw new ArgumentException("The input cannot be encoded because it contains invalid part!", inputPart); } return bitArrayOfInput; }
private static BidirectionalDictionary<string, BitArray> InitializeBasesQualCodec() { var basesQual = new BidirectionalDictionary<string, BitArray>(new BitArrayEqualityComparer()); for (int intReprOfChar = 33 /*'!'*/; intReprOfChar <= 126 /*'~'*/; intReprOfChar++) { char ch = (char)intReprOfChar; string stringReprOfChar = new string(new char[] { ch }); string stringBitOfChar = ConvertQualityCharToBitString(intReprOfChar); basesQual.Add(stringReprOfChar, EncodeZeroOneStringToBitArrays(stringBitOfChar)); } return basesQual; }
private static BidirectionalDictionary<string, BitArray> InitializeBasesCodec() { var bases = new BidirectionalDictionary<string, BitArray>(new BitArrayEqualityComparer()); bases.Add(".", EncodeZeroOneStringToBitArrays(EncodingResource.bases_Dot)); bases.Add(",", EncodeZeroOneStringToBitArrays(EncodingResource.bases_Comma)); bases.Add("A", EncodeZeroOneStringToBitArrays(EncodingResource.bases_CapitalA)); bases.Add("a", EncodeZeroOneStringToBitArrays(EncodingResource.bases_SmallA)); bases.Add("C", EncodeZeroOneStringToBitArrays(EncodingResource.bases_CapitalC)); bases.Add("c", EncodeZeroOneStringToBitArrays(EncodingResource.bases_SmallC)); bases.Add("G", EncodeZeroOneStringToBitArrays(EncodingResource.bases_CapitalG)); bases.Add("g", EncodeZeroOneStringToBitArrays(EncodingResource.bases_SmallG)); bases.Add("T", EncodeZeroOneStringToBitArrays(EncodingResource.bases_CapitalT)); bases.Add("t", EncodeZeroOneStringToBitArrays(EncodingResource.bases_SmallT)); bases.Add("N", EncodeZeroOneStringToBitArrays(EncodingResource.bases_CapitalN)); bases.Add("n", EncodeZeroOneStringToBitArrays(EncodingResource.bases_SmallN)); bases.Add("*", EncodeZeroOneStringToBitArrays(EncodingResource.bases_Asterisk)); return bases; }
private static void CollectRemovableFieldLikeDeclarations(RemovableDeclarationCollector declarationCollector, HashSet <ISymbol> declaredPrivateSymbols, BidirectionalDictionary <ISymbol, SyntaxNode> fieldLikeSymbols) { var declarationKinds = new HashSet <SyntaxKind> { SyntaxKind.FieldDeclaration, SyntaxKind.EventFieldDeclaration }; var removableFieldsDefinitions = declarationCollector.GetRemovableFieldLikeDeclarations(declarationKinds, maxAccessibility); foreach (var fieldsDefinitions in removableFieldsDefinitions) { declaredPrivateSymbols.Add(fieldsDefinitions.Symbol); fieldLikeSymbols.Add(fieldsDefinitions.Symbol, fieldsDefinitions.SyntaxNode); } }
private static void InitializeCodecLength(Constants.CodecDomainNames codecDomainName, BidirectionalDictionary<string, BitArray> codec, Dictionary<Constants.CodecDomainNames, int> codecBitStringLengths) { var fixedLengthOfEncoder = CheckInitializedEncoder(codec); codecBitStringLengths.Add(codecDomainName, fixedLengthOfEncoder); }
/// <summary> /// A cached representation of the Enum string representation to respect per Enum field name. /// </summary> /// <param name="t">The type of the Enum.</param> /// <returns>A map of enum field name to either the field name, or the configured enum member name (<see cref="EnumMemberAttribute"/>).</returns> private BidirectionalDictionary<string, string> GetEnumNameMap(Type t) { BidirectionalDictionary<string, string> map; if (!_enumMemberNamesPerType.TryGetValue(t, out map)) { lock (_enumMemberNamesPerType) { if (_enumMemberNamesPerType.TryGetValue(t, out map)) return map; map = new BidirectionalDictionary<string, string>( StringComparer.OrdinalIgnoreCase, StringComparer.OrdinalIgnoreCase); foreach (FieldInfo f in t.GetFields()) { string n1 = f.Name; string n2; #if !NET20 n2 = f.GetCustomAttributes(typeof (EnumMemberAttribute), true) .Cast<EnumMemberAttribute>() .Select(a => a.Value) .SingleOrDefault() ?? f.Name; #else n2 = f.Name; #endif string s; if (map.TryGetBySecond(n2, out s)) { throw new InvalidOperationException("Enum name '{0}' already exists on enum '{1}'." .FormatWith(CultureInfo.InvariantCulture, n2, t.Name)); } map.Set(n1, n2); } _enumMemberNamesPerType[t] = map; } } return map; }
private static void CollectRemovableFieldLikeDeclarations(RemovableDeclarationCollector declarationCollector, HashSet<ISymbol> declaredPrivateSymbols, BidirectionalDictionary<ISymbol, SyntaxNode> fieldLikeSymbols) { var declarationKinds = ImmutableHashSet.Create(SyntaxKind.FieldDeclaration, SyntaxKind.EventFieldDeclaration); var removableFieldsDefinitions = declarationCollector.GetRemovableFieldLikeDeclarations(declarationKinds, maxAccessibility); foreach (var fieldsDefinitions in removableFieldsDefinitions) { declaredPrivateSymbols.Add(fieldsDefinitions.Symbol); fieldLikeSymbols.Add(fieldsDefinitions.Symbol, fieldsDefinitions.SyntaxNode); } }
public void Setup() { // Don't put these in constructor; constructor is only run once for all tests Dict = new BidirectionalDictionary<string, int>(); Dict.Add("one", 1); Dict.Add("two", 2); Dict.Add("three", 3); }
public LfFieldTypeMapper(BidirectionalDictionary<string, Type> map) { Map = map; }
public EnglishPluralizationService() { base.Culture = new CultureInfo("en"); this._userDictionary = new BidirectionalDictionary<string, string>(); this._irregularPluralsPluralizationService = new StringBidirectionalDictionary(this._irregularPluralsList); this._assimilatedClassicalInflectionPluralizationService = new StringBidirectionalDictionary(this._assimilatedClassicalInflectionList); this._oSuffixPluralizationService = new StringBidirectionalDictionary(this._oSuffixList); this._classicalInflectionPluralizationService = new StringBidirectionalDictionary(this._classicalInflectionList); this._wordsEndingWithSePluralizationService = new StringBidirectionalDictionary(this._wordsEndingWithSeList); this._wordsEndingWithSisPluralizationService = new StringBidirectionalDictionary(this._wordsEndingWithSisList); this._irregularVerbPluralizationService = new StringBidirectionalDictionary(this._irregularVerbList); this._knownSingluarWords = new List<string>(this._irregularPluralsList.Keys.Concat(this._assimilatedClassicalInflectionList.Keys).Concat(this._oSuffixList.Keys).Concat(this._classicalInflectionList.Keys).Concat(this._irregularVerbList.Keys).Concat(this._uninflectiveWords).Except(this._knownConflictingPluralList)); this._knownPluralWords = new List<string>(this._irregularPluralsList.Values.Concat(this._assimilatedClassicalInflectionList.Values).Concat(this._oSuffixList.Values).Concat(this._classicalInflectionList.Values).Concat(this._irregularVerbList.Values).Concat(this._uninflectiveWords)); }
private static string ResolvedEnumName(BidirectionalDictionary<string, string> map, string enumText) { string resolvedEnumName; map.TryGetBySecond(enumText, out resolvedEnumName); resolvedEnumName = resolvedEnumName ?? enumText; return resolvedEnumName; }
private static BidirectionalDictionary<string, BitArray> InitializeRefNucCodec() { var refNuc = new BidirectionalDictionary<string, BitArray>(new BitArrayEqualityComparer()); refNuc.Add("A", EncodeZeroOneStringToBitArrays(EncodingResource.refNuc_A)); refNuc.Add("C", EncodeZeroOneStringToBitArrays(EncodingResource.refNuc_C)); refNuc.Add("G", EncodeZeroOneStringToBitArrays(EncodingResource.refNuc_G)); refNuc.Add("T", EncodeZeroOneStringToBitArrays(EncodingResource.refNuc_T)); return refNuc; }
private void ReportIssues(SymbolAnalysisContext context, HashSet <ISymbol> usedSymbols, HashSet <ISymbol> declaredPrivateSymbols, HashSet <ISymbol> emptyConstructors, BidirectionalDictionary <ISymbol, SyntaxNode> fieldLikeSymbols) { var unusedSymbols = declaredPrivateSymbols .Except(usedSymbols.Union(emptyConstructors)) .ToList(); var alreadyReportedFieldLikeSymbols = new HashSet <ISymbol>(); var unusedSymbolSyntaxPairs = unusedSymbols .SelectMany(unusedSymbol => unusedSymbol.DeclaringSyntaxReferences .Select(r => new { Syntax = r.GetSyntax(), Symbol = unusedSymbol })); foreach (var unused in unusedSymbolSyntaxPairs) { var location = unused.Syntax.GetLocation(); var canBeFieldLike = unused.Symbol is IFieldSymbol || unused.Symbol is IEventSymbol; if (canBeFieldLike) { if (alreadyReportedFieldLikeSymbols.Contains(unused.Symbol)) { continue; } var variableDeclaration = GetVariableDeclaration(unused.Syntax); if (variableDeclaration == null) { continue; } var declarations = variableDeclaration.Variables .Select(v => fieldLikeSymbols.GetByB(v)) .ToList(); if (declarations.All(d => unusedSymbols.Contains(d))) { location = unused.Syntax.Parent.Parent.GetLocation(); alreadyReportedFieldLikeSymbols.UnionWith(declarations); } } var memberKind = GetMemberType(unused.Symbol); var memberName = GetMemberName(unused.Symbol); var effectiveAccessibility = unused.Symbol.GetEffectiveAccessibility(); if (effectiveAccessibility == Accessibility.Internal) { // We can't report internal members directly because they might be used through another assembly. possibleUnusedInternalMembers.Add( Diagnostic.Create(rule, location, "internal", memberKind, memberName)); continue; } if (effectiveAccessibility == Accessibility.Private) { context.ReportDiagnosticIfNonGenerated( Diagnostic.Create(rule, location, "private", memberKind, memberName), context.Compilation); } } }
private static BidirectionalDictionary<string, string> InitializeEnumType(Type type) { BidirectionalDictionary<string, string> map = new BidirectionalDictionary<string, string>( StringComparer.OrdinalIgnoreCase, StringComparer.OrdinalIgnoreCase); foreach (FieldInfo f in type.GetFields()) { string n1 = f.Name; string n2; #if !NET20 n2 = f.GetCustomAttributes(typeof(EnumMemberAttribute), true) .Cast<EnumMemberAttribute>() .Select(a => a.Value) .SingleOrDefault() ?? f.Name; #else n2 = f.Name; #endif string s; if (map.TryGetBySecond(n2, out s)) throw new InvalidOperationException("Enum name '{0}' already exists on enum '{1}'.".FormatWith(CultureInfo.InvariantCulture, n2, type.Name)); map.Set(n1, n2); } return map; }
protected sealed override void Initialize(SonarAnalysisContext context) { context.RegisterCompilationStartAction( c => { var shouldRaise = true; possibleUnusedInternalMembers = new ConcurrentBag <Diagnostic>(); c.RegisterSemanticModelAction( cc => { var isInternalsVisibleToAttributeFound = cc.SemanticModel.SyntaxTree.GetRoot() .DescendantNodes() .OfType <AttributeListSyntax>() .SelectMany(list => list.Attributes) .Any(a => IsInternalVisibleToAttribute(a, cc.SemanticModel)); if (isInternalsVisibleToAttributeFound) { shouldRaise = false; } }); c.RegisterSymbolAction( cc => { var namedType = (INamedTypeSymbol)cc.Symbol; if (!namedType.IsClassOrStruct() || namedType.ContainingType != null) { return; } var declarationCollector = new RemovableDeclarationCollector(namedType, cc.Compilation); var declaredPrivateSymbols = new HashSet <ISymbol>(); var fieldLikeSymbols = new BidirectionalDictionary <ISymbol, SyntaxNode>(); CollectRemovableNamedTypes(declarationCollector, declaredPrivateSymbols); CollectRemovableFieldLikeDeclarations(declarationCollector, declaredPrivateSymbols, fieldLikeSymbols); CollectRemovableEventsAndProperties(declarationCollector, declaredPrivateSymbols); CollectRemovableMethods(declarationCollector, declaredPrivateSymbols); if (!declaredPrivateSymbols.Any()) { return; } var usedSymbols = new HashSet <ISymbol>(); var emptyConstructors = new HashSet <ISymbol>(); var propertyAccessorAccess = new Dictionary <IPropertySymbol, AccessorAccess>(); CollectUsedSymbols(declarationCollector, usedSymbols, declaredPrivateSymbols, propertyAccessorAccess); CollectUsedSymbolsFromCtorInitializerAndCollectEmptyCtors(declarationCollector, usedSymbols, emptyConstructors); ReportIssues(cc, usedSymbols, declaredPrivateSymbols, emptyConstructors, fieldLikeSymbols); ReportUnusedPropertyAccessors(cc, usedSymbols, declaredPrivateSymbols, propertyAccessorAccess); }, SymbolKind.NamedType); c.RegisterCompilationEndAction( cc => { if (!shouldRaise) { return; } foreach (var diagnostic in possibleUnusedInternalMembers) { cc.ReportDiagnosticIfNonGenerated(diagnostic, cc.Compilation); } }); }); }
private static void ReportIssues(SymbolAnalysisContext context, HashSet<ISymbol> usedSymbols, HashSet<ISymbol> declaredPrivateSymbols, HashSet<ISymbol> emptyConstructors, BidirectionalDictionary<ISymbol, SyntaxNode> fieldLikeSymbols) { var unusedSymbols = declaredPrivateSymbols .Except(usedSymbols.Union(emptyConstructors)) .ToList(); var alreadyReportedFieldLikeSymbols = new HashSet<ISymbol>(); var unusedSymbolSyntaxPairs = unusedSymbols .SelectMany(unusedSymbol => unusedSymbol.DeclaringSyntaxReferences .Select(r => new { Syntax = r.GetSyntax(), Symbol = unusedSymbol })); foreach (var unused in unusedSymbolSyntaxPairs) { var location = unused.Syntax.GetLocation(); var canBeFieldLike = unused.Symbol is IFieldSymbol || unused.Symbol is IEventSymbol; if (canBeFieldLike) { if (alreadyReportedFieldLikeSymbols.Contains(unused.Symbol)) { continue; } var variableDeclaration = GetVariableDeclaration(unused.Syntax); if (variableDeclaration == null) { continue; } var declarations = variableDeclaration.Variables .Select(v => fieldLikeSymbols.GetByB(v)) .ToList(); if (declarations.All(d => unusedSymbols.Contains(d))) { location = unused.Syntax.Parent.Parent.GetLocation(); alreadyReportedFieldLikeSymbols.UnionWith(declarations); } } context.ReportDiagnosticIfNonGenerated(Diagnostic.Create(Rule, location), context.Compilation); } }