Пример #1
0
        private static SessionContext GetSessionContext(string currentAssemblyLocation)
        {
            var configReader = new FilesystemConfigReader(new Filesystem(), new ConfigParser());

            ConfigSettings settings = configReader.GetConfig(currentAssemblyLocation);
            if (!settings.AssemblyLocations.Any())
                settings = configReader.GetConfig(Directory.GetCurrentDirectory());

            if (!settings.AssemblyLocations.Any() && !_assemblies.Any())
            {
                var message = "No storevil assemblies were found.\r\nCurrent location:"
                    + currentAssemblyLocation + "\r\nCurrent directory:"
                    + Directory.GetCurrentDirectory();

                _nunitAssertWrapper.Ignore(message);
            }

            var assemblyRegistry = new AssemblyRegistry(_assemblies.Select(x=>x.Location).Union(settings.AssemblyLocations));

            ParameterConverter.AddCustomConverters(assemblyRegistry);

            _sessionContext = new SessionContext(assemblyRegistry);
            _extensionMethodHandler = new ExtensionMethodHandler(assemblyRegistry);

            return _sessionContext;
        }
Пример #2
0
        public SameDomainHandlerFactory(AssemblyGenerator assemblyGenerator, AssemblyRegistry assemblyRegistry, IFilesystem filesystem)
        {
            _assemblyGenerator = assemblyGenerator;
            _assemblyRegistry = assemblyRegistry;

            _filesystem = filesystem;
        }
 public ExtensionMethodHandler(AssemblyRegistry assemblyRegistry)
 {
     foreach (var type in assemblyRegistry.GetStaticClasses())
     {
         AddExtensionMethods(type);
     }
 }
Пример #4
0
 protected DriverBase(IEventBus eventBus)
 {
     //ResultListener = resultListener;
     _eventBus = eventBus;
     var assemblyRegistry = new AssemblyRegistry(GetAssemblies());
     ScenarioInterpreter = new ScenarioInterpreter(new InterpreterForTypeFactory(assemblyRegistry), new MostRecentlyUsedContext(), new DefaultLanguageService());
     LineExecuter = new ScenarioLineExecuter(ScenarioInterpreter, _eventBus);
     _context = new SessionContext(assemblyRegistry);
     ParameterConverter.AddCustomConverters(assemblyRegistry);
 }
Пример #5
0
        public RemoteScenarioExecutor(IRemoteTaskServer server, AssemblyRegistry assemblyRegistry)
        {
            _server = server;
            _assemblyRegistry = assemblyRegistry;
            _sessionContext = new SessionContext(assemblyRegistry);

            _eventBus = new EventBus();
            _listener = new ResharperResultListener(_server);

            _resolver = new MostRecentlyUsedContext();
            _runner = BuildInPlaceRunner(_resolver);

            _eventBus.Register(_resolver);
            _eventBus.Register(_listener);
        }
Пример #6
0
        public RemoteScenarioExecutor(IRemoteTaskServer server, AssemblyRegistry assemblyRegistry)
        {
            _server = server;
            _assemblyRegistry = assemblyRegistry;
            _sessionContext = new SessionContext(assemblyRegistry);

            _eventBus = new EventBus();

            new EventBusAutoRegistrar(_assemblyRegistry).InstallTo(_eventBus);
            _listener = new ResharperResultListener(_server);

            _resolver = new MostRecentlyUsedContext();
            _runner = BuildInPlaceRunner(_resolver);

            _eventBus.Register(_resolver);
            _eventBus.Register(_listener);

            ParameterConverter.AddCustomConverters(_assemblyRegistry);
        }
Пример #7
0
        /// <summary>
        /// Loads application settings from a configuration file <c>config.ini</c> in the roaming folder.
        /// </summary>
        public AppSettings LoadAppSettings()
        {
            // Note: cannot log in this method, since it might be invoked in static ctor of the logger when using Stride.Core.Diagnostics.Logger
            if (!VirtualFileSystem.ApplicationRoaming.FileExists("config.ini"))
            {
                return(new AppSettings());
            }

            IEnumerable <IniParser.Record> records;

            using (var configFile = VirtualFileSystem.ApplicationRoaming.OpenStream("config.ini", VirtualFileMode.Open, VirtualFileAccess.Read))
                records = IniParser.Parse(configFile);

            var availableSettings = AssemblyRegistry.FindAll()
                                    .SelectMany(assembly => (IReadOnlyCollection <Type>)AssemblyRegistry.GetScanTypes(assembly)?.Types
                                                .GetValueOrDefault(typeof(ConfigurationSectionAttribute)) ?? Type.EmptyTypes)
                                    .Select(type => (type.GetCustomAttribute <ConfigurationSectionAttribute>()?.SectionName, type))
                                    .Where(pair => !string.IsNullOrWhiteSpace(pair.SectionName))
                                    .ToDictionary(pair => pair.SectionName, pair => pair.type);

            var sections = new Dictionary <string, object>();

            foreach (var record in records)
            {
                if (!sections.TryGetValue(record.Section, out object setting) &&
                    availableSettings.ContainsKey(record.Section))
                {
                    setting = Activator.CreateInstance(availableSettings[record.Section]);
                    sections.Add(record.Section, setting);
                }

                if (setting == null)
                {
                    continue;
                }

                var type = availableSettings[record.Section];
                var prop = type.GetProperty(record.Key);

                if (prop == null)
                {
                    continue;
                }

                if (prop.PropertyType == typeof(string))
                {
                    prop.SetValue(setting, record.Value);
                }
                else if (prop.PropertyType.IsEnum && Enum.TryParse(prop.PropertyType, record.Value, out object enumValue))
                {
                    prop.SetValue(setting, enumValue);
                }
                else if (prop.PropertyType.IsPrimitive)
                {
                    if (record.Value.Contains('.') && double.TryParse(record.Value, out var doubleValue))
                    {
                        prop.SetValue(setting, Convert.ChangeType(doubleValue, prop.PropertyType));
                    }
                    else if (long.TryParse(record.Value, out var longValue))
                    {
                        prop.SetValue(setting, Convert.ChangeType(longValue, prop.PropertyType));
                    }
                }
            }

            return(new AppSettings(sections.Values));
        }
