public static Double TryObjectToDouble(object obj, out ConversionStrictness strictness) { string s; if (obj is double) { strictness = ConversionStrictness.ImplExactMatch; return((double)obj); } if (obj is int) { strictness = ConversionStrictness.ImplExactMatch; return((double)(int)obj); } if ((s = PhpVariable.AsString(obj)) != null) { strictness = ConversionStrictness.ImplDomainChange; return(Convert.StringToDouble(s)); } if (obj is bool) { strictness = ConversionStrictness.ImplDomainChange; return((bool)obj ? 1.0 : 0.0); } if (obj is long) { strictness = ConversionStrictness.ImplExactMatch; return((double)(long)obj); } strictness = ConversionStrictness.Failed; return(0.0); }
/// <summary> /// Calls user error handler. /// </summary> /// <returns>Whether to report error by default handler (determined by handler's return value).</returns> /// <exception cref="ScriptDiedException">Error handler dies.</exception> private static bool CallUserErrorHandler(ScriptContext context, PhpError error, Func <ErrorStackInfo> info, string message) { LocalConfiguration config = context.Config; try { object result = PhpVariable.Dereference(config.ErrorControl.UserHandler.Invoke(new PhpReference[] { new PhpReference((int)error), new PhpReference(message), new PhpReference(new LazyStackInfo(info, true)), new PhpReference(new LazyStackInfo(info, false)), new PhpReference() // global variables list is not supported })); // since PHP5 an error is reported by default error handler if user handler returns false: return(result is bool && (bool)result == false); } catch (ScriptDiedException) { // user handler has cancelled the error via script termination: throw; } catch (PhpUserException) { // rethrow user exceptions: throw; } catch (Exception) { } return(false); }
public static T TryObjectToDelegate <T>(object obj, out ConversionStrictness strictness) where T : class { T result = null; object bare_obj = PhpVariable.Unwrap(obj); if (bare_obj == null || (result = bare_obj as T) != null) { strictness = ConversionStrictness.ImplExactMatch; return(result); } // try to convert the object to PhpCallback PhpCallback callback = Convert.ObjectToCallback(obj, true); if (callback != null && callback.Bind(true)) { // generate a conversion stub result = EventClass <T> .GetStub( callback.TargetInstance, callback.TargetRoutine, callback.IsBoundToCaller?callback.RoutineName : null); if (result != null) { strictness = ConversionStrictness.ImplExactMatch; return(result); } } strictness = ConversionStrictness.Failed; return(default(T)); }
public static void InvalidImplicitCast(object argument, string targetType, string functionName) { Throw(PhpError.Warning, CoreResources.GetString("invalid_implicit_cast", PhpVariable.GetTypeName(argument), targetType, functionName)); }
new public static void GetObjectData(DObject /*!*/ instance, SerializationInfo /*!*/ info, StreamingContext strctx) { info.SetType(typeof(SPLDeserializer)); SerializationContext context = SerializationContext.CreateFromStreamingContext(strctx); object res = PhpVariable.Dereference(instance.InvokeMethod("serialize", null, context.ScriptContext)); if (res == null) { // serialize returned NULL -> this instance will deserialize as NULL info.AddValue(__PHP_Incomplete_Class.ClassNameFieldName, String.Empty); } else { string res_str = PhpVariable.AsString(res); if (res_str == null) { // serialize did not return NULL nor a string -> throw an exception Library.SPL.Exception.ThrowSplException( _ctx => new Library.SPL.Exception(_ctx, true), context.ScriptContext, string.Format(CoreResources.serialize_must_return_null_or_string, instance.TypeName), 0, null); } info.AddValue(SerializedDataFieldName, res_str); info.AddValue(__PHP_Incomplete_Class.ClassNameFieldName, instance.TypeName); } }
public void Dump(TextWriter /*!*/ output) { output.WriteLine("<pre>"); output.WriteLine("Stack (args_Length = {0}, types_Length = {5}, args_Top = {1}, types_Top = {6}, " + "argc = {2}, typec = {7}, callee = {3}, callback = {4}):", Items.Length, Top, ArgCount, CalleeName, Callback, Types.Length, TypesTop, TypeArgCount); output.WriteLine("Args:"); for (int i = 0; i < Top; i++) { output.WriteLine("{0}:", i); PhpVariable.Dump(output, Items[i]); } output.WriteLine("Types:"); for (int i = 0; i < TypesTop; i++) { output.WriteLine("{0}:", i); output.WriteLine(Types[i]); } output.WriteLine("</pre>"); }
public static object UnwrapNullable(object obj) { obj = PhpVariable.Unwrap(obj); if (obj == null) { return(null); } // This could be done more efficiently, but it is not used very often... Type ty = obj.GetType(); if (ty.IsGenericType && ty.GetGenericTypeDefinition() == typeof(Nullable <>)) { bool val = (bool)ty.GetProperty("HasValue").GetGetMethod().Invoke(obj, Type.EmptyTypes); if (!val) { return(null); } return(ty.GetProperty("Value").GetGetMethod().Invoke(obj, Type.EmptyTypes)); } else { return(obj); } }
//private static object GpcEncodeValue(object value, LocalConfiguration config) //{ // if (value != null && value.GetType() == typeof(string)) // { // // url-decodes the values: (COOKIES ONLY) // string svalue = HttpUtility.UrlDecode((string)value, Configuration.Application.Globalization.PageEncoding); // // quotes the values: // if (Configuration.Global.GlobalVariables.QuoteGpcVariables) // { // if (config.Variables.QuoteInDbManner) // svalue = StringUtils.AddDbSlashes(svalue); // svalue = StringUtils.AddCSlashes(svalue, true, true); // } // // // value = svalue; // } // return value; //} /// <summary> /// Adds variables from one auto-global array to another. /// </summary> /// <param name="dst">The target array.</param> /// <param name="src">The source array.</param> /// <remarks>Variable values are deeply copied.</remarks> /// <exception cref="ArgumentNullException"><paramref name="dst"/> is a <B>null</B> reference.</exception> /// <exception cref="ArgumentNullException"><paramref name="src"/> is a <B>null</B> reference.</exception> private static void AddVariables(PhpArray /*!*/ dst, PhpArray /*!*/ src) { Debug.Assert(dst != null && src != null); foreach (KeyValuePair <IntStringKey, object> entry in src) { dst[entry.Key] = PhpVariable.DeepCopy(entry.Value); } }
/// <summary> /// Evaluates this chain as if it had the <see cref="PHP.Core.AST.AccessType.ReadRef"/> access type. /// </summary> /// <param name="context">Current script context.</param> /// <returns>The result of chain evaluation.</returns> public PhpReference GetReference(ScriptContext context) { PhpReference reference; RuntimeChainElement element = Chain; if (element == null) { // if we are just wrapping the variable with a PhpReference, make a copy reference = Variable as PhpReference; if (reference == null) { reference = new PhpReference(PhpVariable.Copy(Variable, CopyReason.Unknown)); } return(reference); } // make sure that we have a PhpReference reference = PhpVariable.MakeReference(Variable); if (element == lastElement) { // GetPropertyRef/GetItemRef return(element.GetRef(ref reference.value, context, Caller)); } // EnsureVariableIsObject/EnsureVariableIsArray object var = element.EnsureVariable(ref reference.value, context, Caller); if (var == null) { return(new PhpReference()); } while (element.Next != null) { // Ensure{Field,Item}Is{Object,Array} var = element.Ensure(var, context, Caller); if (var == null) { return(new PhpReference()); } element = element.Next; } // GetObjectPropertyRef/GetArrayItemRef return(element.GetEnsuredRef(var, context, Caller)); }
/// <summary> /// Evaluates this chain as if it had the <see cref="PHP.Core.AST.AccessType.Read"/> access type. /// </summary> /// <param name="context">Current script context.</param> /// <returns>The result of chain evaluation.</returns> public object GetValue(ScriptContext context) { // dereference the PhpReference object var = PhpVariable.Dereference(Variable); RuntimeChainElement element = Chain; while (element != null) { // GetProperty/GetItem var = element.Get(var, context, Caller); element = element.Next; } return(var); }
public static T TryObjectToStruct <T>(object obj, out ConversionStrictness strictness) where T : struct { obj = PhpVariable.Unwrap(obj); if (obj is T) { strictness = ConversionStrictness.ImplExactMatch; return((T)obj); } else { strictness = ConversionStrictness.Failed; return(default(T)); } }
public static bool Assert( object assertion, ScriptContext context, Dictionary <string, object> definedVariables, DObject self, DTypeDesc includer, string containingSourcePath, int line, int column, int containerId, NamingContext namingContext) { object result; string code; // skips asserts if not active: if (!context.Config.Assertion.Active) { return(true); } if ((code = PhpVariable.AsString(assertion)) != null) { // disables error reporting if eval should be quite: if (context.Config.Assertion.Quiet) { context.DisableErrorReporting(); } SourceCodeDescriptor descriptor = new SourceCodeDescriptor(containingSourcePath, containerId, line, column); // evaluates the expression: result = EvalInternal("return ", code, ";", EvalKinds.Assert, context, definedVariables, self, includer, descriptor, false, namingContext); // restores error reporting if eval have been quite: if (context.Config.Assertion.Quiet) { context.EnableErrorReporting(); } } else { result = assertion; } // checks the result of assertion: return(CheckAssertion(result, code, context, containingSourcePath, line, column, namingContext)); }
public static String TryObjectToString(object obj, out ConversionStrictness strictness) { string s; PhpReference pr; IPhpConvertible conv; if ((s = PhpVariable.AsString(obj)) != null) { strictness = ConversionStrictness.ImplExactMatch; return(s); } if ((pr = obj as PhpReference) != null) { return(TryObjectToString(pr.Value, out strictness)); } if (obj == null) { strictness = ConversionStrictness.ImplDomainChange; return(null); } if (obj is int) { strictness = ConversionStrictness.ImplDomainChange; return(obj.ToString()); } if (obj is bool) { strictness = ConversionStrictness.ImplDomainChange; return(((bool)obj) ? "1" : String.Empty); } if (obj is double) { strictness = ConversionStrictness.ImplDomainChange; return(Convert.DoubleToString((double)obj)); } if (obj is long) { strictness = ConversionStrictness.ImplDomainChange; return(obj.ToString()); } // explicit conversion if ((conv = obj as IPhpConvertible) != null) { bool success; string ret = conv.ToString(false, out success); strictness = success?ConversionStrictness.Failed:ConversionStrictness.Explicit; return(ret); } strictness = ConversionStrictness.Failed; return(String.Empty); }
/// <summary> /// Reports an error when a variable should be PHP object but it is not. /// </summary> /// <param name="reference">Whether a reference modifier (=&) is used.</param> /// <param name="var">The variable which was misused.</param> /// <exception cref="PhpException"><paramref name="var"/> is <see cref="PhpArray"/> (Warning).</exception> /// <exception cref="PhpException"><paramref name="var"/> is scalar type (Warning).</exception> /// <exception cref="PhpException"><paramref name="var"/> is a string (Warning).</exception> public static void VariableMisusedAsObject(object var, bool reference) { Debug.Assert(var != null); if (var is PhpArray) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("array_used_as_object")); } else if (PhpVariable.IsString(var)) { PhpException.Throw(PhpError.Warning, CoreResources.GetString(reference ? "string_item_used_as_reference" : "string_used_as_object")); } else { PhpException.Throw(PhpError.Warning, CoreResources.GetString("scalar_used_as_object", PhpVariable.GetTypeName(var))); } }
public object PeekValueUnchecked(int i) { PhpRuntimeChain php_chain; // caller may have pushed a reference even if a formal argument is not reference => dereference it: object result = PhpVariable.Dereference(Items[Top - i]); // caller may have pushed a runtime chain => evaluate it: if ((php_chain = result as PhpRuntimeChain) != null) { // call state has to be stored since chain can call arbitrary user code: CallState call_state = SaveCallState(); result = php_chain.GetValue(Context); RestoreCallState(call_state); } return(result); }
public static T TryObjectToClass <T>(object obj, out ConversionStrictness strictness) where T : class { if (obj == null) { strictness = ConversionStrictness.ImplDomainChange; return(null); } T result = null; if ((result = PhpVariable.Unwrap(obj) as T) != null && (!(result is IPhpVariable) || result is PhpObject || result is PhpArray)) { strictness = ConversionStrictness.ImplExactMatch; return(result); } strictness = ConversionStrictness.Failed; return(default(T)); }
/// <summary> /// Reports an error when a variable should be PHP array but it is not. /// </summary> /// <param name="reference">Whether a reference modifier (=&) is used.</param> /// <param name="var">The variable which was misused.</param> /// <exception cref="PhpException"><paramref name="var"/> is <see cref="PhpArray"/> (Warning).</exception> /// <exception cref="PhpException"><paramref name="var"/> is scalar type (Warning).</exception> /// <exception cref="PhpException"><paramref name="var"/> is a string (Warning).</exception> public static void VariableMisusedAsArray(object var, bool reference) { Debug.Assert(var != null); DObject obj; if ((obj = var as DObject) != null) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("object_used_as_array", obj.TypeName)); } else if (PhpVariable.IsString(var)) { PhpException.Throw(PhpError.Warning, CoreResources.GetString(reference ? "string_item_used_as_reference" : "string_used_as_array")); } else { PhpException.Throw(PhpError.Warning, CoreResources.GetString("scalar_used_as_array", PhpVariable.GetTypeName(var))); } }
public static T[] TryObjectToArray <T>(object obj, out ConversionStrictness strictness) { T[] result = PhpVariable.Unwrap(obj) as T[]; if (result != null) { strictness = ConversionStrictness.ImplExactMatch; return(result); } // try to convert PhpArray to the desired array PhpArray array = obj as PhpArray; if (array != null && array.StringCount == 0) { result = new T[array.MaxIntegerKey + 1]; strictness = ConversionStrictness.ImplExactMatch; for (int i = 0; i < result.Length; i++) { object item; if (array.TryGetValue(i, out item)) { // try to convert the item ConversionStrictness tmp; result[i] = TryObjectToType <T>(item, out tmp); if (tmp > strictness) { strictness = tmp; } if (strictness == ConversionStrictness.Failed) { return(default(T[])); } } } return(result); } strictness = ConversionStrictness.Failed; return(default(T[])); }
public PhpReference PeekReferenceUnchecked(int i) { object item = Items[Top - i]; PhpReference result; PhpRuntimeChain php_chain; // the caller may not pushed a reference although the formal argument is a reference: // it doesn't matter if called by callback: if ((result = item as PhpReference) == null) { // caller may have pushed a runtime chain => evaluate it: if ((php_chain = item as PhpRuntimeChain) != null) { // call state has to be stored since chain can call arbitrary user code: CallState call_state = SaveCallState(); result = php_chain.GetReference(Context); RestoreCallState(call_state); } else { // the reason of copy is not exactly known (it may be returning by copy as well as passing by copy): result = new PhpReference(PhpVariable.Copy(item, CopyReason.Unknown)); // Reports an error in the case that we are not called by callback. // Although, this error is fatal one can switch throwing exceptions off. // If this is the case the afterwards behavior will be the same as if callback was called. if (!Callback) { // warning (can invoke user code => we have to save and restore callstate): CallState call_state = SaveCallState(); PhpException.ArgumentNotPassedByRef(i, CalleeName); RestoreCallState(call_state); } } } return(result); }
/// <summary> /// Prints a content of the given variable and its type. /// </summary> /// <param name="output">The output text stream.</param> /// <param name="obj">The variable to be printed.</param> public static void Dump(TextWriter output, object obj) { string s; IPhpPrintable printable; if ((printable = obj as IPhpPrintable) != null) { printable.Dump(output); } else if ((s = obj as string) != null) { output.WriteLine(TypeNameString + "({0}) \"{1}\"", s.Length, s); } else if (obj is double) { output.WriteLine(TypeNameFloat + "({0})", Convert.DoubleToString((double)obj)); } else if (obj is bool) { output.WriteLine(TypeNameBool + "({0})", (bool)obj ? True : False); } else if (obj is int) { output.WriteLine(TypeNameInt + "({0})", (int)obj); } else if (obj is long) { output.WriteLine(TypeNameLongInteger + "({0})", (long)obj); } else if (obj == null) { output.WriteLine(PhpVariable.TypeNameNull); } else { output.WriteLine("{0}({1})", PhpVariable.GetTypeName(obj), obj.ToString()); } }
/// <summary> /// Exports a value which is referenced by this instance. /// </summary> /// <param name="output">The output where the value is printed.</param> public void Export(System.IO.TextWriter output) { PhpVariable.Export(output, value); }
/// <summary> /// Dumps a value which is referenced by this instance. /// </summary> /// <param name="output">The output where the value is printed.</param> public void Dump(System.IO.TextWriter output) { output.Write("&"); PhpVariable.Dump(output, value); }
public static UInt64 TryObjectToUInt64(object obj, out ConversionStrictness strictness) { string s; if (obj is int) { int ival = (int)obj; strictness = ival >= 0 ? ConversionStrictness.ImplExactMatch : ConversionStrictness.Failed; return(unchecked ((UInt64)ival)); } if (obj is long) { long lval = (long)obj; strictness = lval >= 0 ? ConversionStrictness.ImplExactMatch : ConversionStrictness.Failed; return(unchecked ((UInt64)lval)); } if (obj is bool) { strictness = ConversionStrictness.ImplDomainChange; return((ulong)((bool)obj ? 1 : 0)); } if (obj is double) { double dval = (double)obj; strictness = (dval >= UInt64.MinValue && dval <= UInt64.MaxValue) ? ConversionStrictness.ImplPercisionLost : ConversionStrictness.Failed; return(unchecked ((UInt64)dval)); } if ((s = PhpVariable.AsString(obj)) != null) { int ival; double dval; long lval; // successfull iff the number encoded in the string fits Int32 or Int64: Convert.NumberInfo info = Convert.StringToNumber(s, out ival, out lval, out dval); if ((info & Convert.NumberInfo.Integer) != 0) { strictness = ConversionStrictness.ImplDomainChange; return(unchecked ((UInt64)ival)); } if ((info & Convert.NumberInfo.LongInteger) != 0) { strictness = ConversionStrictness.ImplDomainChange; return(unchecked ((UInt64)lval)); } strictness = (dval >= UInt64.MinValue && dval <= UInt64.MaxValue) ? ConversionStrictness.ImplPercisionLost : ConversionStrictness.Failed; return(unchecked ((UInt64)dval)); } // explicit conversion /*IPhpConvertible conv; * if ((conv = obj as IPhpConvertible) != null) * { * int ival; * double dval; * long lval; * * Convert.NumberInfo info = conv.ToNumber(out ival, out lval, out dval); * if ((info & Convert.NumberInfo.Integer) != 0) * { strictness = ConversionStrictness.Explicit; return unchecked((UInt64)ival); } * if ((info & Convert.NumberInfo.LongInteger) != 0) * { strictness = ConversionStrictness.Explicit; return unchecked((UInt64)lval); } * * strictness = (dval >= UInt64.MinValue && dval <= UInt64.MaxValue) ? * ConversionStrictness.Explicit : ConversionStrictness.Failed; * return unchecked((UInt64)dval); * }*/ strictness = ConversionStrictness.Failed; return(0); }
public static Int32 TryObjectToInt32(object obj, out ConversionStrictness strictness) { string s; if (obj is int) { strictness = ConversionStrictness.ImplExactMatch; return((int)obj); } if (obj is bool) { strictness = ConversionStrictness.ImplDomainChange; return((bool)obj ? 1 : 0); } if (obj is long) { long lval = (long)obj; if (lval < Int32.MinValue || lval > Int32.MaxValue) { strictness = ConversionStrictness.Failed; } else { strictness = ConversionStrictness.ImplExactMatch; } return(unchecked ((Int32)lval)); } if (obj is double) { double dval = (double)obj; if (dval < Int32.MinValue || dval > Int32.MaxValue) { strictness = ConversionStrictness.Failed; } else { strictness = ConversionStrictness.ImplPercisionLost; } return(unchecked ((Int32)dval)); } if ((s = PhpVariable.AsString(obj)) != null) { int ival; double dval; long lval; // successfull iff the number encoded in the string fits the Int32: Convert.NumberInfo info = Convert.StringToNumber(s, out ival, out lval, out dval); if ((info & Convert.NumberInfo.Integer) != 0) { strictness = ConversionStrictness.ImplDomainChange; return(ival); } // "123 hello world" -> 123 (for example) strictness = ConversionStrictness.Failed; return(unchecked ((Int32)lval)); } // explicit conversion /*IPhpConvertible conv; * if ((conv = obj as IPhpConvertible) != null) * { * int ival; * double dval; * long lval; * * Convert.NumberInfo info = conv.ToNumber(out ival, out lval, out dval); * if ((info & (Convert.NumberInfo.Integer | Convert.NumberInfo.IsNumber)) == * (Convert.NumberInfo.Integer | Convert.NumberInfo.IsNumber)) * { * strictness = ConversionStrictness.Explicit; * return ival; * } * * strictness = ConversionStrictness.Failed; * return unchecked((Int32)lval); * }*/ strictness = ConversionStrictness.Failed; return(0); }
/// <summary> /// Retrieves a copy of this instance. /// </summary> /// <returns>The copy.</returns> /// <remarks> /// If this <see cref="PhpSmartReference"/> <see cref="IsAliased"/>, this instance is returned without copying. /// That is because (deep) copying stops on references in PHP. If this instance is not <see cref="IsAliased"/>, /// a new <see cref="PhpSmartReference"/> referencing a copy of the current value is returned. /// </remarks> public override object Copy(CopyReason reason) { return(IsAliased ? this : new PhpSmartReference(PhpVariable.Copy(value, reason))); }
/// <summary> /// Retrieves a deep copy of this instance. /// </summary> /// <returns>The copy.</returns> /// <remarks> /// If this <see cref="PhpSmartReference"/> <see cref="IsAliased"/>, this instance is returned without copying. /// That is because deep copying stops on references in PHP. If this instance's <see cref="IsAliased"/> is /// <B>false</B>, a new <see cref="PhpSmartReference"/> referencing a deep copy of the current value is returned. /// </remarks> public override object DeepCopy() { return(IsAliased ? this : new PhpSmartReference(PhpVariable.DeepCopy(value))); }
/// <summary> /// Returns a name of declaring type. /// </summary> /// <returns>The name.</returns> public string GetTypeName() { return(PhpVariable.GetTypeName(value)); }
/// <summary> /// Defines whether <see cref="PhpReference"/> is a scalar. /// </summary> /// <returns>Whether a referenced object is a scalar.</returns> public bool IsScalar() { return(PhpVariable.IsScalar(value)); }
/// <summary> /// Checks whether a specified name is valid constant name. /// </summary> /// <param name="name">The name.</param> /// <seealso cref="PhpVariable.IsValidName"/> public static bool IsValidName(string name) { // TODO: qualified names are valid as well return(PhpVariable.IsValidName(name)); }
/// <summary> /// Whether this instance is empty. /// </summary> /// <returns>Whether a referenced object is empty.</returns> public bool IsEmpty() { return(PhpVariable.IsEmpty(value)); }