Skip to content
64 changes: 22 additions & 42 deletions src/NetArchTest.Rules/Dependencies/DependencySearch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
using System.Collections.Generic;
using System.Linq;
using Mono.Cecil;

/// <summary>
/// Finds dependencies within a given set of types.
/// </summary>
Expand Down Expand Up @@ -50,43 +50,25 @@ internal IReadOnlyList<TypeDefinition> FindTypesWithAnyDependencies(IEnumerable<
/// <returns>A list of dependencies found in the input classes.</returns>
internal IReadOnlyList<TypeDefinition> FindTypesWithAllDependencies(IEnumerable<TypeDefinition> input, IEnumerable<string> dependencies)
{
var output = new List<TypeDefinition>();
var found = new List<string>();
var start = true;
// Set up the search definition
var results = new SearchDefinition(dependencies);

foreach (var dependency in dependencies)
// Check each type in turn
foreach (var type in input)
{
if (start || found.Count > 0)
{
// Set up the search definition
var results = new SearchDefinition(new string[] { dependency });

// Check each type in turn
foreach (var type in input)
{
CheckType(type, ref results);
}

if (start)
{
// Kick off the list of types that we have found
found = results.TypesFound.ToList();
start = false;
}
else
{
// Only select items that appear in both lists
found = found.Where(r => results.TypesFound.Contains(r)).ToList();
}
}
CheckType(type, ref results);
}

foreach (var typeFound in found)
var output = new List<TypeDefinition>();

foreach (var typeFound in results.TypesFound)
{
// NB: Nested classes won't be picked up here
var match = input.FirstOrDefault(d => d.FullName.Equals(typeFound, StringComparison.InvariantCultureIgnoreCase));
if (match != null)
if (match != null &&
results.GetAllDependenciesMatchingAnyOf(results.GetDependenciesFoundForType(typeFound)).Count() == results.UniqueDependenciesCount)
{
// Check found
output.Add(match);
}
}
Expand All @@ -112,12 +94,10 @@ private void CheckType(TypeDefinition type, ref SearchDefinition results)
var baseClass = type.BaseType?.Resolve();
if (baseClass != null)
{
foreach (var dependency in results.SearchList)
foreach (var dependency in results.GetAllMatchingDependencies(baseClass.FullName))
{
if (baseClass.FullName.StartsWith(dependency, StringComparison.InvariantCultureIgnoreCase))
{
results.AddToFound(type, dependency);
}

results.AddToFound(type, dependency);
}
}

Expand Down Expand Up @@ -160,7 +140,7 @@ private void CheckMethod(TypeDefinition type, MethodDefinition method, ref Searc
CheckGenericParameters(type, method.ReturnType.GenericParameters, ref results);
}

if (results.SearchList.Any(m => method.ReturnType.FullName.StartsWith(m)))
if (results.GetAllMatchingDependencies(method.ReturnType.FullName).Any())
{
results.AddToFound(type, method.ReturnType.FullName);
}
Expand Down Expand Up @@ -196,7 +176,7 @@ private void CheckProperties(TypeDefinition type, ref SearchDefinition results)
}

// Check the property type
if (results.SearchList.Any(m => property.PropertyType.FullName.StartsWith(m)))
if (results.GetAllMatchingDependencies(property.PropertyType.FullName).Any())
{
results.AddToFound(type, property.PropertyType.FullName);
}
Expand All @@ -219,7 +199,7 @@ private void CheckFields(TypeDefinition type, ref SearchDefinition results)
CheckGenericParameters(type, field.FieldType.GenericParameters, ref results);
}

if (results.SearchList.Any(m => field.FieldType.FullName.StartsWith(m)))
if (results.GetAllMatchingDependencies(field.FieldType.FullName).Any())
{
results.AddToFound(type, field.FieldType.FullName);
}
Expand Down Expand Up @@ -268,7 +248,7 @@ private void CheckMethodBody(TypeDefinition type, MethodDefinition method, ref S
CheckGenericParameters(type, variable.VariableType.GenericParameters, ref results);
}