Пример #8
0
        private void CollectNewProcessorsByComponentType(TypeInfo componentType)
        {
            if (componentTypes.Contains(componentType))
            {
                return;
            }

            componentTypes.Add(componentType);
            OnComponentTypeAdded(componentType);

            // Automatically collect processors that are used by this component
            var processorAttributes = componentType.GetCustomAttributes <DefaultEntityComponentProcessorAttribute>();

            foreach (var processorAttributeType in processorAttributes)
            {
                var processorType = AssemblyRegistry.GetType(processorAttributeType.TypeName);
                if (processorType == null || !typeof(EntityProcessor).GetTypeInfo().IsAssignableFrom(processorType.GetTypeInfo()))
                {
                    // TODO: log an error if type is not of EntityProcessor
                    continue;
                }

                // Filter using ExecutionMode
                if ((ExecutionMode & processorAttributeType.ExecutionMode) != ExecutionMode.None)
                {
                    // Make sure that we are adding a processor of the specified type only if it is not already in the list or pending

                    // 1) Check in the list of existing processors
                    var addNewProcessor = true;
                    for (int i = 0; i < processors.Count; i++)
                    {
                        if (processorType == processors[i].GetType())
                        {
                            addNewProcessor = false;
                            break;
                        }
                    }
                    if (addNewProcessor)
                    {
                        // 2) Check in the list of pending processors
                        for (int i = 0; i < pendingProcessors.Count; i++)
                        {
                            if (processorType == pendingProcessors[i].GetType())
                            {
                                addNewProcessor = false;
                                break;
                            }
                        }

                        // If not found, we can add this processor
                        if (addNewProcessor)
                        {
                            var processor = (EntityProcessor)Activator.CreateInstance(processorType);
                            pendingProcessors.Add(processor);

                            // Collect dependencies
                            foreach (var subComponentType in processor.RequiredTypes)
                            {
                                CollectNewProcessorsByComponentType(subComponentType);
                            }
                        }
                    }
                }
            }
        }
Пример #9
0
 public static void Initialize()
 {
     AssemblyRegistry.Register(typeof(Module).GetTypeInfo().Assembly, AssemblyCommonCategories.Assets);
 }
Пример #10
0
        public override void Serialize(ref T obj, ArchiveMode mode, SerializationStream stream)
        {
            var referenceSerialization   = stream.Context.Get(ContentSerializerContext.SerializeAttachedReferenceProperty);
            var contentSerializerContext = stream.Context.Get(ContentSerializerContext.ContentSerializerContextProperty);

            if (contentSerializerContext != null)
            {
                if (mode == ArchiveMode.Serialize)
                {
                    var contentReference = new ContentReference <T>(obj);
                    int index            = contentSerializerContext.AddContentReference(contentReference);
                    stream.Write(index);
                }
                else
                {
                    int index            = stream.ReadInt32();
                    var contentReference = contentSerializerContext.GetContentReference <T>(index);
                    obj = contentReference.Value;
                    if (obj == null)
                    {
                        // Check if already deserialized
                        var assetReference = contentSerializerContext.ContentManager.FindDeserializedObject(contentReference.Location, typeof(T));
                        if (assetReference != null)
                        {
                            obj = (T)assetReference.Object;
                            if (obj != null)
                            {
                                contentReference.Value = obj;
                            }
                        }
                    }

                    if (obj == null && contentSerializerContext.LoadContentReferences)
                    {
                        var contentSerializer = cachedContentSerializer ?? (cachedContentSerializer = contentSerializerContext.ContentManager.Serializer.GetSerializer(null, typeof(T)));
                        if (contentSerializer == null)
                        {
                            // Need to read chunk header to know actual type (note that we can't cache it in cachedContentSerializer as it depends on content)
                            var chunkHeader = contentSerializerContext.ContentManager.ReadChunkHeader(contentReference.Location);
                            if (chunkHeader == null || (contentSerializer = contentSerializerContext.ContentManager.Serializer.GetSerializer(AssemblyRegistry.GetType(chunkHeader.Type), typeof(T))) == null)
                            {
                                throw new InvalidOperationException($"Could not find a valid content serializer for {typeof(T)} when loading {contentReference.Location}");
                            }
                        }

                        // First time, let's create it
                        if (contentSerializerContext.ContentManager.Exists(contentReference.Location))
                        {
                            obj = (T)contentSerializer.Construct(contentSerializerContext);
                            contentSerializerContext.ContentManager.RegisterDeserializedObject(contentReference.Location, obj);
                            contentReference.Value = obj;
                        }
                    }
                }
            }
            else if (referenceSerialization == ContentSerializerContext.AttachedReferenceSerialization.AsNull)
            {
                if (mode == ArchiveMode.Deserialize)
                {
                    obj = default(T);
                }
            }
            else if (referenceSerialization == ContentSerializerContext.AttachedReferenceSerialization.AsSerializableVersion)
            {
                if (mode == ArchiveMode.Serialize)
                {
                    // This case will happen when serializing build engine command hashes: we still want Location to still be written
                    var attachedReference = AttachedReferenceManager.GetAttachedReference(obj);
                    if (attachedReference?.Url == null)
                    {
                        throw new InvalidOperationException("Error when serializing reference.");
                    }

                    // TODO: Do not use string
                    stream.Write(obj.GetType().AssemblyQualifiedName);
                    stream.Write(attachedReference.Id);
                    stream.Write(attachedReference.Url);
                }
                else
                {
                    var type = AssemblyRegistry.GetType(stream.ReadString());
                    var id   = stream.Read <AssetId>();
                    var url  = stream.ReadString();

                    obj = (T)AttachedReferenceManager.CreateProxyObject(type, id, url);
                }
            }
            else
            {
                // This case will happen when serializing build engine command hashes: we still want Location to still be written
                if (mode == ArchiveMode.Serialize)
                {
                    // This case will happen when serializing build engine command hashes: we still want Location to still be written
                    var attachedReference = AttachedReferenceManager.GetAttachedReference(obj);
                    if (attachedReference?.Url == null)
                    {
                        throw new InvalidOperationException("Error when serializing reference.");
                    }

                    stream.Write(attachedReference.Url);
                }
                else
                {
                    // No real case yet
                    throw new NotSupportedException();
                }
            }
        }
Пример #11
0
        public void Reload()
        {
            CloneReferenceSerializer.References = new List <object>();

            var loadedAssembliesSet = new HashSet <Assembly>(assembliesToUnregister);
            var reloadedScripts     = CollectReloadedScriptEntries(loadedAssembliesSet);

            foreach (var assembly in assembliesToUnregister)
            {
                // Unregisters assemblies that have been registered in Package.Load => Package.LoadAssemblyReferencesForPackage
                AssemblyRegistry.Unregister(assembly);

                // Unload binary serialization
                DataSerializerFactory.UnregisterSerializationAssembly(assembly);

                // Unload assembly
                assemblyContainer.UnloadAssembly(assembly);
            }

            foreach (var assembly in assembliesToRegister)
            {
                ModuleRuntimeHelpers.RunModuleConstructor(assembly.ManifestModule);

                // Unregisters assemblies that have been registered in Package.Load => Package.LoadAssemblyReferencesForPackage
                AssemblyRegistry.Register(assembly, AssemblyCommonCategories.Assets);

                DataSerializerFactory.RegisterSerializationAssembly(assembly);
            }

            // First pass of deserialization: recreate the scripts
            foreach (ReloadedScriptEntryLive reloadedScript in reloadedScripts)
            {
                // Try to create object
                var objectStart = reloadedScript.YamlEvents.OfType <SharpYaml.Events.MappingStart>().FirstOrDefault();
                if (objectStart != null)
                {
                    // Get type info
                    var  objectStartTag = objectStart.Tag;
                    bool alias;
                    var  scriptType = YamlSerializer.GetSerializerSettings().TagTypeRegistry.TypeFromTag(objectStartTag, out alias);
                    if (scriptType != null)
                    {
                        reloadedScript.NewScript = (Script)Activator.CreateInstance(scriptType);
                    }
                }
            }

            // Second pass: update script references in live objects
            // As a result, any script references processed by Yaml serializer will point to updated objects (script reference cycle will work!)
            for (int index = 0; index < CloneReferenceSerializer.References.Count; index++)
            {
                var script = CloneReferenceSerializer.References[index] as Script;
                if (script != null)
                {
                    var reloadedScript = reloadedScripts.Cast <ReloadedScriptEntryLive>().FirstOrDefault(x => x.OriginalScript == script);
                    if (reloadedScript != null)
                    {
                        CloneReferenceSerializer.References[index] = reloadedScript.NewScript;
                    }
                }
            }

            // Third pass: deserialize
            RestoreReloadedScriptEntries(reloadedScripts);

            CloneReferenceSerializer.References = null;
        }
