Ejemplo n.º 1
0
        private void InitConstants(DualDictionary <string, object> _constants)
        {
            // Thease constants are here, because they are environment dependent
            // When the code is compiled and assembly is run on another platforms they could be different

            _constants.Add("PHALANGER", PhalangerVersion.Current, false);
            _constants.Add("PHP_VERSION", PhpVersion.Current, false);
            _constants.Add("PHP_MAJOR_VERSION", PhpVersion.Major, false);
            _constants.Add("PHP_MINOR_VERSION", PhpVersion.Minor, false);
            _constants.Add("PHP_RELEASE_VERSION", PhpVersion.Release, false);
            _constants.Add("PHP_VERSION_ID", PhpVersion.Major * 10000 + PhpVersion.Minor * 100 + PhpVersion.Release, false);
            _constants.Add("PHP_EXTRA_VERSION", PhpVersion.Extra, false);
            _constants.Add("PHP_OS", Environment.OSVersion.Platform == PlatformID.Win32NT ? "WINNT" : "WIN32", false); // TODO: GENERICS (Unix)
            _constants.Add("PHP_SAPI", (System.Web.HttpContext.Current == null) ? "cli" : "isapi", false);
            _constants.Add("DIRECTORY_SEPARATOR", FullPath.DirectorySeparatorString, false);
            _constants.Add("PATH_SEPARATOR", Path.PathSeparator.ToString(), false);

            //TODO: should be specified elsewhere (app context??)
            _constants.Add("PHP_EOL", System.Environment.NewLine, false);

            //TODO: this is a bit pesimistic, as this value is a bit higher on Vista and on other filesystems and OSes
            //      sadly .NET does not specify value of MAXPATH constant
            _constants.Add("PHP_MAXPATHLEN", 255, false);

            if (HttpContext.Current == null)
            {
                _constants.Add("STDIN", InputOutputStreamWrapper.In, false);
                _constants.Add("STDOUT", InputOutputStreamWrapper.Out, false);
                _constants.Add("STDERR", InputOutputStreamWrapper.Error, false);
            }
        }
Ejemplo n.º 2
0
        internal static void ReflectConstants(Assembly /*!*/ realAssembly, DModule /*!*/ declaringModule,
                                              DualDictionary <string, DConstantDesc> /*!*/ constants)
        {
            Debug.Assert(realAssembly != null && constants != null);

            foreach (FieldInfo real_field in ReflectionUtils.GetGlobalFields(realAssembly, BindingFlags.Public | BindingFlags.Static))
            {
                if (real_field.IsLiteral && !real_field.IsSpecialName)
                {
                    string full_name = ClrNotationUtils.FromClrNotation(real_field.Name, true).ToString();

                    DConstantDesc existing;
                    if (constants.TryGetValue(full_name, out existing))
                    {
                        // can be already loaded from different module (CRL or CLib):
                        existing.MemberAttributes |= PhpMemberAttributes.Ambiguous;
                    }
                    else
                    {
                        object        value      = real_field.GetValue(null);
                        DConstantDesc const_desc = new DConstantDesc(declaringModule, PhpMemberAttributes.Public | PhpMemberAttributes.Static, value);
                        constants.Add(full_name, const_desc, false);
                    }
                }
            }
        }
Ejemplo n.º 3
0
 public override void Reflect(bool full,
                              Dictionary <string, DTypeDesc> /*!*/ types,
                              Dictionary <string, DRoutineDesc> /*!*/ functions,
                              DualDictionary <string, DConstantDesc> /*!*/ constants)
 {
     Debug.Fail(null);
 }
        public static JMNedictParser Create(Stream stream)
        {
            var friendlyNames = new DualDictionary <string, string>();

            var xmlReader = new XmlTextReader(stream);

            xmlReader.EntityHandling = EntityHandling.ExpandCharEntities;
            xmlReader.DtdProcessing  = DtdProcessing.Parse;
            xmlReader.XmlResolver    = null;
            while (xmlReader.Read())
            {
                if (xmlReader.NodeType == XmlNodeType.DocumentType)
                {
                    friendlyNames = new DualDictionary <string, string>(XmlEntities
                                                                        .ParseJMDictEntities(xmlReader.Value)
                                                                        .DistinctBy(kvp => kvp.Key));
                }

                if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == "JMnedict")
                {
                    break;
                }
            }
            return(new JMNedictParser(xmlReader, friendlyNames, stream));
        }