if (results.SearchList.Any(m => variable.VariableType.FullName.StartsWith(m)))
if (results.GetAllMatchingDependencies(variable.VariableType.FullName).Any())
{
results.AddToFound(type, variable.VariableType.FullName);
}
Expand All @@ -281,7 +261,7 @@ private void CheckMethodBody(TypeDefinition type, MethodDefinition method, ref S
if (instruction.Operand != null)
{
var operands = instruction.Operand.ToString().Split(new char[] { ' ', '<', ',', '>' });
var matches = results.SearchList.Where(m => operands.Any(o => o.StartsWith(m))).ToArray();
var matches = results.GetAllDependenciesMatchingAnyOf(operands);
foreach (var item in matches)
{
results.AddToFound(type, item);
Expand All @@ -298,7 +278,7 @@ private static void CheckGenericParameters(TypeDefinition type, IEnumerable<Gene
{
foreach (var generic in parameters)
{
if (results.SearchList.Any(m => generic.FullName.StartsWith(m)))
if (results.GetAllMatchingDependencies(generic.FullName).Any())
{
results.AddToFound(type, generic.FullName);
}
Expand All @@ -310,7 +290,7 @@ private void CheckParameters(TypeDefinition type, IEnumerable<ParameterDefinitio
foreach (var parameter in parameters)
{
string fullName = parameter.ParameterType?.FullName ?? String.Empty;
if (results.SearchList.Any(m => fullName.StartsWith(m)))
if (results.GetAllMatchingDependencies(fullName).Any())
{
results.AddToFound(type, fullName);
}
Expand Down
190 changes: 190 additions & 0 deletions src/NetArchTest.Rules/Dependencies/NamespaceTree.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
namespace NetArchTest.Rules.Dependencies
{
using System;
using System.Collections.Generic;
using System.Text;

/// <summary>
/// Holds tree structure of full names; child nodes of each parent are indexed for optimal time of search.
/// </summary>
/// <example>
/// The sequence {"System.Linq", "System.Object", "System", "System.Collections.Generic", "NetArchTest.TestStructure.Dependencies.Examples"}
/// produces the tree
/// ""
/// |- "NetArchTest"
/// | |- "TestStructure"
/// | |- "Dependencies"
/// | |- "Examples" (terminated)
/// |
/// |- "System" (terminated)
/// |- "Collections"
/// | |- "Generic" (terminated)
/// |
/// |- "Linq" (terminated)
/// |- "Object" (terminated)
/// </example>
/// <remarks>
/// In the example above the flag "terminated" means that marked name is presented in the sequence the tree is built for.
/// Despite of the fact that the namespace "System" takes over its descendants "Linq", "Object" and "Collections.Generic"
/// all of them are presented in the tree. For dependency search it provides the same results as original implementation
/// based on the String.StartsWith(...) does.
/// </remarks>
internal class NamespaceTree
{
/// <summary>
/// Represents a node in the namespace tree.
/// </summary>
private sealed class Node
{
/// <summary> Maps child namespace to its root node. </summary>
private Dictionary<string, Node> Nodes { get; } = new Dictionary<string, Node>();

/// <summary> Returs node's "terminated" flag. </summary>
public bool IsTerminated
{
get; private set;
}

/// <summary>
/// Adds new child node with given name or returns existing one.
/// </summary>
/// <param name="name">Name of child node.</param>
/// <returns>Child node with given name.</returns>
public Node GetOrAddNode(string name)
{
name = NormalizeString(name);

Node result;
if (!Nodes.TryGetValue(name, out result))
{
result = new Node();
Nodes.Add(name, result);
}
return result;
}

/// <summary>
/// Checks whether child node with given name exists and returns it.
/// </summary>
/// <param name="name">Name of child node of interest.</param>
/// <param name="node">Child node with given name, if it exists; otherwise, null.</param>
/// <returns>True, if child node with given name exists; otherwise, false.</returns>
public bool TryGetNode(string name, out Node node)
{
return Nodes.TryGetValue(NormalizeString(name), out node) && node != null;
}

/// <summary>
/// Terminates the node.
/// </summary>
public void Terminate()
{
IsTerminated = true;
}

private static string NormalizeString(string str)
{
return str.Normalize(NormalizationForm.FormC);
}
}

/// <summary> Holds the root for the namespace tree. </summary>
private readonly Node _root = new Node();

private static readonly char[] _namespaceSeparators = new char[] { '.', '<', '>', ':' };

/// <summary>
/// Initially fills the tree with given names.
/// </summary>
/// <param name="fullNames">Sequence of full names.</param>
public NamespaceTree(IEnumerable<string> fullNames)
{
foreach (string fullName in fullNames)
{
Add(fullName);
}
}

/// <summary>
/// Splits full name into subnamespaces and adds corresponding nodes to the tree.
/// </summary>
/// <param name="fullName">Can be empty, but not null.</param>
private void Add(string fullName)
{
if (fullName == null)
{
throw new ArgumentNullException(nameof(fullName));
}

var deepestNode = _root;

int subnameEndIndex = -1;
while (subnameEndIndex != fullName.Length)
{
int subnameStartIndex = subnameEndIndex + 1;
subnameEndIndex = GetSubnameEndIndex(fullName, subnameStartIndex);

deepestNode = deepestNode.GetOrAddNode(fullName.Substring(subnameStartIndex, subnameEndIndex - subnameStartIndex));
}

if (!deepestNode.IsTerminated)
{
deepestNode.Terminate();
TerminatedNodesCount++;
}
}

/// <summary> Count of terminated nodes in the tree. </summary>
public int TerminatedNodesCount { get; private set; } = 0;

/// <summary>
/// Retrieves the sequence of all matching names for given full name.
/// A name matches some full name, if its node is terminated and whole path from tree root to that node
/// builds the chain of namespaces in the full name.
/// </summary>
/// <param name="fullName">Full name to search matching names for.</param>
/// <returns>Sequence of all matching names.</returns>
/// <example>
/// If the tree contains "System.Collections" and "System.Collections.IList", both are returned
/// for the full name "System.Collections.IList".
/// </example>
public IEnumerable<string> GetAllMatchingNames(string fullName)
{
var builder = new StringBuilder();

var deepestNode = _root;

int subnameEndIndex = -1;
while (subnameEndIndex != fullName.Length)
{
int subnameStartIndex = subnameEndIndex + 1;
subnameEndIndex = GetSubnameEndIndex(fullName, subnameStartIndex);

string name = fullName.Substring(subnameStartIndex, subnameEndIndex - subnameStartIndex);
if (!deepestNode.TryGetNode(name, out deepestNode))
{
yield break;
}

if (deepestNode.IsTerminated)
{
builder.Append(name);
yield return builder.ToString();

builder.Append('.');
}
}
}

private static int GetSubnameEndIndex(string namespaceFullName, int subnameStartIndex)
{
int nextSeparatorIndex = namespaceFullName.IndexOfAny(_namespaceSeparators, subnameStartIndex);
if (nextSeparatorIndex < 0)
{
nextSeparatorIndex = namespaceFullName.Length;
}

return nextSeparatorIndex;
}
}
}
Loading