Пример #12
0
        public async Task AnalyzeProject(SessionViewModel session, Project project, CancellationToken token)
        {
            //Handle Scripts discovery
            var gameProjectCompilation = await project.GetCompilationAsync(token);

            // Update latest compilation
            LatestCompilation = gameProjectCompilation;
            LatestCompilationChanged?.Invoke(this, EventArgs.Empty);

            var assemblyFullName = gameProjectCompilation.Assembly.Identity.GetDisplayName();

            var xenkoScriptType = gameProjectCompilation.GetTypeByMetadataName(typeof(ScriptComponent).FullName);

            var symbols = gameProjectCompilation.GetSymbolsWithName(x => true, SymbolFilter.Type).Cast <ITypeSymbol>().ToList();

            if (!symbols.Any())
            {
                return;
            }

            var assembly = AssemblyRegistry.FindAll()?.FirstOrDefault(x => x.FullName == assemblyFullName);

            if (assembly == null)
            {
                return;
            }

            var types = assembly.GetTypes();

            var typesDict = new Dictionary <string, List <Type> >();

            foreach (var symbol in symbols)
            {
                //recurse basetypes up to finding Script type
                var baseType   = symbol.BaseType;
                var scriptType = false;
                while (baseType != null)
                {
                    if (baseType == xenkoScriptType)
                    {
                        scriptType = true;
                        break;
                    }
                    baseType = baseType.BaseType;
                }

                if (!scriptType)
                {
                    continue;
                }

                //find the script paths, (could be multiple in the case of partial)
                foreach (var location in symbol.Locations)
                {
                    var csPath = new UFile(location.SourceTree.FilePath);

                    //find the real type, and add to the dictionary
                    var realType = types.FirstOrDefault(x => x.Name == symbol.Name && x.Namespace == symbol.GetFullNamespace());

                    if (!typesDict.ContainsKey(csPath))
                    {
                        typesDict.Add(csPath, new List <Type> {
                            realType
                        });
                    }
                    else
                    {
                        typesDict[csPath].Add(realType);
                    }
                }
            }

            lock (this)
            {
                foreach (var x in typesDict)
                {
                    typesForPath[x.Key] = x.Value;
                }

                //clean up paths that do not exist anymore
                var toRemove = typesForPath.Where(x => !File.Exists(x.Key)).Select(x => x.Key).ToList();
                typesForPath.RemoveWhere(x => toRemove.Contains(x.Key));
            }
        }
 private TypeReference GetFunctorType(TypeReference returnType, params TypeReference[] args)
 {
     return(AssemblyRegistry.GetFunctorType(assemblyEmitter, returnType, args));
 }
Пример #14
0
        /// <inheritdoc/>
        public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var typeName = value.ToString();

            return(typeName == NullObjectType ? null : AssemblyRegistry.GetType(typeName));
        }
Пример #15
0
        public TypeReference GetContainedType(string name)
        {
            var full = Name + "." + name;

            return(AssemblyRegistry.FindType(assembly, full));
        }
Пример #16
0
 static TestSerializing()
 {
     AssemblyRegistry.Register(typeof(TestSerializing).Assembly, AssemblyCommonCategories.Assets);
 }
Пример #17
0
        private object DeserializeObject(Queue <DeserializeOperation> serializeOperations, Reference parentReference, string url, Type objType, object obj, ContentManagerLoaderSettings settings)
        {
            // Try to find already loaded object
            Reference reference = FindDeserializedObject(url, objType);

            if (reference != null && reference.Deserialized)
            {
                // Add reference
                bool isRoot = parentReference == null;
                if (isRoot || parentReference.References.Add(reference))
                {
                    IncrementReference(reference, isRoot);
                }

                return(reference.Object);
            }

            if (!FileProvider.FileExists(url))
            {
                HandleAssetNotFound(url);
                return(null);
            }

            ContentSerializerContext contentSerializerContext;
            object result;

            // Open asset binary stream
            try
            {
                using (var stream = FileProvider.OpenStream(url, VirtualFileMode.Open, VirtualFileAccess.Read))
                {
                    // File does not exist
                    // TODO/Benlitz: Add a log entry for that, it's not expected to happen
                    if (stream == null)
                    {
                        return(null);
                    }

                    Type headerObjType = null;

                    // Read header
                    var streamReader = new BinarySerializationReader(stream);
                    var chunkHeader  = ChunkHeader.Read(streamReader);
                    if (chunkHeader != null)
                    {
                        headerObjType = AssemblyRegistry.GetType(chunkHeader.Type);
                    }

                    // Find serializer
                    var serializer = Serializer.GetSerializer(headerObjType, objType);
                    if (serializer == null)
                    {
                        throw new InvalidOperationException(string.Format("Content serializer for {0}/{1} could not be found.", headerObjType, objType));
                    }
                    contentSerializerContext = new ContentSerializerContext(url, ArchiveMode.Deserialize, this)
                    {
                        LoadContentReferences = settings.LoadContentReferences
                    };

                    // Read chunk references
                    if (chunkHeader != null && chunkHeader.OffsetToReferences != -1)
                    {
                        // Seek to where references are stored and deserialize them
                        streamReader.NativeStream.Seek(chunkHeader.OffsetToReferences, SeekOrigin.Begin);
                        contentSerializerContext.SerializeReferences(streamReader);
                        streamReader.NativeStream.Seek(chunkHeader.OffsetToObject, SeekOrigin.Begin);
                    }

                    if (reference == null)
                    {
                        // Create Reference
                        reference = new Reference(url, parentReference == null);
                        result    = obj ?? serializer.Construct(contentSerializerContext);
                        SetAssetObject(reference, result);
                    }
                    else
                    {
                        result = reference.Object;
                    }

                    reference.Deserialized = true;

                    PrepareSerializerContext(contentSerializerContext, streamReader.Context);

                    contentSerializerContext.SerializeContent(streamReader, serializer, result);

                    // Add reference
                    if (parentReference != null)
                    {
                        parentReference.References.Add(reference);
                    }
                }
            }
            catch (Exception exception)
            {
                throw new ContentManagerException(string.Format("Unexpected exception while loading asset [{0}]. Reason: {1}. Check inner-exception for details.", url, exception.Message), exception);
            }

            if (settings.LoadContentReferences)
            {
                // Process content references
                // TODO: Should we work at ChunkReference level?
                foreach (var contentReference in contentSerializerContext.ContentReferences)
                {
                    bool shouldBeLoaded = true;

                    //Reference childReference;

                    settings.ContentFilter?.Invoke(contentReference, ref shouldBeLoaded);

                    if (shouldBeLoaded)
                    {
                        serializeOperations.Enqueue(new DeserializeOperation(reference, contentReference.Location, contentReference.Type, contentReference.ObjectValue));
                    }
                }
            }

            return(result);
        }
