示例#1
0
        public override void OnConfigure(
            IDescriptorContext context,
            IObjectTypeDescriptor descriptor,
            Type type)
        {
            var nodeDescriptor = new NodeDescriptor(descriptor, type);

            descriptor.Extend().OnBeforeCreate(definition =>
            {
                // since we bind the id field late we need to hint to the type discovery
                // that we will need the ID scalar.
                definition.Dependencies.Add(
                    TypeDependency.FromSchemaType(
                        context.TypeInspector.GetType(typeof(IdType))));
            });

            descriptor.Extend().OnBeforeCompletion((descriptorContext, definition) =>
            {
                // first we try to resolve the id field.
                if (IdField is not null)
                {
                    MemberInfo?idField = type.GetMember(IdField).FirstOrDefault();

                    if (idField is null)
                    {
                        throw NodeAttribute_IdFieldNotFound(type, IdField);
                    }

                    nodeDescriptor.IdField(idField);
                }
                else if (context.TypeInspector.GetNodeIdMember(type) is { } id)
                {
                    nodeDescriptor.IdField(id);
                }
示例#2
0
        public static bool IsAllowedDependency(this TypeDependencyValidator typeDependencyValidator,
                                               string fromNamespace, string fromType, string toNamespace, string toType)
        {
            var typeDependency = new TypeDependency(fromNamespace, fromType, toNamespace, toType, DummySourceSegment);

            return(typeDependencyValidator.IsAllowedDependency(typeDependency));
        }
示例#3
0
        private static Diagnostic CreateIllegalDependencyDiagnostic(SyntaxNode node, TypeDependency typeDependency, IssueKind issueKind)
        {
            // TODO: get location from typeDependency.SourceSegment?
            var location = Location.Create(node.SyntaxTree, node.Span);
            var message  = IssueDefinitions.IllegalDependencyIssue.GetDynamicDescription(typeDependency);

            return(CreateDiagnostic(IllegalDependencyDescriptor, location, message, issueKind));
        }
示例#4
0
        public IDependencyDescriptor DependsOn <TType>(bool mustBeNamed)
            where TType : ITypeSystem
        {
            TypeDependencyKind kind = mustBeNamed
                ? TypeDependencyKind.Named
                : TypeDependencyKind.Default;

            _configuration.Dependencies.Add(
                TypeDependency.FromSchemaType(
                    typeof(TType), kind));

            return(this);
        }
示例#5
0
        public void DependencyWithMissingReferenceTest()
        {
            var constructor = new TypeDependencyConstructor();
            var dependency  = new TypeDependency(typeof(DependentService), new Dictionary <Type, IDependency>());

            Assert.Throws <NotImplementedException>(() =>
                                                    constructor.Construct(
                                                        dependency.OriginalType,
                                                        dependency,
                                                        new Dictionary <Type, Action <ILGenerator> >(),
                                                        new Dictionary <Type, IDependency>(),
                                                        new Stack <Type>()));
        }
示例#6
0
        public void RecursiveDependencyTest()
        {
            var constructor = new TypeDependencyConstructor();
            var dependency  = new TypeDependency(GetType(), new Dictionary <Type, IDependency>());

            dependency.SetServiceType <TypeDependencyConstructorTests>();

            Assert.Throws <InvalidOperationException>(() =>
                                                      constructor.Construct(
                                                          dependency.OriginalType,
                                                          dependency,
                                                          new Dictionary <Type, Action <ILGenerator> >(),
                                                          new Dictionary <Type, IDependency>(),
                                                          new Stack <Type>(Enumerable.Repeat(GetType(), 1))));
        }
示例#7
0
        public void DependencyWithDefaultConstructorTest()
        {
            var constructor = new TypeDependencyConstructor();
            var dependency  = new TypeDependency(typeof(PlainService), new Dictionary <Type, IDependency>());
            var knownTypes  = new Dictionary <Type, Action <ILGenerator> >();

            var action = constructor.Construct(
                dependency.OriginalType,
                dependency,
                knownTypes,
                new Dictionary <Type, IDependency>(),
                new Stack <Type>());

            Assert.IsNotEmpty(knownTypes);

            AssertIlValidity(action, dependency.OriginalType);
        }
        public override bool IsAllowedDependency(TypeDependency typeDependency)
        {
            if (typeDependency.FromNamespaceName == typeDependency.ToNamespaceName)
            {
                return(true);
            }

            var isAllowedDependency = _dependencyValidationCache.GetOrAdd(typeDependency, base.IsAllowedDependency, out var added);

            if (added)
            {
                MissCount++;
                LogTraceMessage($"Dependency {typeDependency} added to cache as {isAllowedDependency}.");
            }
            else
            {
                HitCount++;
            }

            return(isAllowedDependency);
        }
        protected void DependsOn(IExtendedType schemaType, bool mustBeNamedOrCompleted)
        {
            if (schemaType is null)
            {
                throw new ArgumentNullException(nameof(schemaType));
            }

            if (!schemaType.IsSchemaType)
            {
                throw new ArgumentException(
                          TypeResources.DependencyDescriptorBase_OnlyTsoIsAllowed,
                          nameof(schemaType));
            }

            TypeDependencyKind kind = mustBeNamedOrCompleted
                ? DependencyKind
                : TypeDependencyKind.Default;

            _configuration.AddDependency(
                TypeDependency.FromSchemaType(schemaType, kind));
        }
示例#10
0
        /// <summary>
        /// Decides whether a dependency is allowed based on the rule configuration.
        /// </summary>
        /// <param name="typeDependency">A dependency of two types.</param>
        /// <returns>True if the dependency is allowed, false otherwise.</returns>
        public virtual bool IsAllowedDependency(TypeDependency typeDependency)
        {
            // Inside a namespace all dependencies are allowed.
            if (typeDependency.FromNamespaceName == typeDependency.ToNamespaceName)
            {
                return(true);
            }

            // These namespace names are coming from a compiler so we don't have to validate them.
            var fromNamespace = new Namespace(typeDependency.FromNamespaceName, validate: false);
            var toNamespace   = new Namespace(typeDependency.ToNamespaceName, validate: false);

            var disallowRule = GetDisallowRule(fromNamespace, toNamespace);

            if (disallowRule != null)
            {
                return(false);
            }

            if (IsAllowedBecauseChildCanDependOnParent(fromNamespace, toNamespace))
            {
                return(true);
            }

            var allowRule = GetMostSpecificAllowRule(fromNamespace, toNamespace);

            if (allowRule == null)
            {
                return(false);
            }

            var visibleMembers = GetVisibleMembers(allowRule, toNamespace);

            if (visibleMembers == null || visibleMembers.Count == 0)
            {
                return(true);
            }

            return(visibleMembers.Contains(typeDependency.ToTypeName));
        }
        protected void DependsOn(Type schemaType, bool mustBeNamedOrCompleted)
        {
            if (schemaType == null)
            {
                throw new ArgumentNullException(nameof(schemaType));
            }

            if (!typeof(ITypeSystem).IsAssignableFrom(schemaType))
            {
                // TODO : resources
                throw new ArgumentException(
                          "Only type system objects are allowed.");
            }

            TypeDependencyKind kind = mustBeNamedOrCompleted
                ? DependencyKind
                : TypeDependencyKind.Default;

            _configuration.Dependencies.Add(
                TypeDependency.FromSchemaType(
                    schemaType, kind));
        }
        protected void DependsOn(Type schemaType, bool mustBeNamedOrCompleted)
        {
            if (schemaType == null)
            {
                throw new ArgumentNullException(nameof(schemaType));
            }

            if (!typeof(ITypeSystemMember).IsAssignableFrom(schemaType))
            {
                throw new ArgumentException(
                          TypeResources.DependencyDescriptorBase_OnlyTsoIsAllowed,
                          nameof(schemaType));
            }

            TypeDependencyKind kind = mustBeNamedOrCompleted
                ? DependencyKind
                : TypeDependencyKind.Default;

            _configuration.Dependencies.Add(
                TypeDependency.FromSchemaType(
                    schemaType, kind));
        }
示例#13
0
 private static string FormatIssue(TypeDependency typeDependency)
 {
     return($"{IssueDefinitions.IllegalDependencyIssue.GetDynamicDescription(typeDependency)} at {typeDependency.SourceSegment}");
 }
 public IllegalDependencyMessage(TypeDependency illegalDependency)
 {
     IllegalDependency = illegalDependency;
 }
示例#15
0
 public void AddDependency(TypeDependency dependency) => typeDependencies.Add(dependency);
        private static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine(@"Usage: SerializationDepthCheck [-u c:\path\to\unity] c:\path\to\project");
                Console.WriteLine();
                return;
            }

            string unityPath = DefaultUnityPath;

            if (args[0] == "-u")
            {
                unityPath = args[1];
            }

            if (!File.Exists(unityPath + @"\Editor\unity.exe"))
            {
                Console.WriteLine("Could not find Unity at " + unityPath + @"\Editor\unity.exe");
                Console.WriteLine("Please specify the correct path to Unity using the -u option.");
                Console.WriteLine();
                return;
            }

            string projectPath = args.Last();

            if (!Directory.Exists(projectPath) || !Directory.Exists(projectPath + @"\Library"))
            {
                Console.WriteLine("Could not find project library at \"{0}\\Library\".", projectPath);
                Console.WriteLine();
                return;
            }

            AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += ReflectionResolveAssembly;

            // Load all Unity assemblies
            UnityObjectType = LoadUnityAssemblies(unityPath);

            IEnumerable <Assembly> projectAssemblies = LoadProjectAssemblies(projectPath);

            List <Type> allProjectTypes = CollectProjectTypes(projectAssemblies);

            // Build list of all dependencies between types
            Dictionary <Type, List <TypeDependency> > dependencies = BuildTypeDependencies(allProjectTypes);

            Console.WriteLine();
            Console.WriteLine("-------------------------------------------------------");
            Console.WriteLine("Beginning walk of {0} types in dependency graph...", dependencies.Count);
            Console.WriteLine();

            // Consider every path from each root in turn
            var path = new TypeDependency[MaxSerializationDepth];

            foreach (Type root in allProjectTypes.Where(t => t.IsSubclassOf(UnityObjectType)))
            {
                WalkType(root, 0, path, dependencies);
            }

            Console.WriteLine();
            Console.WriteLine("...done.");
            Console.ReadKey();
        }
 void AddDependency(TypeReference dependentTypeRef, TypeDependency dependingMember)
 {
     HashSet<TypeDependency> members = null;
     if (!_usedTypeReferences.TryGetValue(dependentTypeRef, out members)) {
         members = new HashSet<TypeDependency>();
         _usedTypeReferences.Add(dependentTypeRef, members);
     }
     members.Add(dependingMember);
 }
        private static void WalkType(Type root, int level, TypeDependency[] path,
            Dictionary<Type, List<TypeDependency>> dependencies)
        {
            if (level >= path.Length)
            {
                // Found an invalid path
                Console.WriteLine("Serialization depth exceeded by the following member chain:");
                DisplayPath(path);
                Console.WriteLine();
                return;
            }

            List<TypeDependency> rootDeps;
            if (!dependencies.TryGetValue(root, out rootDeps) || rootDeps == null) return;

            foreach (TypeDependency dep in rootDeps)
            {
                path[level] = dep;
                WalkType(path[level].ToType, level + 1, path, dependencies);
            }
            path[level] = null;
        }
        private static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine(@"Usage: SerializationDepthCheck [-u c:\path\to\unity] c:\path\to\project");
                Console.WriteLine();
                return;
            }

            string unityPath = DefaultUnityPath;

            if (args[0] == "-u")
                unityPath = args[1];

            if (!File.Exists(unityPath + @"\Editor\unity.exe"))
            {
                Console.WriteLine("Could not find Unity at " + unityPath + @"\Editor\unity.exe");
                Console.WriteLine("Please specify the correct path to Unity using the -u option.");
                Console.WriteLine();
                return;
            }

            string projectPath = args.Last();
            if (!Directory.Exists(projectPath) || !Directory.Exists(projectPath + @"\Library"))
            {
                Console.WriteLine("Could not find project library at \"{0}\\Library\".", projectPath);
                Console.WriteLine();
                return;
            }

            AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += ReflectionResolveAssembly;

            // Load all Unity assemblies
            UnityObjectType = LoadUnityAssemblies(unityPath);

            IEnumerable<Assembly> projectAssemblies = LoadProjectAssemblies(projectPath);

            List<Type> allProjectTypes = CollectProjectTypes(projectAssemblies);

            // Build list of all dependencies between types
            Dictionary<Type, List<TypeDependency>> dependencies = BuildTypeDependencies(allProjectTypes);

            Console.WriteLine();
            Console.WriteLine("-------------------------------------------------------");
            Console.WriteLine("Beginning walk of {0} types in dependency graph...", dependencies.Count);
            Console.WriteLine();

            // Consider every path from each root in turn
            var path = new TypeDependency[MaxSerializationDepth];
            foreach (Type root in allProjectTypes.Where(t => t.IsSubclassOf(UnityObjectType)))
            {
                WalkType(root, 0, path, dependencies);
            }

            Console.WriteLine();
            Console.WriteLine("...done.");
            Console.ReadKey();
        }
示例#20
0
 public void AddDependency(TypeDependency dependency)
 => throw new NotSupportedException(
           "Create configurations do not support dependencies.");
示例#21
0
        private static void ReportIllegalDependency(SyntaxNodeAnalysisContext context, TypeDependency illegalDependency, IssueKind issueKind)
        {
            var diagnostic = CreateIllegalDependencyDiagnostic(context.Node, illegalDependency, issueKind);

            context.ReportDiagnostic(diagnostic);
        }
示例#22
0
 public void AddIllegalDependency(TypeDependency typeDependency) => _buffer.Add(new IllegalDependencyMessage(typeDependency));
 public IllegalDependencyMessage(TypeDependency illegalDependency, IssueKind issueKind)
 {
     IllegalDependency = illegalDependency;
     IssueKind         = issueKind;
 }
示例#24
0
 public IllegalDependencyMessage(TypeDependency illegalDependency, IssueKind issueKind)
     : base(IssueType.IllegalDependency, issueKind)
 {
     IllegalDependency = illegalDependency;
 }