Ejemplo n.º 5
0
 public override void Reflect(bool full,
                              Dictionary <string, DTypeDesc> /*!*/ types,
                              Dictionary <string, DRoutineDesc> /*!*/ functions,
                              DualDictionary <string, DConstantDesc> /*!*/ constants)
 {
     ReflectTypes(assembly.RealAssembly, types);
     ReflectFunctions(assembly.RealAssembly, globalType.TypeDesc, functions);
     ReflectConstants(assembly.RealAssembly, this, constants);
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Reflect global constants in &lt;script&gt; class.
        /// </summary>
        /// <param name="scriptType">The type representing single script.</param>
        /// <param name="constants">Dictionary for constants.</param>
        private void ReflectScriptTypeConstants(Type scriptType, DualDictionary <string, DConstantDesc> /*!*/ constants)
        {
            foreach (var field in scriptType.GetFields(BindingFlags.Public | BindingFlags.Static))
            {
                // TODO: namespaces!!

                GlobalConstant constant = new GlobalConstant(this, QualifiedName.FromClrNotation(field.Name, true), field);
                constant.SetValue(Convert.ClrLiteralToPhpLiteral(field.GetValue(null)));
                constants.Add(field.Name, constant.ConstantDesc, false);
            }
        }
Ejemplo n.º 7
0
        public override void Reflect(bool full,
                                     Dictionary <string, DTypeDesc> /*!*/ types,
                                     Dictionary <string, DRoutineDesc> /*!*/ functions,
                                     DualDictionary <string, DConstantDesc> /*!*/ constants)
        {
            // TODO: functions' lazy reflection doesn't work
            full = true;

            if (dynamicWrapper == null)
            {
                this.LoadDynamicWrapper();
            }

            Type[] real_types;

            if (dynamicWrapper == null)
            {
                Debug.Assert(!Configuration.IsLoaded && !Configuration.IsBeingLoaded, "No dynamic wrappers are allowed only for configuration-less reflection!");
                real_types = Assembly.RealAssembly.GetTypes();

                // functions
                // only argfulls
            }
            else
            {
                real_types = dynamicWrapper.GetTypes();

                // functions (scan arglesses in the dynamic wrapper - full reflect needs this info as well):
                foreach (Type type in real_types)
                {
                    if (type.Namespace == Namespaces.LibraryStubs)
                    {
                        ReflectArglesses(functions, type);
                    }
                }

                // types are in the real assembly
                if (dynamicWrapper != Assembly.RealAssembly)
                {
                    real_types = Assembly.RealAssembly.GetTypes();
                }
            }

            foreach (Type type in real_types)
            {
                ReflectArgfulls(types, functions, constants, type, full);
            }

            //// reflect <Module>
            //if (Assembly.RealModule != null)
            //{
            //    ReflectGlobals(functions, constants, Assembly.RealModule);
            //}
        }
        DualDictionary <string, string> CreateDictionary(Action <Dictionary <string, string> > ops)
        {
            var src = new Dictionary <string, string>
            {
                { "hello", "world" },
                { "asdf", "lol" }
            };

            ops(src);
            var d = new DualDictionary <string, string>(src);

            return(d);
        }
Ejemplo n.º 9
0
        private void InitConstants(DualDictionary <string, object> _constants)
        {
            // SILVERLIGHT: ??

            //_constants.Add("PHALANGER", Assembly.GetExecutingAssembly().GetName().Version.ToString(), false);
            //_constants.Add("PHP_VERSION", PhpVersion.Current, false);
            //_constants.Add("PHP_OS", Environment.OSVersion.Platform == PlatformID.Win32NT ? "WINNT" : "WIN32", false); // TODO: GENERICS (Unix)
            //_constants.Add("DIRECTORY_SEPARATOR", Path.DirectorySeparatorChar.ToString(), false);
            //_constants.Add("PATH_SEPARATOR", Path.PathSeparator.ToString(), false);

            //_constants.Add("STDIN", InputOutputStreamWrapper.In, false);
            //_constants.Add("STDOUT", InputOutputStreamWrapper.Out, false);
            //_constants.Add("STDERR", InputOutputStreamWrapper.Error, false);
        }
Ejemplo n.º 10
0
        internal MangaContext(MetadataJson metadata, ProjectDirectoryListingProvider listing)
        {
            this.listing  = listing;
            this.metadata = metadata;

            using var file       = listing.FileOpen(listing.GetCharactersPath());
            using var jsonReader = new JsonTextReader(file);
            var serializer = new JsonSerializer();

            this.charactersJson = serializer.Deserialize <CharactersJson>(jsonReader);
            IdNameMapping       = new DualDictionary <long, string>(charactersJson.Characters
                                                                    .ToDictionary(c => c.Id, c => c.Name));
            this.characterTypeConverter = new CharacterTypeConverter(IdNameMapping);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Assuming the given <c>type</c> is Library type, reflect argfull function stubs, PHP types and constants from given <c>type</c>.
        /// </summary>
        /// <param name="functions">Dictionary of reflected functions.</param>
        /// <param name="constants">Dictionary of reflected constants.</param>
        /// <param name="type">The type to reflect functions from.</param>
        /// <param name="full">Whether to perform full function reflect.</param>
        private void ReflectLibraryType(
            Dictionary <string, DRoutineDesc> /*!*/ functions,
            DualDictionary <string, DConstantDesc> /*!*/ constants,
            Type /*!*/ type, bool full)
        {
            // functions (argfulls):
            if (full && !type.IsEnum)
            {
                FullReflectFunctions(type.GetMethods(BindingFlags.Public | BindingFlags.Static), functions, true);
            }

            // constants:
            ReflectConstants(type.GetFields(BindingFlags.Public | BindingFlags.Static), constants);
        }
Ejemplo n.º 12
0
		private void InitConstants(DualDictionary<string, object> _constants)
		{
			// SILVERLIGHT: ??
			
			//_constants.Add("PHALANGER", Assembly.GetExecutingAssembly().GetName().Version.ToString(), false);
			//_constants.Add("PHP_VERSION", PhpVersion.Current, false);
			//_constants.Add("PHP_OS", Environment.OSVersion.Platform == PlatformID.Win32NT ? "WINNT" : "WIN32", false); // TODO: GENERICS (Unix)
			//_constants.Add("DIRECTORY_SEPARATOR", Path.DirectorySeparatorChar.ToString(), false);
			//_constants.Add("PATH_SEPARATOR", Path.PathSeparator.ToString(), false);

			//_constants.Add("STDIN", InputOutputStreamWrapper.In, false);
			//_constants.Add("STDOUT", InputOutputStreamWrapper.Out, false);
			//_constants.Add("STDERR", InputOutputStreamWrapper.Error, false);
		}
Ejemplo n.º 13
0
		public override void Reflect(bool full,
			Dictionary<string, DTypeDesc>/*!*/ types,
			Dictionary<string, DRoutineDesc>/*!*/ functions,
			DualDictionary<string, DConstantDesc>/*!*/ constants)
		{
			// TODO: functions' lazy reflection doesn't work
			full = true;

			if (dynamicWrapper == null)
				this.LoadDynamicWrapper();

            Type[] real_types;

            if (dynamicWrapper == null)
            {
                Debug.Assert(!Configuration.IsLoaded && !Configuration.IsBeingLoaded, "No dynamic wrappers are allowed only for configuration-less reflection!");
                real_types = Assembly.RealAssembly.GetTypes();

                // functions
                // only argfulls
            }
            else
            {
                real_types = dynamicWrapper.GetTypes();

                // functions (scan arglesses in the dynamic wrapper - full reflect needs this info as well):
                foreach (Type type in real_types)
                {
                    if (type.Namespace == Namespaces.LibraryStubs)
                        ReflectArglesses(functions, type);
                }

                // types are in the real assembly
                if (dynamicWrapper != Assembly.RealAssembly)
                    real_types = Assembly.RealAssembly.GetTypes();
            }
            
            foreach (Type type in real_types)
			{
                ReflectArgfulls(types, functions, constants, type, full);
			}

            //// reflect <Module>
            //if (Assembly.RealModule != null)
            //{
            //    ReflectGlobals(functions, constants, Assembly.RealModule);
            //}
		}
Ejemplo n.º 14
0
        public ApplicationContext(bool lazyFullReflection, bool reflectionOnly, bool createTransientBuilder)
        {
            this.lazyFullReflection = lazyFullReflection;

            this.assemblyLoader           = new AssemblyLoader(this, reflectionOnly);
            this.transientAssemblyBuilder = createTransientBuilder ? new TransientAssemblyBuilder(this) : null;

            this.types     = new Dictionary <string, DTypeDesc>(StringComparer.OrdinalIgnoreCase);
            this.functions = new Dictionary <string, DRoutineDesc>(StringComparer.OrdinalIgnoreCase);
            this.constants = new DualDictionary <string, DConstantDesc>(null, StringComparer.OrdinalIgnoreCase);

#if !SILVERLIGHT
            this.scriptLibraryDatabase = new ScriptLibraryDatabase(this);
#endif

            PopulateTables();
        }
        public static JMDictParser Create(Stream stream)
        {
            DateTime?versionDate = null;
            var      undoEntityExpansionDictionary = new DualDictionary <string, string>();

            var xmlReader = new XmlTextReader(stream);

            xmlReader.EntityHandling = EntityHandling.ExpandCharEntities;
            xmlReader.DtdProcessing  = DtdProcessing.Parse;
            xmlReader.XmlResolver    = null;
            while (xmlReader.Read())
            {
                if (xmlReader.NodeType == XmlNodeType.DocumentType)
                {
                    undoEntityExpansionDictionary = new DualDictionary <string, string>(
                        EnumerableExt.DistinctBy(
                            XmlEntities.ParseJMDictEntities(xmlReader.Value),
                            kvp => kvp.Key));
                }

                if (xmlReader.NodeType == XmlNodeType.Comment)
                {
                    var commentText = xmlReader.Value.Trim();
                    if (commentText.StartsWith("JMdict created:", StringComparison.Ordinal))
                    {
                        var generationDate = commentText.Split(':').ElementAtOrDefault(1)?.Trim();
                        if (DateTime.TryParseExact(generationDate, "yyyy-MM-dd", CultureInfo.InvariantCulture,
                                                   DateTimeStyles.AssumeUniversal, out var date))
                        {
                            versionDate = date;
                        }
                        else
                        {
                            versionDate = null;
                        }
                    }
                }

                if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == "JMdict")
                {
                    break;
                }
            }

            return(new JMDictParser(versionDate, undoEntityExpansionDictionary, xmlReader));
        }
Ejemplo n.º 16
0
		public override void Reflect(bool full,
			Dictionary<string, DTypeDesc>/*!*/ types,
			Dictionary<string, DRoutineDesc>/*!*/ functions,
			DualDictionary<string, DConstantDesc>/*!*/ constants)
		{
			if (AutoPopulate()) return;

			// types:
			ClrModule.ReflectTypes(this.Assembly.RealAssembly, types);

			// TODO:

			// functions and global constants:
			foreach (Module module in this.Assembly.RealAssembly.GetModules())
			{
				//ClrTypeDesc.ReflectMethods(module.GetMethods(), globalType.TypeDesc,
				//	delegate(Name name, ClrMethodDesc/*!*/ function) { functions.Add(name.Value, function); });
			}
		}
Ejemplo n.º 17
0
        /// <summary>
        /// Reflect types, functions and constants in compiled CU
        /// </summary>
        /// <param name="full">Not used.</param>
        /// <param name="functions">Will contain reflected functions.</param>
        /// <param name="types">Will contain reflected classes.</param>
        /// <param name="constants">Not used.</param>
        public override void Reflect(bool full,
                                     Dictionary <string, DTypeDesc> /*!*/ types,
                                     Dictionary <string, DRoutineDesc> /*!*/ functions,
                                     DualDictionary <string, DConstantDesc> /*!*/ constants)
        {
            // pairs of <assembly, list of namespaces>
            // each namespace represents relative path to the script containing functions/PHP classes
            var reachedScripts = new Dictionary <Type, bool>();

            CollectIncludees(ScriptType, reachedScripts);

            // reflect functions/classes from reachedScripts
            foreach (var scriptType in reachedScripts.Keys)
            {
                Debug.Assert(scriptType.Name == ScriptModule.ScriptTypeName);

                ReflectScriptTypeFunctions(scriptType, functions);
                ReflectScriptTypeClasses(scriptType, types);
                ReflectScriptTypeConstants(scriptType, constants);
            }
        }
Ejemplo n.º 18
0
        public KanaProperties(string katakanaPath, string hiraganaPath, string hiraganaKatakanaPath, string complexPath, Encoding encoding)
        {
            ReadKanaFile(katakanaPath);
            ReadKanaFile(hiraganaPath);

            foreach (var lineColumn in File.ReadLines(complexPath, encoding))
            {
                var components = lineColumn.Split(' ');
                if (components.Length > 2)
                {
                    romajiMapping.Add(components[1], components[2]);
                }
                var list = mapping.GetOrAdd(components[0], () => new List <string>());
                list.Add(components[1]);
            }

            var kana = new Dictionary <int, int>();

            foreach (var lineColumn in File.ReadLines(hiraganaKatakanaPath, encoding))
            {
                var components = lineColumn.Split(' ');
                if (components.Length > 1)
                {
                    kana.Add(components[0].AsCodePoints().Single(), components[1].AsCodePoints().Single());
                }
            }
            hiraganaKatakana = new DualDictionary <int, int>(kana);

            void ReadKanaFile(string kanaPath)
            {
                foreach (var lineColumn in File.ReadLines(kanaPath, encoding))
                {
                    var components = lineColumn.Split(' ');
                    if (components.Length > 1)
                    {
                        romajiMapping.Add(components[0], components[1]);
                    }
                }
            }
        }
Ejemplo n.º 19
0
        public override void Reflect(bool full,
                                     Dictionary <string, DTypeDesc> /*!*/ types,
                                     Dictionary <string, DRoutineDesc> /*!*/ functions,
                                     DualDictionary <string, DConstantDesc> /*!*/ constants)
        {
            // PluginAssembly does not contain any declarations

            // Let the plugin to modify ApplicationContext
            var attrs = PluginAssemblyAttribute.Reflect(PluginAssembly.RealAssembly);

            if (attrs != null)
            {
                foreach (var plug in attrs)
                {
                    var method = plug.LoaderType.GetMethod(PluginAssembly.LoaderMethod, BindingFlags.Public | BindingFlags.Static, null, PluginAssembly.LoaderMethodParameters, null);
                    if (method != null)
                    {
                        method.Invoke(null, new object[] { PluginAssembly.ApplicationContext });
                    }
                }
            }
        }
Ejemplo n.º 20
0
        public override void Reflect(bool full,
                                     Dictionary <string, DTypeDesc> /*!*/ types,
                                     Dictionary <string, DRoutineDesc> /*!*/ functions,
                                     DualDictionary <string, DConstantDesc> /*!*/ constants)
        {
            if (AutoPopulate())
            {
                return;
            }

            // types:
            ClrModule.ReflectTypes(this.Assembly.RealAssembly, types);

            // TODO:

            // functions and global constants:
            foreach (Module module in this.Assembly.RealAssembly.GetModules())
            {
                //ClrTypeDesc.ReflectMethods(module.GetMethods(), globalType.TypeDesc,
                //	delegate(Name name, ClrMethodDesc/*!*/ function) { functions.Add(name.Value, function); });
            }
        }
Ejemplo n.º 21
0
        private void ReflectConstants(FieldInfo[] /*!!*/ realFields, DualDictionary <string, DConstantDesc> /*!*/ constants)
        {
            foreach (FieldInfo field in realFields)
            {
                // reflect only fields with [ImplementsConstant] attribute:
                ImplementsConstantAttribute impl_const = ImplementsConstantAttribute.Reflect(field);
                if (impl_const != null)
                {
                    object value;

                    try
                    {
                        // expect the constant have literal value, otherwise crash
                        value = Convert.ClrLiteralToPhpLiteral(field.GetValue(null));
                    }
                    catch (Exception)
                    {
                        throw new InvalidCastException();
                    }

                    GlobalConstant constant = new GlobalConstant(this, new QualifiedName(new Name(impl_const.Name)), field);
                    constant.SetValue(value);

                    constants[impl_const.Name, impl_const.CaseInsensitive] = constant.ConstantDesc;
                }


                //// accepts literals of PHP/CLR primitive types only:
                //if (field.IsLiteral && (PhpVariable.IsLiteralPrimitiveType(field.FieldType) || field.FieldType.IsEnum))
                //{
                //    if (impl_const != null)
                //    {
                //        // ...
                //    }
                //}
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Reflect argfull function, PHP types and constants from given <c>type</c>.
        /// </summary>
        /// <param name="types">Dictionary of types where newly discovered PHP types will be placed. (Types having [ImplementsType] attribute.)</param>
        /// <param name="functions">Dictionary of reflected functions.</param>
        /// <param name="constants">Dictionary of reflected constants.</param>
        /// <param name="type">The type to reflect functions from.</param>
        /// <param name="full">Whether to perform full function reflect.</param>
        private void ReflectArgfulls(
            Dictionary <string, DTypeDesc> /*!*/ types,
            Dictionary <string, DRoutineDesc> /*!*/ functions,
            DualDictionary <string, DConstantDesc> /*!*/ constants,
            Type /*!*/ type, bool full)
        {
            // skip generic types:
            if (type.IsGenericTypeDefinition)
            {
                return;
            }

            if (PhpType.IsPhpRealType(type))
            {
                var dtype = PhpTypeDesc.Create(type);
                types[dtype.MakeSimpleName()] = dtype;
            }

            // reflect even if it is PhpType to find global functions [ImplementsFunction] and constants [ImplementsConstant]
            if (IsLibraryType(type))
            {
                ReflectLibraryType(functions, constants, type, full);
            }
        }
Ejemplo n.º 23
0
 public override void Reflect(bool full, Dictionary<string, DTypeDesc> types, Dictionary<string, DRoutineDesc> functions, DualDictionary<string, DConstantDesc> constants)
 {
     Debug.Fail();
     throw null;
 }
Ejemplo n.º 24
0
 public Account(bool addToWorld)
     : base(DatabaseID.Zero, addToWorld)
 {
     Chars        = new DualDictionary <WorldID, Character>();
     AccountState = EAccountState.None;
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Reflect global constants in &lt;script&gt; class.
        /// </summary>
        /// <param name="scriptType">The type representing single script.</param>
        /// <param name="constants">Dictionary for constants.</param>
        private void ReflectScriptTypeConstants(Type scriptType, DualDictionary<string, DConstantDesc>/*!*/ constants)
        {
            foreach (var field in scriptType.GetFields(BindingFlags.Public | BindingFlags.Static))
            {
                // TODO: namespaces!!

                GlobalConstant constant = new GlobalConstant(this, ClrNotationUtils.FromClrNotation(field.Name, true), field);
                constant.SetValue(Convert.ClrLiteralToPhpLiteral(field.GetValue(null)));
                constants.Add(field.Name, constant.ConstantDesc, false);
            }            
        }
Ejemplo n.º 26
0
        public KanaProperties2(string kanaPropertiesPath, Encoding encoding)
        {
            var kanaToRomaji         = new Dictionary <string, string>();
            var regularHandakutenMap = new Dictionary <int, int>();
            var regularDakutenMap    = new Dictionary <int, int>();
            var smallLargeMap        = new Dictionary <int, int>();
            var katakanaHiraganaMap  = new Dictionary <int, int>();
            var hiraganaKatakanaMap  = new Dictionary <int, int>();

            foreach (var line in File.ReadLines(kanaPropertiesPath, encoding))
            {
                var components = line.Split(' ');
                var hiragana   = components[0];
                var katakana   = components[1];
                var romaji     = components[2];
                var kind       = components[3];
                switch (kind)
                {
                case "regular":
                case "archaic":
                    AddHiraganaKatakanaMapping(katakanaHiraganaMap, hiraganaKatakanaMap, katakana, hiragana);
                    AddToRomajiDic(kanaToRomaji, hiragana, katakana, romaji);
                    break;

                case "combo":
                    AddToRomajiDic(kanaToRomaji, hiragana, katakana, romaji);
                    break;

                case "small":
                    smallLargeMap.Add(AssumeSingleCodepoint(hiragana), AssumeSingleCodepoint(components[4]));
                    smallLargeMap.Add(AssumeSingleCodepoint(katakana), hiraganaKatakanaMap[AssumeSingleCodepoint(components[4])]);
                    break;

                case "dakuten":
                    regularDakutenMap.Add(AssumeSingleCodepoint(components[4]), AssumeSingleCodepoint(hiragana));
                    regularDakutenMap.Add(hiraganaKatakanaMap[AssumeSingleCodepoint(components[4])], AssumeSingleCodepoint(katakana));
                    AddHiraganaKatakanaMapping(katakanaHiraganaMap, hiraganaKatakanaMap, katakana, hiragana);
                    AddToRomajiDic(kanaToRomaji, hiragana, katakana, romaji);
                    break;

                case "handakuten":
                    regularHandakutenMap.Add(AssumeSingleCodepoint(components[4]), AssumeSingleCodepoint(hiragana));
                    regularHandakutenMap.Add(hiraganaKatakanaMap[AssumeSingleCodepoint(components[4])], AssumeSingleCodepoint(katakana));
                    AddHiraganaKatakanaMapping(katakanaHiraganaMap, hiraganaKatakanaMap, katakana, hiragana);
                    AddToRomajiDic(kanaToRomaji, hiragana, katakana, romaji);
                    break;

                default:
                    throw new InvalidDataException();
                }
            }

            this.kanaToRomaji         = kanaToRomaji;
            this.regularHandakutenMap = new DualDictionary <int, int>(regularHandakutenMap);
            this.regularDakutenMap    = new DualDictionary <int, int>(regularDakutenMap);
            this.smallLargeMap        = new DualDictionary <int, int>(smallLargeMap);
            this.hiraganaKatakanaMap  = new DualDictionary <int, int>(hiraganaKatakanaMap);

            void AddToRomajiDic(Dictionary <string, string> map, string hiragana, string katakana, string romaji)
            {
                map.Add(hiragana, romaji);
                map.Add(katakana, romaji);
            }

            void AddHiraganaKatakanaMapping(Dictionary <int, int> dictionary, Dictionary <int, int> ints, string katakana, string hiragana)
            {
                dictionary.Add(AssumeSingleCodepoint(katakana), AssumeSingleCodepoint(hiragana));
                ints.Add(AssumeSingleCodepoint(hiragana), AssumeSingleCodepoint(katakana));
            }
        }
Ejemplo n.º 27
0
 public abstract void Reflect(bool full,
     Dictionary<string, DTypeDesc>/*!*/ types,
     Dictionary<string, DRoutineDesc>/*!*/ functions,
     DualDictionary<string, DConstantDesc>/*!*/ constants);
Ejemplo n.º 28
0
        public override void Reflect(bool full,
            Dictionary<string, DTypeDesc>/*!*/ types,
            Dictionary<string, DRoutineDesc>/*!*/ functions,
            DualDictionary<string, DConstantDesc>/*!*/ constants)
        {
            // PluginAssembly does not contain any declarations

            // Let the plugin to modify ApplicationContext
            var attrs = PluginAssemblyAttribute.Reflect(PluginAssembly.RealAssembly);
            if (attrs != null)
                foreach (var plug in attrs)
                {
                    var method = plug.LoaderType.GetMethod(PluginAssembly.LoaderMethod, BindingFlags.Public | BindingFlags.Static, null, PluginAssembly.LoaderMethodParameters, null);
                    if (method != null)
                        method.Invoke(null, new object[] { PluginAssembly.ApplicationContext });
                }
        }
 private JMNedictParser(XmlTextReader xmlReader, DualDictionary <string, string> friendlyNames, Stream stream)
 {
     this.xmlReader     = xmlReader;
     this.FriendlyNames = friendlyNames;
     this.stream        = stream;
 }
Ejemplo n.º 30
0
 public override void Reflect(bool full, Dictionary <string, DTypeDesc> types, Dictionary <string, DRoutineDesc> functions, DualDictionary <string, DConstantDesc> constants)
 {
     Debug.Fail();
     throw null;
 }
Ejemplo n.º 31
0
		private void ReflectConstants(FieldInfo[]/*!!*/ realFields, DualDictionary<string, DConstantDesc>/*!*/ constants)
		{
			foreach (FieldInfo field in realFields)
			{
                // reflect only fields with [ImplementsConstant] attribute:
                ImplementsConstantAttribute impl_const = ImplementsConstantAttribute.Reflect(field);
				if (impl_const != null)
                {
                    object value;

                    try
                    {
                        // expect the constant have literal value, otherwise crash
                        value = Convert.ClrLiteralToPhpLiteral(field.GetValue(null));
                    }	
                    catch(Exception)
                    {
                        throw new InvalidCastException();
                    }

                    GlobalConstant constant = new GlobalConstant(this ,new QualifiedName(new Name(impl_const.Name)), field);
                    constant.SetValue(value);

					constants[impl_const.Name, impl_const.CaseInsensitive] = constant.ConstantDesc;
                }
                    

                //// accepts literals of PHP/CLR primitive types only:
                //if (field.IsLiteral && (PhpVariable.IsLiteralPrimitiveType(field.FieldType) || field.FieldType.IsEnum))
                //{
                //    if (impl_const != null)								
                //    {
                //        // ...
                //    }
                //}
			}
		}
Ejemplo n.º 32
0
        /// <summary>
        /// Reflect argfull function, PHP types and constants from given <c>type</c>.
        /// </summary>
        /// <param name="types">Dictionary of types where newly discovered PHP types will be placed. (Types having [ImplementsType] attribute.)</param>
        /// <param name="functions">Dictionary of reflected functions.</param>
        /// <param name="constants">Dictionary of reflected constants.</param>
        /// <param name="type">The type to reflect functions from.</param>
        /// <param name="full">Whether to perform full function reflect.</param>
        private void ReflectArgfulls(
            Dictionary<string, DTypeDesc>/*!*/ types,
            Dictionary<string, DRoutineDesc>/*!*/ functions,
            DualDictionary<string, DConstantDesc>/*!*/ constants,
            Type/*!*/type, bool full)
        {
            // skip generic types:
            if (type.IsGenericTypeDefinition)
                return;

            if (PhpType.IsPhpRealType(type))
            {
                var dtype = PhpTypeDesc.Create(type);
                types[dtype.MakeSimpleName()] = dtype;
            }
            
            // reflect even if it is PhpType to find global functions [ImplementsFunction] and constants [ImplementsConstant]
            if (IsLibraryType(type))
            {
                ReflectLibraryType(functions, constants, type, full);
            }
        }
Ejemplo n.º 33
0
 public override void Reflect(bool full,
     Dictionary<string, DTypeDesc>/*!*/ types,
     Dictionary<string, DRoutineDesc>/*!*/ functions,
     DualDictionary<string, DConstantDesc>/*!*/ constants)
 {
     ReflectTypes(assembly.RealAssembly, types);
     ReflectFunctions(assembly.RealAssembly, globalType.TypeDesc, functions);
     ReflectConstants(assembly.RealAssembly, this, constants);
 }
Ejemplo n.º 34
0
        internal static void ReflectConstants(Assembly/*!*/ realAssembly, DModule/*!*/ declaringModule,
            DualDictionary<string, DConstantDesc>/*!*/ constants)
        {
            Debug.Assert(realAssembly != null && constants != null);

            foreach (FieldInfo real_field in ReflectionUtils.GetGlobalFields(realAssembly, BindingFlags.Public | BindingFlags.Static))
            {
                if (real_field.IsLiteral && !real_field.IsSpecialName)
                {
                    string full_name = QualifiedName.FromClrNotation(real_field.Name, true).ToString();

                    DConstantDesc existing;
                    if (constants.TryGetValue(full_name, out existing))
                    {
                        // can be already loaded from different module (CRL or CLib):
                        existing.MemberAttributes |= PhpMemberAttributes.Ambiguous;
                    }
                    else
                    {
                        object value = real_field.GetValue(null);
                        DConstantDesc const_desc = new DConstantDesc(declaringModule, PhpMemberAttributes.Public | PhpMemberAttributes.Static, value);
                        constants.Add(full_name, const_desc, false);
                    }
                }
            }
        }
 public void SetUp()
 {
     dict = CreateDictionary(d => { });
 }
Ejemplo n.º 36
0
 public override void Reflect(bool full,
     Dictionary<string, DTypeDesc>/*!*/ types,
     Dictionary<string, DRoutineDesc>/*!*/ functions,
     DualDictionary<string, DConstantDesc>/*!*/ constants)
 {
     Debug.Fail();
 }
Ejemplo n.º 37
0
        private static List <ItemPair> parseFactorio(DualDictionary <string, string> mappings, Dictionary <string, double> ratios)
        {
            List <ItemPair> items = new List <ItemPair>();

            using (FileStream fs = new FileStream(ToMCPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                using (StreamReader sr = new StreamReader(fs, Encoding.Default)) {
                    while (!sr.EndOfStream)
                    {
                        string[] temp = sr.ReadLine().Split(':');
                        int      count;
                        if (ratios.Count > 0)
                        {
                            count = (int)Math.Round(double.Parse(temp[1]) * ratios[temp[0]], MidpointRounding.AwayFromZero);
                        }
                        else
                        {
                            count = int.Parse(temp[1]);
                        }
                        int containsTest = pairContains(items, temp[0]);

                        if (containsTest != -1)
                        {
                            if (items[containsTest].count < 64)
                            {
                                int remainder = 64 - items[containsTest].count;
                                if (remainder > 0)
                                {
                                    items[containsTest].count += remainder;
                                    count -= remainder;
                                }
                            }
                            if ((64 - count) < 0)
                            {
                                items.Add(new ItemPair(temp[0], 64));
                                int remain = Math.Abs(64 - count);
                                while (remain > 0)
                                {
                                    if (remain > 64)
                                    {
                                        items.Add(new ItemPair(temp[0], 64));
                                        remain -= 64;
                                    }
                                    else
                                    {
                                        items.Add(new ItemPair(temp[0], remain));
                                        remain -= 64;
                                    }
                                }
                            }
                            else
                            {
                                items.Add(new ItemPair(temp[0], int.Parse(temp[1])));
                            }
                        }
                        else
                        {
                            if ((64 - count) < 0)
                            {
                                items.Add(new ItemPair(temp[0], 64));
                                int remain = Math.Abs(64 - count);
                                while (remain > 0)
                                {
                                    if (remain > 64)
                                    {
                                        items.Add(new ItemPair(temp[0], 64));
                                        remain -= 64;
                                    }
                                    else
                                    {
                                        items.Add(new ItemPair(temp[0], remain));
                                        remain -= 64;
                                    }
                                }
                            }
                            else
                            {
                                items.Add(new ItemPair(temp[0], int.Parse(temp[1])));
                            }
                            //items.Add(new ItemPair(temp[0], Int32.Parse(temp[1])));
                        }
                    }
                }

            //Remap Items to the opposing item
            for (int i = 0; i < items.Count; i++)
            {
                items[i].name = mappings.factorio[items[i].name];
            }
            return(items);
        }
Ejemplo n.º 38
0
		private void InitConstants(DualDictionary<string, object> _constants)
		{
            // Thease constants are here, because they are environment dependent
            // When the code is compiled and assembly is run on another platforms they could be different

            _constants.Add("PHALANGER", PhalangerVersion.Current, false);
            _constants.Add("PHP_VERSION", PhpVersion.Current, false);
            _constants.Add("PHP_MAJOR_VERSION", PhpVersion.Major, false);
            _constants.Add("PHP_MINOR_VERSION", PhpVersion.Minor, false);
            _constants.Add("PHP_RELEASE_VERSION", PhpVersion.Release, false);
            _constants.Add("PHP_VERSION_ID", PhpVersion.Major * 10000 + PhpVersion.Minor * 100 + PhpVersion.Release, false);
            _constants.Add("PHP_EXTRA_VERSION", PhpVersion.Extra, false);
            _constants.Add("PHP_OS", Environment.OSVersion.Platform == PlatformID.Win32NT ? "WINNT" : "WIN32", false); // TODO: GENERICS (Unix)
            _constants.Add("PHP_SAPI", (System.Web.HttpContext.Current == null) ? "cli" : "isapi", false);
            _constants.Add("DIRECTORY_SEPARATOR", FullPath.DirectorySeparatorString, false);
            _constants.Add("PATH_SEPARATOR", Path.PathSeparator.ToString(), false);

            //TODO: should be specified elsewhere (app context??)
            _constants.Add("PHP_EOL", System.Environment.NewLine, false);

            //TODO: this is a bit pesimistic, as this value is a bit higher on Vista and on other filesystems and OSes
            //      sadly .NET does not specify value of MAXPATH constant
            _constants.Add("PHP_MAXPATHLEN", 255, false);

            if (HttpContext.Current == null)
            {
                _constants.Add("STDIN", InputOutputStreamWrapper.In, false);
                _constants.Add("STDOUT", InputOutputStreamWrapper.Out, false);
                _constants.Add("STDERR", InputOutputStreamWrapper.Error, false);
            }
		}
Ejemplo n.º 39
0
        public static void Run()
        {
            FactorioServer.Run(true);
            MinecraftServer.Run(true);

            Wrapper.WriteLine("Preparing FMCBridge...");

            string  SettingsFileName = "Settings.ini";
            string  SettingsFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, SettingsFileName);
            IniFile s = new IniFile(SettingsFileName);

            RootPath = s.Read("ServerFolder", "Windows") + '\\';

            /*
             *                  Load in the item mappings file.
             */
            DualDictionary <String, String> itemMappings    = new DualDictionary <String, String>();
            Dictionary <String, double>     minecraftRatios = new Dictionary <String, double>();
            Dictionary <String, double>     factorioRatios  = new Dictionary <String, double>();

            //Open up the file stream for the item mappings
            string       itemMappingsPath = Path.Combine(RootPath, s.Read("MappingsFile", "FMCBridge"));
            FileStream   fileStream       = new FileStream(itemMappingsPath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read);
            StreamReader streamReader     = new StreamReader(fileStream, Encoding.Default);

            //This loops needs to do a couple of things.
            //The first is it needs to read in the mappings into the DualDictionary for better translation of names.
            //The second it needs to bind the item ratios to their respective lists.
            while (!streamReader.EndOfStream)
            {
                //Item Name Mappings first
                String readString = streamReader.ReadLine();
                if (readString.Contains("#") || readString.Equals("") || readString.Equals("\n"))
                {
                    continue;
                }
                String[] split = readString.Split('=');
                itemMappings.Add(split[0], split[1]);
                //Split the string again to get the ratios
                if (split.Length > 2)
                {
                    String[] ratios = split[2].Split(':');
                    minecraftRatios.Add(split[0], Double.Parse(ratios[0]));
                    factorioRatios.Add(split[1], Double.Parse(ratios[1]));
                }
            }
            streamReader.Close();
            fileStream.Close();

            RCON rcon2 = new RCON(IPAddress.Parse("127.0.0.1"), (ushort)25575, "test_password");

            FMCBridge.Running = true;
            Wrapper.Command("InputMode 3");
            Wrapper.WriteLine("Use \"wrapper InputMode 0\" to access Wrapper mode.");

            /*=======================================
            *  This loop monitors for user input in the console
            *  and sends it to the appropriate process
            *  =======================================*/
            string ConsoleInput = "";

            System.Threading.Tasks.Task.Run
                (async() =>
            {
                do
                {
                    if (Console.IsInputRedirected == false)
                    {
                        //BridgeInput = await Console.In.ReadLineAsync();
                        ConsoleInput = await Console.In.ReadLineAsync();
                        //BridgeInput = Console.ReadLine();
                    }
                } while (FMCBridge.Running == true);
            }
                );
            List <ItemPair> factorioItems;
            List <ItemPair> minecraftItems;

            do
            {
                try {
                    //If the user wasn't a squit
                    if (string.IsNullOrWhiteSpace(ConsoleInput) == false)
                    {
                        switch (Wrapper.InputTarget)
                        {
                        //Default to wrapper
                        case Wrapper.Modes.Menu:
                            Wrapper.Command(ConsoleInput);
                            break;

                        case Wrapper.Modes.MinecraftServer:
                            if (MinecraftServer.Running)
                            {
                                MinecraftServer.ProcessInput(ConsoleInput);
                            }
                            break;

                        case Wrapper.Modes.FactorioServer:
                            if (FactorioServer.Running)
                            {
                                FactorioServer.ProcessInput(ConsoleInput);
                            }
                            break;

                        case Wrapper.Modes.FMCBridge:
                            FMCBridge.ProcessInput(ConsoleInput);
                            break;

                        default:
                            Wrapper.InputTarget = Wrapper.Modes.Menu;
                            throw new TrashMonkeyException("Invalid input mode! Defaulting to wrapper mode.");
                        }
                    }
                    factorioItems  = parseFactorio(itemMappings, factorioRatios);
                    minecraftItems = parseVanillaMinecraft(itemMappings, minecraftRatios, rcon2).Result;
                    sendToFactorioExperimentalIO(minecraftItems);
                    sendToVanillaExperimentalIO(factorioItems);
                }
                catch (TrashMonkeyException e) { //Handled errors
                    Wrapper.ErrorWriteLine(e.Message);
                }
                catch (Exception e) {            //Something actually broke errors
                    Util.PrintErrorInfo(e);
                }
                ConsoleInput = "";
            } while (FMCBridge.Running == true);
            //Exiting this loop should return to the menu
        }
 internal ValueProxy(DualDictionary <TKey, TValue> dict)
 {
     this.dict = dict;
 }
Ejemplo n.º 41
0
        private static async System.Threading.Tasks.Task <List <ItemPair> > parseVanillaMinecraft(DualDictionary <string, string> mappings, Dictionary <string, double> ratios, RCON rcon)
        {
            string RCON_Output = await rcon.SendCommandAsync("execute as @e[tag=SendChest] at @s store result score @s FMCClearItems run data get block ~ ~ ~ Items");

            //string toFactorioString = "";
            if (RCON_Output != "")
            {
                string[]     SplitOutput  = regex.Split(RCON_Output);
                string[][][] ParsedOutput = new string[SplitOutput.Length - 2][][];
                for (int i = 0; i < (SplitOutput.Length - 2); i++)
                {
                    MatchCollection MatchOutput2 = regex2.Matches(SplitOutput[i + 1]);
                    ParsedOutput[i] = new string[MatchOutput2.Count][];
                    for (int j = 0; j < MatchOutput2.Count; j++)
                    {
                        string[] SplitOutput3 = MatchOutput2[j].ToString().Split(new[] { ',' }, 4);
                        ParsedOutput[i][j] = new string[SplitOutput3.Length];
                        for (int k = 0; k < (SplitOutput3.Length); k++)
                        {
                            ParsedOutput[i][j][k] = SplitOutput3[k].Trim();
                        }
                    }
                }
                for (int i = 0; i < ParsedOutput.Length; i++)
                {
                    for (int j = 0; j < ParsedOutput[i].Length; j++)
                    {
                        if (ParsedOutput[i][j].Length == 3)
                        {
                            str.Append(ParsedOutput[i][j][1].Remove(0, 5).TrimEnd('"'));
                            str.Append("~");
                            str.Append(ParsedOutput[i][j][2].Remove(0, 7).TrimEnd('}').TrimEnd('b'));
                        }
                        else
                        {
                            str.Append(ParsedOutput[i][j][1].Remove(0, 5).TrimEnd('"'));
                            str.Append(ParsedOutput[i][j][3].Remove(ParsedOutput[i][j][3].Length - 1, 1).Remove(0, 5));
                            str.Append("~");
                            str.Append(ParsedOutput[i][j][2].Remove(0, 7).TrimEnd('b'));
                        }
                        str.AppendLine();
                    }
                }
                //toFactorioString = str.ToString().TrimEnd(Environment.NewLine.ToCharArray());
                //toFactorioString = str.ToString();
            }
            List <ItemPair> items = new List <ItemPair>();

            //String[] temp7 = str.ToString().TrimEnd(Environment.NewLine.ToCharArray()).Split(Environment.NewLine.ToCharArray());
            foreach (string stringy3 in str.ToString().TrimEnd(Environment.NewLine.ToCharArray()).Split(Environment.NewLine.ToCharArray()))
            {
                if (string.IsNullOrWhiteSpace(stringy3) == false)
                {
                    string[] temp = stringy3.Split('~');
                    int      count;
                    if (ratios.Count > 0)
                    {
                        count = (int)Math.Round(double.Parse(temp[1]) * ratios[temp[0]], MidpointRounding.AwayFromZero);
                    }
                    else
                    {
                        count = int.Parse(temp[1]);
                    }
                    items.Add(new ItemPair(temp[0], count));
                }
            }

            //Remap Items to the opposing item
            for (int i = 0; i < items.Count; i++)
            {
                try {
                    items[i].name = mappings.minecraft[items[i].name];
                }
                catch (Exception) {
                    //PrintErrorInfo(e);
                    continue;
                }
            }
            return(items);
        }
Ejemplo n.º 42
0
 public abstract void Reflect(bool full,
                              Dictionary <string, DTypeDesc> /*!*/ types,
                              Dictionary <string, DRoutineDesc> /*!*/ functions,
                              DualDictionary <string, DConstantDesc> /*!*/ constants);
Ejemplo n.º 43
0
		/// <summary>
		/// Reflect types, functions and constants in compiled CU
		/// </summary>
        /// <param name="full">Not used.</param>
        /// <param name="functions">Will contain reflected functions.</param>
        /// <param name="types">Will contain reflected classes.</param>
        /// <param name="constants">Not used.</param>
		public override void Reflect(bool full,
			Dictionary<string, DTypeDesc>/*!*/ types,
			Dictionary<string, DRoutineDesc>/*!*/ functions,
			DualDictionary<string, DConstantDesc>/*!*/ constants)
		{
            // pairs of <assembly, list of namespaces>
            // each namespace represents relative path to the script containing functions/PHP classes
            var reachedScripts = new Dictionary<Type, bool>();

            CollectIncludees(ScriptType, reachedScripts);

            // reflect functions/classes from reachedScripts
            foreach (var scriptType in reachedScripts.Keys)
            {
                Debug.Assert(scriptType.Name == ScriptModule.ScriptTypeName);

                ReflectScriptTypeFunctions(scriptType, functions);
                ReflectScriptTypeClasses(scriptType, types);
                ReflectScriptTypeConstants(scriptType, constants);
            }
		}
Ejemplo n.º 44
0
        /// <summary>
        /// Assuming the given <c>type</c> is Library type, reflect argfull function stubs, PHP types and constants from given <c>type</c>.
        /// </summary>
        /// <param name="functions">Dictionary of reflected functions.</param>
        /// <param name="constants">Dictionary of reflected constants.</param>
        /// <param name="type">The type to reflect functions from.</param>
        /// <param name="full">Whether to perform full function reflect.</param>
        private void ReflectLibraryType(
            Dictionary<string, DRoutineDesc>/*!*/ functions,
            DualDictionary<string, DConstantDesc>/*!*/ constants,
            Type/*!*/type, bool full)
        {
            // functions (argfulls):
            if (full && !type.IsEnum)
                FullReflectFunctions(type.GetMethods(BindingFlags.Public | BindingFlags.Static), functions, true);

            // constants:
            ReflectConstants(type.GetFields(BindingFlags.Public | BindingFlags.Static), constants);
        }
Ejemplo n.º 45
0
 public override void Reflect(bool full, Dictionary <string, DTypeDesc> types, Dictionary <string, DRoutineDesc> functions, DualDictionary <string, DConstantDesc> constants)
 {
     throw new Exception("The method or operation is not implemented.");
 }
Ejemplo n.º 46
0
 public override void Reflect(bool full, Dictionary<string, DTypeDesc> types, Dictionary<string, DRoutineDesc> functions, DualDictionary<string, DConstantDesc> constants) {
     throw new Exception("The method or operation is not implemented.");
 }
Ejemplo n.º 47
0
		public Account(bool addToWorld)
			: base(DatabaseID.Zero, addToWorld) {
			Chars = new DualDictionary<WorldID, Character>();
			AccountState = EAccountState.None;
		}