Пример #18
0
 public InterpreterForTypeFactory(AssemblyRegistry assemblyRegistry)
 {
     _extensionMethodHandler = new ExtensionMethodHandler(assemblyRegistry);
     _contextTypeFactory     = new ContextTypeFactory(_extensionMethodHandler);
 }
 public static TypeReference GetNestedType(this TypeReference type, AssemblyEmitter assembly, string name)
 {
     return(AssemblyRegistry.FindType(assembly, type.FullName + "." + name));
 }
 public static IEnumerable <MethodReference> GetOperatorMethods(AssemblyEmitter assembly, IExpressionNode operand, string name)
 {
     return(operand.ExpressionReturnType.IsTypeless() ? new MethodReference[0] : AssemblyRegistry.GetMethods(assembly, operand.ExpressionReturnType, name));
 }
Пример #21
0
 public Classifier(AssemblyRegistry assemblyRegistry)
 {
     _parser = new StoryParser();
     _scenarioInterpreter = new StandardScenarioInterpreter(assemblyRegistry);
     _context = new SessionContext(assemblyRegistry).GetContextForStory().GetScenarioContext();
 }
Пример #22
0
 internal static void Initialize()
 {
     AssemblyRegistry.Register(typeof(Module).Assembly, AssemblyCommonCategories.Assets);
     AssetQuantumRegistry.RegisterAssembly(typeof(Module).Assembly);
     RuntimeHelpers.RunModuleConstructor(typeof(Asset).Module.ModuleHandle);
 }
Пример #23
0
        /// <summary>
        /// Compiles a list of update operations into a <see cref="CompiledUpdate"/>, for use with <see cref="Run"/>.
        /// </summary>
        /// <param name="rootObjectType">The type of the root object.</param>
        /// <param name="animationPaths">The different paths and source offsets to use when <see cref="Run"/> is applied.</param>
        /// <returns>A <see cref="CompiledUpdate"/> object that can be used for <see cref="Run"/>.</returns>
        public static CompiledUpdate Compile(Type rootObjectType, List <UpdateMemberInfo> animationPaths)
        {
            var currentPath          = string.Empty;
            var temporaryObjectsList = new List <object>();

            var state = new ComputeUpdateOperationState();

            state.UpdateOperations = new List <UpdateOperation>();
            state.StackPath        = new List <AnimationBuilderStackEntry>
            {
                new AnimationBuilderStackEntry(rootObjectType, 0, 0, -1),
            };

            foreach (var animationPath in animationPaths)
            {
                var commonPathParts = 1;

                // Detect how much of the path is unmodified (note: we start from 1 because root always stay there)
                for (int index = 1; index < state.StackPath.Count; index++)
                {
                    var pathPart = state.StackPath[index];

                    // Check if next path part is the same (first check length then content)
                    if (((animationPath.Name.Length == pathPart.EndIndex) ||
                         (animationPath.Name.Length > pathPart.EndIndex && (animationPath.Name[pathPart.EndIndex] == PathDelimiter || animationPath.Name[pathPart.EndIndex] == PathIndexerOpen))) &&
                        string.Compare(animationPath.Name, pathPart.StartIndex, currentPath, pathPart.StartIndex, pathPart.EndIndex - pathPart.StartIndex, StringComparison.Ordinal) == 0)
                    {
                        commonPathParts++;
                        continue;
                    }

                    break;
                }

                PopObjects(ref state, commonPathParts);

                // Parse the new path parts
                state.ParseElementStart = state.StackPath.Last().EndIndex;

                // Compute offset from start of current object
                state.NewOffset = state.StackPath.Last().ObjectStartOffset;

                while (state.ParseElementStart < animationPath.Name.Length)
                {
                    var containerType = state.StackPath.Last().Type;

                    // We have only two cases for now: array or property/field name
                    bool isIndexerAccess = animationPath.Name[state.ParseElementStart] == PathIndexerOpen;
                    if (isIndexerAccess)
                    {
                        // Parse until end of indexer
                        state.ParseElementEnd = animationPath.Name.IndexOf(PathIndexerClose, state.ParseElementStart + 1);
                        if (state.ParseElementEnd == -1)
                        {
                            throw new InvalidOperationException("Property path parse error: could not find indexer end ']'");
                        }

                        // Include the indexer close
                        state.ParseElementEnd++;

                        // Parse integer
                        // TODO: Avoid substring?
                        var indexerString = animationPath.Name.Substring(state.ParseElementStart + 1, state.ParseElementEnd - state.ParseElementStart - 2);

                        // T[], IList<T>, etc...
                        // Try to resolve using custom resolver
                        UpdatableMember updatableMember = null;
                        var             parentType      = containerType;
                        while (parentType != null)
                        {
                            UpdateMemberResolver resolver;
                            if (MemberResolvers.TryGetValue(parentType, out resolver))
                            {
                                updatableMember = resolver.ResolveIndexer(indexerString);
                                if (updatableMember != null)
                                {
                                    break;
                                }
                            }

                            parentType = parentType.GetTypeInfo().BaseType;
                        }

                        // Try interfaces
                        if (updatableMember == null)
                        {
                            foreach (var implementedInterface in containerType.GetTypeInfo().ImplementedInterfaces)
                            {
                                UpdateMemberResolver resolver;
                                if (MemberResolvers.TryGetValue(implementedInterface, out resolver))
                                {
                                    updatableMember = resolver.ResolveIndexer(indexerString);
                                    if (updatableMember != null)
                                    {
                                        break;
                                    }
                                }
                            }
                        }

                        if (updatableMember == null)
                        {
                            throw new InvalidOperationException(string.Format("Property path parse error: could not find binding info for index {0} in type {1}", indexerString, containerType));
                        }

                        ProcessMember(ref state, animationPath, updatableMember, temporaryObjectsList);
                    }
                    else
                    {
                        // Note: first character might be a . delimiter, if so, skip it
                        var propertyStart = state.ParseElementStart;
                        if (animationPath.Name[propertyStart] == PathDelimiter)
                        {
                            propertyStart++;
                        }

                        // Check if it started with a parenthesis (to perform a cast operation)
                        if (animationPath.Name[propertyStart] == PathCastOpen)
                        {
                            // Parse until end of cast operation
                            state.ParseElementEnd = animationPath.Name.IndexOf(PathCastClose, ++propertyStart);
                            if (state.ParseElementEnd == -1)
                            {
                                throw new InvalidOperationException("Property path parse error: could not find cast operation ending ')'");
                            }

                            var typeName = animationPath.Name.Substring(propertyStart, state.ParseElementEnd - propertyStart);

                            // Include the indexer close
                            state.ParseElementEnd++;

                            // Try to resolve using alias first, then full assembly registry using assembly qualified name
                            var type = DataSerializerFactory.GetTypeFromAlias(typeName) ?? AssemblyRegistry.GetType(typeName);
                            if (type == null)
                            {
                                throw new InvalidOperationException($"Could not resolve type {typeName}");
                            }

                            // Push entry with new type
                            // TODO: Should we actually perform an early castclass and skip if type is incorrect?
                            state.StackPath.Add(new AnimationBuilderStackEntry(type, state.ParseElementStart, state.ParseElementEnd, -1)
                            {
                                ObjectStartOffset = state.NewOffset,
                            });
                        }
                        else
                        {
                            UpdatableMember updatableMember;

                            // Parse until end next group (or end)
                            state.ParseElementEnd = animationPath.Name.IndexOfAny(PathGroupDelimiters, state.ParseElementStart + 1);
                            if (state.ParseElementEnd == -1)
                            {
                                state.ParseElementEnd = animationPath.Name.Length;
                            }

                            // TODO: Avoid substring?
                            var propertyName = animationPath.Name.Substring(propertyStart, state.ParseElementEnd - propertyStart);
                            if (!UpdateKeys.TryGetValue(new UpdateKey(containerType, propertyName), out updatableMember))
                            {
                                // Try to resolve using custom resolver
                                var parentType = containerType;
                                while (parentType != null)
                                {
                                    UpdateMemberResolver resolver;
                                    if (MemberResolvers.TryGetValue(parentType, out resolver))
                                    {
                                        updatableMember = resolver.ResolveProperty(propertyName);
                                        if (updatableMember != null)
                                        {
                                            break;
                                        }
                                    }

                                    parentType = parentType.GetTypeInfo().BaseType;
                                }

                                if (updatableMember == null)
                                {
                                    throw new InvalidOperationException(string.Format("Property path parse error: could not find binding info for member {0} in type {1}", propertyName, containerType));
                                }
                            }

                            // Process member
                            ProcessMember(ref state, animationPath, updatableMember, temporaryObjectsList);
                        }
                    }

                    state.ParseElementStart = state.ParseElementEnd;
                }

                currentPath = animationPath.Name;
            }

            // Totally pop the stack (we might still have stuff to copy back into properties
            PopObjects(ref state, 0);

            return(new CompiledUpdate
            {
                TemporaryObjects = temporaryObjectsList.ToArray(),
                UpdateOperations = state.UpdateOperations.ToArray(),
            });
        }
