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); } }
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); } } } }
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)); }
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); }
/// <summary> /// Reflect global constants in <script> 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); } }
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); }
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); }
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); }
/// <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); }
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); }
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); //} }
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)); }
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); }); } }
/// <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); } }
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]); } } } }
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 }); } } } }
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); }); } }
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) // { // // ... // } //} } }
/// <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); } }
public override void Reflect(bool full, Dictionary<string, DTypeDesc> types, Dictionary<string, DRoutineDesc> functions, DualDictionary<string, DConstantDesc> constants) { Debug.Fail(); throw null; }
public Account(bool addToWorld) : base(DatabaseID.Zero, addToWorld) { Chars = new DualDictionary <WorldID, Character>(); AccountState = EAccountState.None; }
/// <summary> /// Reflect global constants in <script> 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); } }
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)); } }
public abstract void Reflect(bool full, Dictionary<string, DTypeDesc>/*!*/ types, Dictionary<string, DRoutineDesc>/*!*/ functions, DualDictionary<string, DConstantDesc>/*!*/ constants);
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; }
public override void Reflect(bool full, Dictionary <string, DTypeDesc> types, Dictionary <string, DRoutineDesc> functions, DualDictionary <string, DConstantDesc> constants) { Debug.Fail(); throw null; }
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) // { // // ... // } //} } }
/// <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); } }
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); }
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 => { }); }
public override void Reflect(bool full, Dictionary<string, DTypeDesc>/*!*/ types, Dictionary<string, DRoutineDesc>/*!*/ functions, DualDictionary<string, DConstantDesc>/*!*/ constants) { Debug.Fail(); }
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); }
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); } }
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; }
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); }
public abstract void Reflect(bool full, Dictionary <string, DTypeDesc> /*!*/ types, Dictionary <string, DRoutineDesc> /*!*/ functions, DualDictionary <string, DConstantDesc> /*!*/ constants);
/// <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); } }
/// <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); }
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."); }
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."); }
public Account(bool addToWorld) : base(DatabaseID.Zero, addToWorld) { Chars = new DualDictionary<WorldID, Character>(); AccountState = EAccountState.None; }