Пример #24
0
        private void LoadAssemblyReferencesForPackage(ILogger log, PackageLoadParameters loadParameters)
        {
            if (log == null)
            {
                throw new ArgumentNullException("log");
            }
            if (loadParameters == null)
            {
                throw new ArgumentNullException("loadParameters");
            }
            var assemblyContainer = loadParameters.AssemblyContainer ?? AssemblyContainer.Default;

            foreach (var profile in Profiles)
            {
                foreach (var projectReference in profile.ProjectReferences.Where(projectRef => projectRef.Type == ProjectType.Plugin || projectRef.Type == ProjectType.Library))
                {
                    // Check if already loaded
                    // TODO: More advanced cases: unload removed references, etc...
                    if (loadedAssemblies.Any(x => x.ProjectReference == projectReference))
                    {
                        continue;
                    }

                    string assemblyPath        = null;
                    var    fullProjectLocation = UPath.Combine(RootDirectory, projectReference.Location);

                    try
                    {
                        var forwardingLogger = new ForwardingLoggerResult(log);
                        assemblyPath = VSProjectHelper.GetOrCompileProjectAssembly(fullProjectLocation, forwardingLogger, loadParameters.AutoCompileProjects, extraProperties: loadParameters.ExtraCompileProperties, onlyErrors: true);
                        if (String.IsNullOrWhiteSpace(assemblyPath))
                        {
                            log.Error("Unable to locate assembly reference for project [{0}]", fullProjectLocation);
                            continue;
                        }

                        var loadedAssembly = new PackageLoadedAssembly(projectReference, assemblyPath);
                        loadedAssemblies.Add(loadedAssembly);

                        if (!File.Exists(assemblyPath) || forwardingLogger.HasErrors)
                        {
                            log.Error("Unable to build assembly reference [{0}]", assemblyPath);
                            continue;
                        }

                        var assembly = assemblyContainer.LoadAssemblyFromPath(assemblyPath, log);
                        if (assembly == null)
                        {
                            log.Error("Unable to load assembly reference [{0}]", assemblyPath);
                        }

                        loadedAssembly.Assembly = assembly;

                        if (assembly != null)
                        {
                            // Register assembly in the registry
                            AssemblyRegistry.Register(assembly, AssemblyCommonCategories.Assets);
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error("Unexpected error while loading project [{0}] or assembly reference [{1}]", ex, fullProjectLocation, assemblyPath);
                    }
                }
            }
        }
Пример #25
0
 public static void InitializeModule()
 {
     //RegisterPlugin(typeof(SpriteStudioPlugin));
     AssemblyRegistry.Register(typeof(Module).GetTypeInfo().Assembly, AssemblyCommonCategories.Assets);
 }
Пример #26
0
        private static void RegisterAssetAssembly(Assembly assembly)
        {
            if (assembly == null)
            {
                throw new ArgumentNullException(nameof(assembly));
            }

            lock (RegistryLock)
            {
                if (RegisteredAssetAssemblies.Contains(assembly))
                {
                    return;
                }

                RegisteredAssetAssemblies.Add(assembly);

                var assemblyScanTypes = AssemblyRegistry.GetScanTypes(assembly);
                if (assemblyScanTypes != null)
                {
                    List <Type> types;

                    var instantiatedObjects = new Dictionary <Type, object>();

                    // Register serializer factories
                    if (assemblyScanTypes.Types.TryGetValue(typeof(IYamlSerializableFactory), out types))
                    {
                        foreach (var type in types)
                        {
                            // Register serializer factories
                            if (!type.IsAbstract &&
                                type.GetCustomAttribute <YamlSerializerFactoryAttribute>() != null && type.GetConstructor(Type.EmptyTypes) != null)
                            {
                                try
                                {
                                    var instance = Activator.CreateInstance(type);
                                    instantiatedObjects.Add(type, instance);
                                    RegisteredSerializerFactories.Add((IYamlSerializableFactory)instance);
                                }
                                catch (Exception ex)
                                {
                                    Log.Error($"Unable to instantiate serializer factory [{type}]", ex);
                                }
                            }
                        }
                    }

                    // Custom visitors
                    if (assemblyScanTypes.Types.TryGetValue(typeof(IDataCustomVisitor), out types))
                    {
                        foreach (var type in types)
                        {
                            if (!type.IsAbstract && type.GetConstructor(Type.EmptyTypes) != null)
                            {
                                try
                                {
                                    object instance;
                                    if (!instantiatedObjects.TryGetValue(type, out instance))
                                    {
                                        instance = Activator.CreateInstance(type);
                                        instantiatedObjects.Add(type, instance);
                                    }
                                    RegisteredDataVisitNodes.Add((IDataCustomVisitor)instance);
                                }
                                catch (Exception ex)
                                {
                                    Log.Error($"Unable to instantiate custom visitor [{type}]", ex);
                                }
                            }
                        }
                    }

                    // Asset importer
                    if (assemblyScanTypes.Types.TryGetValue(typeof(IAssetImporter), out types))
                    {
                        foreach (var type in types)
                        {
                            if (!type.IsAbstract && type.GetConstructor(Type.EmptyTypes) != null)
                            {
                                try
                                {
                                    object instance;
                                    if (!instantiatedObjects.TryGetValue(type, out instance))
                                    {
                                        instance = Activator.CreateInstance(type);
                                        instantiatedObjects.Add(type, instance);
                                    }
                                    // Register the importer instance
                                    RegisterImporter((IAssetImporter)instance);
                                }
                                catch (Exception ex)
                                {
                                    Log.Error($"Unable to instantiate importer [{type.Name}]", ex);
                                }
                            }
                        }
                    }

                    // Register asset factory
                    if (assemblyScanTypes.Types.TryGetValue(typeof(IAssetFactory <>), out types))
                    {
                        foreach (var type in types)
                        {
                            if (!type.IsAbstract && !type.IsGenericTypeDefinition && type.GetConstructor(Type.EmptyTypes) != null)
                            {
                                object instance;
                                if (!instantiatedObjects.TryGetValue(type, out instance))
                                {
                                    instance = Activator.CreateInstance(type);
                                    instantiatedObjects.Add(type, instance);
                                }
                                RegisteredAssetFactories.Add(type.Name, (IAssetFactory <Asset>)instance);
                            }
                        }
                    }

                    // Package upgraders
                    if (assemblyScanTypes.Types.TryGetValue(typeof(PackageUpgraderAttribute), out types))
                    {
                        foreach (var type in types)
                        {
                            var packageUpgraderAttribute = type.GetCustomAttribute <PackageUpgraderAttribute>();
                            if (packageUpgraderAttribute != null)
                            {
                                try
                                {
                                    var packageUpgrader = (PackageUpgrader)Activator.CreateInstance(type);
                                    packageUpgrader.Attribute = packageUpgraderAttribute;
                                    RegisteredPackageUpgraders[packageUpgraderAttribute.PackageName] = packageUpgrader;
                                }
                                catch (Exception ex)
                                {
                                    Log.Error($"Unable to instantiate package upgrader [{type.Name}]", ex);
                                }
                            }
                        }
                    }

                    // Package analyzers
                    if (assemblyScanTypes.Types.TryGetValue(typeof(PackageSessionAnalysisBase), out types))
                    {
                        foreach (var type in types)
                        {
                            if (type.GetConstructor(Type.EmptyTypes) != null)
                            {
                                RegisteredPackageSessionAnalysisTypes.Add(type);
                            }
                        }
                    }

                    // Asset types (and Package type)
                    var assemblyContainsPackageType = assembly == typeof(Package).Assembly;
                    if (assemblyScanTypes.Types.TryGetValue(typeof(Asset), out types) || assemblyContainsPackageType)
                    {
                        if (assemblyContainsPackageType)
                        {
                            var extraTypes = new[] { typeof(Package) };
                            types = types?.Concat(extraTypes).ToList() ?? extraTypes.ToList();
                        }
                        foreach (var assetType in types)
                        {
                            // Store in a list all asset types loaded
                            if (assetType.IsPublic && !assetType.IsAbstract)
                            {
                                AssetTypes.Add(assetType);
                            }

                            // Asset FileExtensions
                            var assetDescriptionAttribute = assetType.GetCustomAttribute <AssetDescriptionAttribute>();
                            if (assetDescriptionAttribute != null)
                            {
                                if (assetDescriptionAttribute.FileExtensions != null)
                                {
                                    var extensions = FileUtility.GetFileExtensions(assetDescriptionAttribute.FileExtensions);
                                    RegisteredDefaultAssetExtension[assetType] = extensions.FirstOrDefault();
                                    foreach (var extension in extensions)
                                    {
                                        if (!RegisteredAssetFileExtensions.ContainsKey(extension))
                                        {
                                            RegisteredAssetFileExtensions.Add(extension, assetType);
                                        }
                                    }
                                }

                                if (assetDescriptionAttribute.AlwaysMarkAsRoot)
                                {
                                    lock (AlwaysMarkAsRootAssetTypes)
                                    {
                                        AlwaysMarkAsRootAssetTypes.Add(assetType);
                                    }
                                }
                            }

                            // Content type associated to assets
                            var assetContentType = assetType.GetCustomAttribute <AssetContentTypeAttribute>();
                            if (assetContentType != null)
                            {
                                List <Type> assetTypes;
                                if (!ContentToAssetTypes.TryGetValue(assetContentType.ContentType, out assetTypes))
                                {
                                    assetTypes = new List <Type>();
                                    ContentToAssetTypes[assetContentType.ContentType] = assetTypes;
                                }
                                assetTypes.Add(assetType);
                                AssetToContentTypes.Add(assetType, assetContentType.ContentType);
                            }

                            // Asset format version (process name by name)
                            var assetFormatVersions = assetType.GetCustomAttributes <AssetFormatVersionAttribute>();
                            foreach (var assetFormatVersion in assetFormatVersions)
                            {
                                var formatVersion = assetFormatVersion.Version;
                                var minVersion    = assetFormatVersion.MinUpgradableVersion;
                                SortedList <string, PackageVersion> formatVersions;
                                if (!RegisteredFormatVersions.TryGetValue(assetType, out formatVersions))
                                {
                                    RegisteredFormatVersions.Add(assetType, formatVersions = new SortedList <string, PackageVersion>());
                                }
                                formatVersions.Add(assetFormatVersion.Name, formatVersion);

                                // Asset upgraders (only those matching current name)
                                var assetUpgraders = assetType.GetCustomAttributes <AssetUpgraderAttribute>().Where(x => x.Name == assetFormatVersion.Name);
                                AssetUpgraderCollection upgraderCollection = null;
                                foreach (var upgrader in assetUpgraders)
                                {
                                    if (upgraderCollection == null)
                                    {
                                        upgraderCollection = new AssetUpgraderCollection(assetType, formatVersion);
                                    }

                                    upgraderCollection.RegisterUpgrader(upgrader.AssetUpgraderType, upgrader.StartVersion, upgrader.TargetVersion);
                                }
                                if (upgraderCollection != null)
                                {
                                    upgraderCollection.Validate(minVersion);
                                    RegisteredAssetUpgraders.Add(new KeyValuePair <Type, string>(assetType, assetFormatVersion.Name), upgraderCollection);
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #27
0
        public static void Reload(Game game, AssemblyContainer assemblyContainer, List <Assembly> assembliesToUnregister, List <Assembly> assembliesToRegister)
        {
            List <Entity> entities = new List <Entity>();

            if (game != null)
            {
                entities.AddRange(game.SceneSystem.SceneInstance);
            }

            CloneReferenceSerializer.References = new List <object>();

            var loadedAssembliesSet = new HashSet <Assembly>(assembliesToUnregister);
            var reloadedComponents  = new List <ReloadedComponentEntryLive>();

            throw new NotImplementedException("Need to reimplement this to use IUnloadable");
#if FALSE
            foreach (var assembly in assembliesToUnregister)
            {
                // Unregisters assemblies that have been registered in Package.Load => Package.LoadAssemblyReferencesForPackage
                AssemblyRegistry.Unregister(assembly);

                // Unload binary serialization
                DataSerializerFactory.UnregisterSerializationAssembly(assembly);

                // Unload assembly
                assemblyContainer.UnloadAssembly(assembly);
            }

            foreach (var assembly in assembliesToRegister)
            {
                ModuleRuntimeHelpers.RunModuleConstructor(assembly.ManifestModule);

                // Unregisters assemblies that have been registered in Package.Load => Package.LoadAssemblyReferencesForPackage
                AssemblyRegistry.Register(assembly, AssemblyCommonCategories.Assets);

                DataSerializerFactory.RegisterSerializationAssembly(assembly);
            }

            // First pass of deserialization: recreate the scripts
            foreach (ReloadedComponentEntryLive reloadedScript in reloadedComponents)
            {
                // Try to create object
                var objectStart = reloadedScript.YamlEvents.OfType <MappingStart>().FirstOrDefault();
                if (objectStart != null)
                {
                    // Get type info
                    var  objectStartTag = objectStart.Tag;
                    bool alias;
                    var  componentType = AssetYamlSerializer.Default.GetSerializerSettings().TagTypeRegistry.TypeFromTag(objectStartTag, out alias);
                    if (componentType != null)
                    {
                        reloadedScript.NewComponent = (EntityComponent)Activator.CreateInstance(componentType);
                    }
                }
            }

            // Second pass: update script references in live objects
            // As a result, any script references processed by Yaml serializer will point to updated objects (script reference cycle will work!)
            for (int index = 0; index < CloneReferenceSerializer.References.Count; index++)
            {
                var component = CloneReferenceSerializer.References[index] as EntityComponent;
                if (component != null)
                {
                    var reloadedComponent = reloadedComponents.FirstOrDefault(x => x.OriginalComponent == component);
                    if (reloadedComponent != null)
                    {
                        CloneReferenceSerializer.References[index] = reloadedComponent.NewComponent;
                    }
                }
            }

            // Third pass: deserialize
            reloadedComponents.ForEach(x => ReplaceComponent(game, x));

            CloneReferenceSerializer.References = null;
#endif
        }
 public FieldReference GetField(string name)
 {
     return(AssemblyRegistry.GetField(Parser.Assembly, TypeEmitter, name));
 }
Пример #29
0
 public static void Initialize()
 {
     AssemblyRegistry.Register(typeof(Module).Assembly, AssemblyCommonCategories.Assets);
     // Initialize translation
     TranslationManager.Instance.RegisterProvider(new GettextTranslationProvider());
 }
 public IEnumerable <MethodReference> GetMethods(string name)
 {
     return(AssemblyRegistry.GetMethods(Parser.Assembly, TypeEmitter, name));
 }
Пример #31
0
 public static void Initialize()
 {
     // Make sure that this assembly is registered
     AssemblyRegistry.Register(typeof(Module).Assembly, AssemblyCommonCategories.Assets);
 }
Пример #32
0
 public static void Initialize()
 {
     // Currently, we are adding this assembly as part of the "assets" in order for the thumbnail types to be accessible through the AssemblyRegistry
     AssemblyRegistry.Register(typeof(Module).Assembly, AssemblyCommonCategories.Assets);
 }
Пример #33
0
 public EventBusAutoRegistrar(AssemblyRegistry assemblyRegistry)
 {
     _assemblyRegistry = assemblyRegistry;
 }
Пример #34
0
        private void SetUpScenarioExecutorForCurrentProject(TaskExecutionNode node)
        {
            var projectTask = node.RemoteTask as RunProjectTask;

            var assemblyRegistry = new AssemblyRegistry(projectTask.Assemblies.Union(new[] {typeof(Scenario).Assembly.Location}));

            _executor = new RemoteScenarioExecutor(Server, assemblyRegistry);
        }
 public void Append(IEnumerable <TypeReference> paramz)
 {
     Type = AssemblyRegistry.GetFunctorType(parser.Assembly, Type, paramz.ToList());
 }
Пример #36
0
 public StepProvider(AssemblyRegistry assemblyRegistry, ContextTypeFactory typeFactory)
 {
     _assemblyRegistry = assemblyRegistry;
     _typeFactory      = typeFactory;
 }
        public void TestIsAssignableTo()
        {
            var types = new Dictionary <string, TypeReference>();
            Action <string, string> addType = (tag, typeName) => types[tag] = AssemblyRegistry.FindType(assembly, typeName);

            addType("int8", "System.SByte");
            addType("int16", "System.Int16");
            addType("int32", "System.Int32");
            addType("int64", "System.Int64");;
            addType("intptr", "System.IntPtr");
            addType("uint8", "System.Byte");
            addType("uint16", "System.UInt16");
            addType("char", "System.Char");
            addType("uint32", "System.UInt32");
            addType("uint64", "System.UInt64");
            addType("uintptr", "System.UIntPtr");
            addType("boolean", "System.Boolean");
            addType("str", "System.String");
            addType("streamwriter", "System.IO.StreamWriter");
            addType("textwriter", "System.IO.TextWriter");
            addType("textreader", "System.IO.TextReader");
            addType("array", "System.Array");
            addType("icloneable", "System.ICloneable");

            foreach (var left in types)
            {
                var exceptions = new List <string>();

                #region Exceptions

                switch (left.Key)
                {
                case "int8":
                    exceptions.Add("int8");
                    break;

                case "int16":
                    exceptions.Add("int8");
                    exceptions.Add("uint8");
                    exceptions.Add("int16");
                    break;

                case "int32":
                    exceptions.Add("char");
                    exceptions.Add("int8");
                    exceptions.Add("uint8");
                    exceptions.Add("int16");
                    exceptions.Add("uint16");
                    exceptions.Add("int32");
                    break;

                case "int64":
                    exceptions.Add("char");
                    exceptions.Add("int8");
                    exceptions.Add("uint8");
                    exceptions.Add("int16");
                    exceptions.Add("uint16");
                    exceptions.Add("int32");
                    exceptions.Add("uint32");
                    exceptions.Add("int64");
                    break;

                case "intptr":
                    exceptions.Add("intptr");
                    break;

                case "uint8":
                    exceptions.Add("uint8");
                    break;

                case "uint16":
                    exceptions.Add("uint8");
                    exceptions.Add("uint16");
                    exceptions.Add("char");
                    break;

                case "uint32":
                    exceptions.Add("uint8");
                    exceptions.Add("uint16");
                    exceptions.Add("uint32");
                    exceptions.Add("char");
                    break;

                case "uint64":
                    exceptions.Add("uint8");
                    exceptions.Add("uint16");
                    exceptions.Add("uint32");
                    exceptions.Add("uint64");
                    exceptions.Add("char");
                    break;

                case "uintptr":
                    exceptions.Add("uintptr");
                    break;

                case "char":
                    exceptions.Add("uint8");
                    exceptions.Add("uint16");
                    exceptions.Add("char");
                    break;

                case "boolean":
                    exceptions.Add("boolean");
                    break;

                case "str":
                    exceptions.Add("str");
                    break;

                case "streamwriter":
                    exceptions.Add("streamwriter");
                    break;

                case "textwriter":
                    exceptions.Add("textwriter");
                    exceptions.Add("streamwriter");
                    break;

                case "textreader":
                    exceptions.Add("textreader");
                    break;

                case "array":
                    exceptions.Add("array");
                    break;

                case "icloneable":
                    exceptions.Add("str");
                    exceptions.Add("icloneable");
                    exceptions.Add("array");
                    break;

                default:
                    throw new Exception("Not all types got tested!");
                }

                #endregion

                foreach (var right in types)
                {
                    var expected = exceptions.Any(exception => exception == right.Key);
                    var actual   = right.Value.IsAssignableTo(left.Value);

                    Assert.IsTrue(expected == actual,
                                  string.Format("Expected {0} {2}to be assignable to {1}.", right.Value.FullName, left.Value.FullName, expected ? "" : "not "));
                }
            }
        }
Пример #38
0
 public void Initialize()
 {
     AssemblyRegistry.Register(typeof(TestSerializing).Assembly, AssemblyCommonCategories.Assets);
 }
Пример #39
0
 public StandardScenarioInterpreter(AssemblyRegistry assemblyRegistry)
     : base(new InterpreterForTypeFactory(assemblyRegistry), new MostRecentlyUsedContext(), new DefaultLanguageService())
 {
 }
        public void TestCanEmit_FunctorPropertyAssignmentToDelegate()
        {
            const int    kArg1 = 485613;
            const string kArg2 = "FASD4FSAD14asdf";

            var intType    = assemblyEmitter.TypeSystem.Int32;
            var stringType = assemblyEmitter.TypeSystem.String;

            var voidType  = assemblyEmitter.TypeSystem.Void;
            var arguments = new TypeReference[]
            {
                intType,
                stringType
            };

            #region Functor Property Setup

            var functorType = AssemblyRegistry.GetFunctorType(assemblyEmitter, voidType, arguments);

            var functorField = new FieldDefinition("myFunction_BackingField", FieldAttributes.Public | FieldAttributes.Static, functorType);
            typeEmitter.AddField(functorField);

            #region Setter

            var functorSetter         = new MethodEmitter(typeEmitter, "set_MyFunction", voidType, MethodAttributes.Public | MethodAttributes.Static);
            var functorSetterArgument = functorSetter.AddArgument(functorType, "value");

            functorSetter.ParseTree(new CodeBlockNode()
            {
                Nodes = new List <IParserNode>()
                {
                    new AssignmentOperatorNode()
                    {
                        LeftOperand  = new FieldNode(functorField),
                        RightOperand = new ParameterNode(functorSetterArgument)
                    }
                }
            });

            #endregion

            #region Getter

            var functorGetter = new MethodEmitter(typeEmitter, "get_MyFunction", functorType, MethodAttributes.Public | MethodAttributes.Static);
            functorGetter.ParseTree(new CodeBlockNode()
            {
                Nodes = new List <IParserNode>()
                {
                    new ReturnNode()
                    {
                        Expression = new FieldNode(functorField)
                    }
                }
            });

            #endregion

            var functorProperty = new PropertyDefinition("MyFunction", PropertyAttributes.None, functorType);
            functorProperty.SetMethod = functorSetter.Get().Resolve();
            functorProperty.GetMethod = functorGetter.Get().Resolve();
            typeEmitter.AddProperty(functorProperty);

            #endregion

            #region Delegate Property setup

            var declaringType = (TypeDefinition)typeEmitter.Get(assemblyEmitter);
            var delegateType  = DelegateEmitter.Create(assemblyEmitter, declaringType, voidType, arguments);
            declaringType.NestedTypes.Add(delegateType);

            var delegateField = new FieldDefinition("myDelegate_BackingField", FieldAttributes.Private | FieldAttributes.Static, delegateType);
            typeEmitter.AddField(delegateField);

            #region Setter

            var delegateSetter         = new MethodEmitter(typeEmitter, "set_MyDelegate", voidType, MethodAttributes.Public | MethodAttributes.Static);
            var delegateSetterArgument = delegateSetter.AddArgument(delegateType, "value");

            delegateSetter.ParseTree(new CodeBlockNode()
            {
                Nodes = new List <IParserNode>()
                {
                    new AssignmentOperatorNode()
                    {
                        LeftOperand  = new FieldNode(delegateField),
                        RightOperand = new ParameterNode(delegateSetterArgument)
                    }
                }
            });

            #endregion

            #region Getter

            var delegateGetter = new MethodEmitter(typeEmitter, "get_MyDelegate", delegateType, MethodAttributes.Public | MethodAttributes.Static);
            delegateGetter.ParseTree(new CodeBlockNode()
            {
                Nodes = new List <IParserNode>()
                {
                    new ReturnNode()
                    {
                        Expression = new FieldNode(delegateField)
                    }
                }
            });

            #endregion

            var delegateProperty = new PropertyDefinition("MyDelegate", PropertyAttributes.None, delegateType);
            delegateProperty.SetMethod = delegateSetter.Get().Resolve();
            delegateProperty.GetMethod = delegateGetter.Get().Resolve();
            typeEmitter.AddProperty(delegateProperty);

            #endregion

            BodyCodeBlock = new CodeBlockNode()
            {
                Nodes = new List <IParserNode>()
                {
                    new AssignmentOperatorNode()
                    {
                        LeftOperand  = new PropertyNode(assemblyEmitter, functorProperty),
                        RightOperand = new FunctionNode()
                        {
                            ExpressionReturnType = functorType,
                            Method = EmitMethodToOutputArgs(null, arguments)
                        }
                    },

                    new AssignmentOperatorNode()
                    {
                        LeftOperand  = new PropertyNode(assemblyEmitter, delegateProperty),
                        RightOperand = new PropertyNode(assemblyEmitter, functorProperty)
                    },

                    new MethodCallNode()
                    {
                        ExpressionReturnType = voidType,
                        Function             = new PropertyNode(assemblyEmitter, delegateProperty),
                        Args = new IExpressionNode[]
                        {
                            new LiteralNode(intType, kArg1),
                            new LiteralNode(stringType, kArg2)
                        }
                    }
                }
            };

            ExpectedOutput = string.Format("{0}\r\n{1}", kArg1, kArg2);
            AssertSuccessByExecution();
        }
Пример #41
0
 public StepProvider(AssemblyRegistry assemblyRegistry, ContextTypeFactory typeFactory)
 {
     _assemblyRegistry = assemblyRegistry;
     _typeFactory = typeFactory;
 }
 public InterpreterForTypeFactory(AssemblyRegistry assemblyRegistry)
 {
     _extensionMethodHandler = new ExtensionMethodHandler(assemblyRegistry);
     _contextTypeFactory = new ContextTypeFactory(_extensionMethodHandler);
 }