public PhpFunctionGroup(string @namespace, MethodGroup o) { var functions = o.Methods.Select(m => new PhpOperation(m)); Class = PHP.Class( name: Class.CreateName(@namespace, o.Name), constructor: PHP.Constructor( parameters: GroupConstructorParameters, body: functions.SelectMany(f => f.ConstructorStatements)), functions: functions.Select(f => f.Function), properties: functions.Select(f => f.Property)); Property = PHP.Property(Class.Name, "_" + o.Name + "_group"); Create = PHP .This .Arrow(Property) .Assign(PHP.New(Class.Name, ClientParameterRef)) .Statement(); Function = PHP.Function( name: $"get{o.Name}", @return: Class, body: PHP.Statements(PHP.Return(PHP.This.Arrow(Property)))); }
static void Main() { PHP php = new PHP(); php.name = "앙기모"; Console.WriteLine(php.name); }
public PhpOperation(Method m) { var name = "_" + m.Name + "_operation"; Property = PHP.Property(new ClassName(MicrosoftRestOperationInterface), name); var thisProperty = PHP.This.Arrow(Property); ConstructorStatements = OperationInfoInit(thisProperty, m); var parameters = m.Parameters .Where(p => !p.IsConstant && !p.IsApiVersion() && p.SerializedName != "subscriptionId"); var call = PHP.Return(thisProperty.Call( CallFunction, PHP.CreateArray(parameters.Select(p => PHP.KeyValue( p.SerializedName, new ObjectName(p.SerializedName).Ref()))))); Function = PHP.Function( name: m.Name, description: m.Description, @return: m.ReturnType.Body == null ? null : SchemaObject.Create(m.ReturnType.Body).ToPhpType(), parameters: parameters.Select(p => { var phpType = SchemaObject.Create(p.ModelType).ToPhpType(); return(PHP.Parameter( p.IsRequired ? phpType : new Nullable(phpType), new ObjectName(p.SerializedName))); }), body: PHP.Statements(call)); }
static IEnumerable <Statement> OperationInfoInit( Expression0 property, Method m) { // $_client->createOperation({...operationId...}) var operationInfoCreate = ClientParameterRef.Call( CreateOperation, PHP.StringConst(m.SerializedName)); // $this->{...operation...} = return(PHP.Statements(property.Assign(operationInfoCreate).Statement())); }
public override async Task Generate(CodeModel codeModel) { var @namespace = Class.CreateName(codeModel.Namespace); var phpGroups = codeModel.Operations .Where(o => o.Name.RawValue != string.Empty) .Select(o => new PhpFunctionGroup(@namespace, o)); var phpFunctions = codeModel.Operations .Where(o => o.Name.RawValue == string.Empty) .SelectMany(o => o.Methods.Select(m => new PhpOperation(m))); var swaggerObjectData = PHP.Const( SwaggerObjectData, PHP.FromJson(SwaggerObject.Create(codeModel))); var client = PHP.Class( name: Class.CreateName(@namespace, codeModel.Name), constructor: PHP.Constructor( parameters: ClientConstructorParameters, body: PHP .Statements(CreateClient) .Concat(phpGroups.Select(g => g.Create)) .Concat(phpFunctions.SelectMany(f => f.ConstructorStatements))), functions: phpGroups .Select(o => o.Function) .Concat(phpFunctions.Select(f => f.Function)), properties: phpGroups .Select(o => o.Property) .Concat(phpFunctions.Select(f => f.Property)), consts: PHP.Consts(swaggerObjectData)); foreach (var class_ in phpGroups .Select(o => o.Class) .Concat(ImmutableArray.Create(client))) { await Write( string.Join("\n", class_.ToCodeText(Indent)), class_.Name.FileName, false); } }
public static int Apply(ScriptContext/*!*/context, PHP.Core.Reflection.DTypeDesc caller, Iterator/*!*/iterator, PhpCallback function, PhpArray args) { // check parameters: Debug.Assert(context != null); Debug.Assert(iterator != null, "Phalanger should not pass a null here."); if (function == null) { PhpException.ArgumentNull("function"); return -1; } // copy args into object array: object[] args_array; if (args != null) { args_array = new object[args.Count]; args.Values.CopyTo(args_array, 0); } else { args_array = ArrayUtils.EmptyObjects; } // iterate through the iterator: int n = 0; iterator.rewind(context); while (PHP.Core.Convert.ObjectToBoolean(iterator.valid(context))) { if (!PHP.Core.Convert.ObjectToBoolean(function.Invoke(caller, args_array))) break; n++; iterator.next(context); } // return amount of iterated elements: return n; }
public IType ToPhpType() { if (Ref != null) { return(PHP.Array()); } switch (Type) { case "string": return(PHP.String); case "integer": switch (Format) { case "int32": return(PHP.Integer); case "int64": return(PHP.String); default: throw new Exception("unknown integer format: " + Format); } case "boolean": return(PHP.Boolean); case "file": return(PHP.String); case "array": return(PHP.Array(Items.ToPhpType())); case "object": return(PHP.Array(AdditionalProperties?.ToPhpType())); default: throw new Exception("unknown swagger type: " + Type); } }
public static object SetErrorHandler(PHP.Core.Reflection.DTypeDesc caller, PhpCallback newHandler) { return SetErrorHandler(caller, newHandler, (int)PhpErrorSet.Handleable); }
public static PhpReference Unserialize(PHP.Core.Reflection.DTypeDesc caller, PhpBytes bytes) { if (bytes == null || bytes.Length == 0) return new PhpReference(false); LibraryConfiguration config = LibraryConfiguration.GetLocal(ScriptContext.CurrentContext); return config.Serialization.DefaultSerializer.Deserialize(bytes, caller); }
public static string ReadString(PHP PHP) { return(ReadString(PHP.GetURL())); }
private static object[] GetStubParameterTypes( int paramCount, int typeParamCount, PhpRoutineSignature/*!*/ signature, PHP.Core.AST.FormalTypeParam[]/*!*/ formalTypeParams) { object[] parameter_types = new object[paramCount]; for (int i = 0; i < paramCount; i++) { DType type_hint = signature.TypeHints[i]; if (type_hint != null && !type_hint.IsUnknown) { GenericParameter gen_type_hint = type_hint as GenericParameter; if (gen_type_hint != null) { // this is a generic parameter - declared by either the method or type if (gen_type_hint.DeclaringMember is PhpRoutine) { if (gen_type_hint.Index < typeParamCount) { // unknown at this point - fixed-up later parameter_types[i] = gen_type_hint.Index; } else { // default generic parameter var typeparam = formalTypeParams[gen_type_hint.Index].DefaultType; DType default_type = typeparam as DType; if (default_type == null && typeparam is GenericQualifiedName) default_type = PrimitiveType.GetByName((GenericQualifiedName)typeparam); parameter_types[i] = (default_type == null ? Types.Object[0] : default_type.RealType); } } else parameter_types[i] = gen_type_hint.RealGenericTypeParameterBuilder; } else parameter_types[i] = type_hint.RealType; } else parameter_types[i] = Types.Object[0]; // make it byref if declared with & if (signature.AliasMask[i]) { Type type = parameter_types[i] as Type; if (type != null) parameter_types[i] = type.MakeByRefType(); else parameter_types[i] = -((int)parameter_types[i] + 1); } Debug.Assert(parameter_types[i] != null); } return parameter_types; }
public static Vector[] ToOrthonormal(Vector[] coords, double[] masses, int[] block, Vector[] PBlk) { if (HDebug.IsDebuggerAttached) #region check if elements in non-block are zeros. { int leng = coords.Length; foreach (int i in HEnum.HEnumCount(leng).HEnumExcept(block.HToHashSet())) { for (int r = 0; r < PBlk.Length; r++) { int c0 = i * 3; HDebug.Assert(PBlk[r][c0 + 0] == 0); HDebug.Assert(PBlk[r][c0 + 1] == 0); HDebug.Assert(PBlk[r][c0 + 2] == 0); } } } #endregion Matrix Pmat = new double[block.Length * 3, PBlk.Length]; for (int r = 0; r < PBlk.Length; r++) { for (int i = 0; i < block.Length; i++) { int i0 = i * 3; int c0 = block[i] * 3; Pmat[i0 + 0, r] = PBlk[r][c0 + 0]; Pmat[i0 + 1, r] = PBlk[r][c0 + 1]; Pmat[i0 + 2, r] = PBlk[r][c0 + 2]; } } using (new Matlab.NamedLock("")) { Matlab.PutValue("n", PBlk.Length); Matlab.PutMatrix("P", Pmat); Matlab.Execute("[U,S,V] = svd(P);"); Matlab.Execute("U = U(:,1:n);"); if (HDebug.IsDebuggerAttached) { Matlab.Execute("SV = S(1:n,1:n)*V';"); double err = Matlab.GetValue("max(max(abs(P - U*SV)))"); HDebug.Assert(Math.Abs(err) < 0.00000001); } Pmat = Matlab.GetMatrix("U"); } Vector[] PBlkOrth = new Vector[PBlk.Length]; for (int r = 0; r < PBlk.Length; r++) { Vector PBlkOrth_r = new double[PBlk[r].Size]; for (int i = 0; i < block.Length; i++) { int i0 = i * 3; int c0 = block[i] * 3; PBlkOrth_r[c0 + 0] = Pmat[i0 + 0, r]; PBlkOrth_r[c0 + 1] = Pmat[i0 + 1, r]; PBlkOrth_r[c0 + 2] = Pmat[i0 + 2, r]; } PBlkOrth[r] = PBlkOrth_r; } if (HDebug.IsDebuggerAttached) #region checi the orthonormal condition, and rot/trans condition (using ANM) { { // check if all trans/rot modes are orthonormal for (int i = 0; i < PBlkOrth.Length; i++) { HDebug.Exception(Math.Abs(PBlkOrth[i].Dist - 1) < 0.00000001); for (int j = i + 1; j < PBlkOrth.Length; j++) { double dot = LinAlg.VtV(PBlkOrth[i], PBlkOrth[j]); HDebug.Exception(Math.Abs(dot) < 0.00000001); } } } { // check if this is true rot/trans modes using ANM Vector[] anmcoords = coords.HClone(); int leng = coords.Length; foreach (int i in HEnum.HEnumCount(leng).HEnumExcept(block.HToHashSet())) { anmcoords[i] = null; } HessMatrix H = GetHessAnm(anmcoords, 100); Matrix PHP; using (new Matlab.NamedLock("")) { Matlab.PutSparseMatrix("H", H.GetMatrixSparse(), 3, 3); Matlab.PutMatrix("P", PBlkOrth.ToMatrix(true)); PHP = Matlab.GetMatrix("P'*H*P"); } double maxerr = PHP.HAbsMax(); HDebug.Exception(Math.Abs(maxerr) < 0.00000001); } } #endregion return(PBlkOrth); }
public static bool UserAssocSort(PHP.Core.Reflection.DTypeDesc caller, [PhpRw] PhpArray array, PhpCallback compare) { if (array == null) { PhpException.ReferenceNull("array"); return false; } if (!PhpArgument.CheckCallback(compare, caller, "compare", 0, false)) return false; // sorts array using callback for comparisons: array.Sort(new ValueComparer(new PhpUserComparer(compare), false)); return true; }
public static object Reduce(PHP.Core.Reflection.DTypeDesc caller, [PhpRw] PhpArray array, PhpCallback function) { return Reduce(caller, array, function, null); }
public static bool Walk(PHP.Core.Reflection.DTypeDesc caller, [PhpRw] PhpHashtable array, PhpCallback function) { return Walk(caller, array, function, null); }
public static bool WalkRecursive(PHP.Core.Reflection.DTypeDesc caller, [PhpRw] PhpHashtable array, PhpCallback callback) { return WalkRecursive(caller, array, callback, null); }
/// <summary> /// Emit the target of instance method invocation. /// </summary> /// <param name="cg"></param> /// <param name="targetExpr"></param> private static void EmitMethodTargetExpr(PHP.Core.CodeGenerator/*!*/cg, Expression/*!*/targetExpr) { // start a new operators chain (as the rest of chain is read) cg.ChainBuilder.Create(); cg.ChainBuilder.Begin(); cg.ChainBuilder.Lengthen(); // for hop over -> // prepare for operator invocation cg.EmitBoxing(targetExpr.Emit(cg)); cg.ChainBuilder.End(); }
/// <summary> /// Emit call of the instance/static method. This defines the call site and call it using given parameters. /// </summary> /// <param name="cg">Current code <see cref="CodeGenerator"/>.</param> /// <param name="returnType">Return type of the method call determined by current access of the method call.</param> /// <param name="targetExpr">The method call instance expression (the target) if it is an instance method call.</param> /// <param name="targetType">The target type if it is a static method call.</param> /// <param name="methodFullName">If known at compile time, the method name. Otherwise <c>null</c>.</param> /// <param name="methodNameExpr">If the <paramref name="methodFullName"/> is null, this will be the expression giving the method name in run time.</param> /// <param name="callSignature">The call signature of the method call.</param> /// <returns>The resulting value type code. This value will be pushed onto the evaluation stack.</returns> public PhpTypeCode EmitMethodCall( PHP.Core.CodeGenerator/*!*/cg, Type returnType, Expression/*!*/targetExpr, DType/*!*/targetType, string methodFullName, Expression methodNameExpr, CallSignature callSignature) { Debug.Assert(methodFullName != null ^ methodNameExpr != null); // bool staticCall = (targetExpr == null); // we are going to emit static method call //bool methodNameIsKnown = (methodFullName != null); //bool classContextIsKnown = (this.classContextPlace != null); // // define the call site: // var delegateType = /*System.Linq.Expressions.Expression.*/delegateBuilder.GetDelegateType( MethodCallDelegateTypeArgs( callSignature, staticCall ? Types.DObject[0] : Types.Object[0], MethodCallDelegateAdditionalArguments(staticCall, methodFullName != null, this.classContextPlace != null), returnType), callSitesCount); // (J) do not create dynamic delegates in dynamic modules, so they can be referenced from non-transient assemblies // var field = DefineCallSite(cg.IL, string.Format("call_{0}", methodFullName ?? "$"), delegateType, (il) => { // <LOAD> Binder.{MethodCall|StaticMethodCall}( methodFullName, genericParamsCount, paramsCount, classContext, <returnType> ) if (methodFullName != null) il.Emit(OpCodes.Ldstr, methodFullName); else il.Emit(OpCodes.Ldnull); il.LdcI4(callSignature.GenericParams.Count); il.LdcI4(callSignature.Parameters.Count); if (this.classContextPlace != null) this.classContextPlace.EmitLoad(il); else il.Emit(OpCodes.Ldsfld, Fields.UnknownTypeDesc.Singleton); il.Emit(OpCodes.Ldtoken, returnType); il.Emit(OpCodes.Call, Methods.GetTypeFromHandle); il.Emit(OpCodes.Call, staticCall ? Methods.Binder.StaticMethodCall : Methods.Binder.MethodCall); }); // // call the CallSite: // // <field>.Target( <field>, <targetExpr|self>, <scriptContext>, <callSignature.EmitLoadOnEvalStack>, <targetType>?, (classContext)?, <methodNameExpr>? ): cg.IL.Emit(OpCodes.Ldsfld, field); cg.IL.Emit(OpCodes.Ldfld, field.FieldType.GetField("Target")); cg.IL.Emit(OpCodes.Ldsfld, field); if (staticCall) cg.EmitLoadSelf(); else EmitMethodTargetExpr(cg, targetExpr); cg.EmitLoadScriptContext(); EmitMethodCallParameters(cg, callSignature); if (staticCall) targetType.EmitLoadTypeDesc(cg, ResolveTypeFlags.UseAutoload | ResolveTypeFlags.ThrowErrors); if (/*!classContextIsKnown*/this.classContextPlace == null) cg.EmitLoadClassContext(); if (/*!methodNameIsKnown*/methodFullName == null) cg.EmitName(methodFullName/*null*/, methodNameExpr, true); cg.MarkTransientSequencePoint(); cg.IL.Emit(OpCodes.Callvirt, delegateType.GetMethod("Invoke")); cg.MarkTransientSequencePoint(); // return PhpTypeCodeEnum.FromType(returnType); }
/// <summary> /// Create and call <see cref="CallSite"/> for getting property. /// </summary> /// <param name="cg"><see cref="CodeGenerator"/>.</param> /// <param name="wantRef">Wheter <see cref="PhpReference"/> is expected as the result.</param> /// <param name="targetExpr">The expression representing the target (object).</param> /// <param name="targetObjectPlace">The place representing the target (<see cref="DObject"/>) iff <paramref name="targetExpr"/> is not provided.</param> /// <param name="targetPlace">The place representing the target (object) iff <paramref name="targetExpr"/> and <paramref name="targetObjectPlace"/> are not provided.</param> /// <param name="targetType">Type of target iff we are getting property statically.</param> /// <param name="fieldName">The name of the field. Can be null if the name is not known at compile time (indirect).</param> /// <param name="fieldNameExpr">The expression used to get field name in run time (iff <paramref name="fieldName"/> is <c>null</c>.</param> /// <param name="issetSemantics">Wheter we are only checking if the property exists. If true, no warnings are thrown during run time.</param> /// <returns>Type code of the value that is pushed onto the top of the evaluation stack.</returns> public PhpTypeCode EmitGetProperty( PHP.Core.CodeGenerator/*!*/cg, bool wantRef, Expression targetExpr, IPlace targetObjectPlace, IPlace targetPlace, DType targetType, string fieldName, Expression fieldNameExpr, bool issetSemantics) { Debug.Assert(fieldName != null ^ fieldNameExpr != null); Debug.Assert(targetExpr != null || targetObjectPlace != null || targetPlace != null || targetType != null); // bool staticCall = (targetExpr == null && targetObjectPlace == null && targetPlace == null); // we are going to access static property bool fieldNameIsKnown = (fieldName != null); bool classContextIsKnown = (this.classContextPlace != null); // // binder flags: // Type returnType = wantRef ? Types.PhpReference[0] : Types.Object[0]; // // define the call site: // // List<Type> additionalArgs = new List<Type>(); if (!classContextIsKnown) additionalArgs.Add(Types.DTypeDesc[0]); if (!fieldNameIsKnown) additionalArgs.Add(Types.String[0]); var delegateTypeArgs = GetPropertyDelegateTypeArgs( staticCall ? Types.DTypeDesc[0] : ((targetObjectPlace != null) ? Types.DObject[0] : Types.Object[0]), // DTypeDesc of static field's declaring type || DObject if field called on DObject known at compile time || otherwise object additionalArgs.ToArray(), returnType); var delegateType = /*System.Linq.Expressions.Expression.*/delegateBuilder.GetDelegateType(delegateTypeArgs, callSitesCount); // (J) do not create dynamic delegates in dynamic modules, so they can be referenced from non-transient assemblies // var field = DefineCallSite(cg.IL, string.Format("get{0}_{1}", wantRef ? "ref" : string.Empty, fieldName ?? "$"), delegateType, (il) => { // <LOAD> Binder.{GetProperty|GetStaticProperty}( fieldName, classContext, issetSemantics, <returnType> ) if (fieldName != null) il.Emit(OpCodes.Ldstr, fieldName); else il.Emit(OpCodes.Ldnull); if (this.classContextPlace != null) this.classContextPlace.EmitLoad(il); else il.Emit(OpCodes.Ldsfld, Fields.UnknownTypeDesc.Singleton); il.LoadBool(issetSemantics); il.Emit(OpCodes.Ldtoken, returnType); il.Emit(OpCodes.Call, Methods.GetTypeFromHandle); il.Emit(OpCodes.Call, staticCall ? Methods.Binder.StaticGetProperty : Methods.Binder.GetProperty); }); // // call the CallSite: // // <field>.Target( <field>, <targetExpr|targetType>, (classContext)?, <methodNameExpr>? ): cg.IL.Emit(OpCodes.Ldsfld, field); cg.IL.Emit(OpCodes.Ldfld, field.FieldType.GetField("Target")); cg.IL.Emit(OpCodes.Ldsfld, field); if (staticCall) targetType.EmitLoadTypeDesc(cg, ResolveTypeFlags.UseAutoload | ResolveTypeFlags.ThrowErrors); else if (targetExpr != null) { cg.ChainBuilder.Lengthen(); // for hop over -> cg.EmitBoxing(targetExpr.Emit(cg)); // prepare for operator invocation } else if (targetObjectPlace != null) targetObjectPlace.EmitLoad(cg.IL); else if (targetPlace != null) targetPlace.EmitLoad(cg.IL); else Debug.Fail(); if (!classContextIsKnown) cg.EmitLoadClassContext(); if (!fieldNameIsKnown) cg.EmitName(fieldName/*null*/, fieldNameExpr, true, PhpTypeCode.String); cg.MarkTransientSequencePoint(); cg.IL.Emit(OpCodes.Callvirt, delegateType.GetMethod("Invoke")); cg.MarkTransientSequencePoint(); // return PhpTypeCodeEnum.FromType(returnType); }
static void Main() { PHP php = new PHP("PHP 프로그래밍 입문", 20130520, "황재호", "김태헌", "한빛아카데미(주)", "김현용", "김이화", "김이화", "여동일"); }
public static PhpReference Unserialize(PHP.Core.Reflection.DTypeDesc caller, PhpBytes bytes) { LibraryConfiguration config = LibraryConfiguration.GetLocal(ScriptContext.CurrentContext); return config.Serialization.DefaultSerializer.Deserialize(bytes, caller); }
public static object SetExceptionHandler(PHP.Core.Reflection.DTypeDesc caller, PhpCallback newHandler) { if (!PhpArgument.CheckCallback(newHandler, caller, "newHandler", 0, false)) return null; PhpCallback old_handler = Configuration.Local.ErrorControl.UserExceptionHandler; // previous handler was defined by user => store it into the stack: if (old_handler != null) { if (OldUserExceptionHandlers == null) { OldUserExceptionHandlers = new Stack(5); RequestContext.RequestEnd += new Action(ClearOldUserHandlers); } OldUserExceptionHandlers.Push(old_handler); } // sets the current handler: Configuration.Local.ErrorControl.UserExceptionHandler = newHandler; // returns the previous handler: return (old_handler != null) ? old_handler.ToPhpRepresentation() : null; }
/// <summary> /// Visits an entyr of array which <see cref="Walk"/> or <see cref="WalkRecursive"/> is walking through. /// </summary> private static void VisitEntryOnWalk(PHP.Core.Reflection.DTypeDesc caller, KeyValuePair<IntStringKey, object> entry, IDictionary<IntStringKey, object> array, PhpCallback callback, object[] args) { PhpReference ref_item = entry.Value as PhpReference; // fills arguments for the callback: ((PhpReference)args[0]).Value = (ref_item != null) ? ref_item.Value : entry.Value; args[1] = entry.Key.Object; // invoke callback: Core.Convert.ObjectToBoolean(callback.Invoke(caller, args)); // loads a new value from a reference: if (ref_item != null) { ref_item.Value = ((PhpReference)args[0]).Value; } else { array[entry.Key] = ((PhpReference)args[0]).Value; } }
public PDO(ScriptContext/*!*/context, PHP.Core.Reflection.DTypeDesc caller) : base(context, caller) { }
public static PhpArray Filter(PHP.Core.Reflection.DTypeDesc caller, PhpArray array, PhpCallback callback) { if (callback == null) { PhpException.ArgumentNull("callback"); return null; } if (array == null) { PhpException.ArgumentNull("array"); return null; } PhpArray result = new PhpArray(); object[] args = new object[1]; foreach (KeyValuePair<IntStringKey, object> entry in array) { // no deep copying needed because it is done so in callback: args[0] = entry.Value; // adds entry to the resulting array if callback returns true: if (Core.Convert.ObjectToBoolean(callback.Invoke(caller, args))) { result.Add(entry.Key, entry.Value); } } // values should be inplace deeply copied: result.InplaceCopyOnReturn = true; return result; }
public static bool UserKeySort(PHP.Core.Reflection.DTypeDesc caller, [PhpRw] PhpArray array, PhpCallback compare) { if (array == null) { PhpException.ReferenceNull("array"); return false; } if (!PhpArgument.CheckCallback(compare, caller, "compare", 0, false)) return false; array.Sort(new KeyComparer(new PhpUserComparer(compare), false)); return true; }
/// <summary> /// Gets a string which is used as a fill in the code to be parsed in order to maintain /// correct token positioning. /// </summary> /// <param name="args">A position of string literal holding source code for lambda function arguments.</param> /// <param name="body">A position of string literal holding source code for the body.</param> /// <returns>A string containing spaces and end-of-line characters '\n'.</returns> private static string GetInlinedLambdaCodeFill(PHP.Core.Parsers.Position args, PHP.Core.Parsers.Position body) { int delta_lines = body.FirstLine - args.LastLine; if (delta_lines == 0) { // ....args.......'_____,_______________'.......body..... // ...............)_________fill________{................ return new String(' ', body.FirstColumn - args.LastColumn - 1); } else { // source: // .....args.....'_____\r\n // _________,_____\r\n // ____________'......body..... // code to parse: // .....args....'\n // \n // ____fill____{.....body...... // the same number of lines as it is in the source file + leading columns: return new System.Text.StringBuilder(delta_lines + body.FirstColumn). Append('\n', delta_lines).Append(' ', body.FirstColumn).ToString(); } }
public static object Reduce(PHP.Core.Reflection.DTypeDesc caller, [PhpRw] PhpArray array, PhpCallback function, [PhpDeepCopy] object initialValue) { if (array == null) { PhpException.ReferenceNull("array"); return null; } if (!PhpArgument.CheckCallback(function, caller, "function", 0, false)) return null; if (array.Count == 0) return initialValue; object[] args = new object[] { initialValue, null }; PhpReference holder = new PhpReference(); foreach (KeyValuePair<IntStringKey, object> entry in array) { object item = entry.Value; PhpReference ref_item = item as PhpReference; // array item is a reference: if (ref_item != null) { args[1] = item; args[0] = function.Invoke(args); } else { // array item is not a reference: holder.Value = item; args[1] = holder; args[0] = function.Invoke(args); // updates an item if it has been changed: if (item != holder.Value) array[entry.Key] = holder.Value; } } // dereferences the last returned value: return PhpVariable.Dereference(args[0]); }
/// <summary> /// Sets attributes of generated override/implement/export stub parameters. /// </summary> /// <param name="stub">The stub constructor builder. /// </param> /// <param name="formalParams">Formal parameters of the implementing PHP method.</param> /// <param name="templateParams">Parameters of the overload being overriden/implemented/exported.</param> public static void DefineStubParameters(ConstructorBuilder/*!*/ stub, PHP.Core.AST.FormalParam[] formalParams, ParameterInfo[]/*!*/ templateParams) { for (int i = 0; i < templateParams.Length; i++) { string name; // take the overriding parameter name if available if (formalParams != null && i < formalParams.Length) name = formalParams[i].Name.ToString(); else name = templateParams[i].Name; stub.DefineParameter(i + 1, templateParams[i].Attributes, name); } }
public static bool Walk(PHP.Core.Reflection.DTypeDesc caller, [PhpRw] PhpHashtable array, PhpCallback callback, object data) { object[] args = PrepareWalk(array, callback, data); if (args == null) return false; foreach (KeyValuePair<IntStringKey, object> entry in array) { VisitEntryOnWalk(caller, entry, array, callback, args); } return true; }
public PHP.Core.AST.Literal CreateLiteral(PHP.Core.Parsers.Position position) { if (IsBinary) return new PHP.Core.AST.BinaryStringLiteral(position, new PhpBytes(BinaryBuilder.ToArray())); else return new PHP.Core.AST.StringLiteral(position, UnicodeBuilder.ToString()); }
public static bool WalkRecursive(PHP.Core.Reflection.DTypeDesc caller, [PhpRw] PhpHashtable array, PhpCallback callback, object data) { object[] args = PrepareWalk(array, callback, data); if (args == null) return false; using (PhpHashtable.RecursiveEnumerator iterator = array.GetRecursiveEnumerator(true,false)) { while (iterator.MoveNext()) { // visits the item unless it is an array or a reference to an array: PhpReference ref_value = iterator.Current.Value as PhpReference; if (!(iterator.Current.Value is PhpHashtable || (ref_value != null && ref_value.Value is PhpHashtable))) VisitEntryOnWalk(caller, iterator.Current, iterator.CurrentTable, callback, args); } } return true; }
public static bool IsCallable(PHP.Core.Reflection.DTypeDesc caller, object variable) { return IsCallable(caller, variable, false); }
public static PhpArray Filter(PHP.Core.Reflection.DTypeDesc _, PhpArray array) { var _result = new PhpArray(); using (var enumerator = array.GetFastEnumerator()) while (enumerator.MoveNext()) if (Core.Convert.ObjectToBoolean(enumerator.CurrentValue)) _result.Add(enumerator.CurrentKey, enumerator.CurrentValue); return _result; }
public static bool IsCallable(PHP.Core.Reflection.DTypeDesc caller, object variable, bool syntaxOnly) { return Operators.IsCallable(variable, caller, syntaxOnly); }
public static PhpArray Map(PHP.Core.Reflection.DTypeDesc caller, PhpCallback map, [PhpRw] params PhpArray[] arrays) { if (!PhpArgument.CheckCallback(map, caller, "map", 0, true)) return null; if (arrays == null || arrays.Length == 0) { PhpException.InvalidArgument("arrays", LibResources.GetString("arg:null_or_emtpy")); return null; } // if callback has not been specified uses the default one: if (map == null) map = new PhpCallback(new RoutineDelegate(MapIdentity), ScriptContext.CurrentContext); int count = arrays.Length; bool preserve_keys = count == 1; PhpReference[] args = new PhpReference[count]; IEnumerator<KeyValuePair<IntStringKey, object>>[] iterators = new IEnumerator<KeyValuePair<IntStringKey, object>>[count]; PhpArray result; // initializes iterators and args array, computes length of the longest array: int max_count = 0; for (int i = 0; i < arrays.Length; i++) { var array = arrays[i]; if (array == null) { PhpException.Throw(PhpError.Warning, LibResources.GetString("argument_not_array", i + 2));// +2 (first arg is callback) return null; } args[i] = new PhpReference(); iterators[i] = array.GetEnumerator(); if (array.Count > max_count) max_count = array.Count; } // keys are preserved in a case of a single array and re-indexed otherwise: if (preserve_keys) result = new PhpArray(arrays[0].IntegerCount, arrays[0].StringCount); else result = new PhpArray(max_count, 0); for (; ; ) { // fills args[] with items from arrays: for (int i = 0; i < arrays.Length; i++) { if (iterators[i] != null) { // an element is available: if (iterators[i].MoveNext()) { // note: deep copy is not necessary since a function copies its arguments if needed: object value = iterators[i].Current.Value; PhpReference valueref = (value != null) ? value as PhpReference : null; args[i].Value = (valueref != null) ? valueref.value : value; //args[i].Value = iterators[i].Current.Value; // TODO: throws if the current Value is PhpReference } else { // the i-th iterator has stopped: count--; iterators[i] = null; args[i].Value = null; } } } if (count == 0) break; // invokes callback: object return_value = map.Invoke(args); // return value is not deeply copied: if (preserve_keys) result.Add(iterators[0].Current.Key, return_value); else result.Add(return_value); // loads new values (callback may modify some by ref arguments): for (int i = 0; i < arrays.Length; i++) { if (iterators[i] != null) { object item = iterators[i].Current.Value; PhpReference ref_item = item as PhpReference; if (ref_item != null) { ref_item.Value = args[i].Value; } else { arrays[i][iterators[i].Current.Key] = args[i].Value; } } } } return result; }
public static bool IsCallable(PHP.Core.Reflection.DTypeDesc caller, object variable, bool syntaxOnly, out string callableName) { PhpCallback callback = PHP.Core.Convert.ObjectToCallback(variable, true); if (callback == null || callback.IsInvalid) { callableName = PHP.Core.Convert.ObjectToString(variable); return false; } callableName = ((IPhpConvertible)callback).ToString(); return (syntaxOnly ? true : callback.Bind(true, caller, null)); }
public static PHP.Core.Compiler.AST.FunctionCallEvaluateInfo CreateFunction_Analyze( Analyzer analyzer, PHP.Core.AST.CallSignature callSignature, string args, string body) { if (analyzer.IsInsideIncompleteClass()) return null; // in this case, the DirectFnCall will not be Emitted. Therefore the lambda routine will not be declared and compilation will fail when emitting not fully declared lambda FunctionDecl. // has to be a valid identifier: // actually this name is never used then string function_name = "__" + Guid.NewGuid().ToString().Replace('-', '_'); //DynamicCode.GenerateLambdaName(args, body); string prefix1, prefix2; DynamicCode.GetLamdaFunctionCodePrefixes(function_name, args, out prefix1, out prefix2); PHP.Core.Parsers.Position pos_args = callSignature.Parameters[0].Position; PHP.Core.Parsers.Position pos_body = callSignature.Parameters[1].Position; // function __XXXXXX(<args>){<fill><body>} string fill = GetInlinedLambdaCodeFill(pos_args, pos_body); string code = String.Concat(prefix2, fill, body, "}"); // the position of the first character of the parsed code: // (note that escaped characters distort position a little bit, which cannot be eliminated so easily) PHP.Core.Parsers.Position pos = PHP.Core.Parsers.Position.Initial; pos.FirstOffset = pos_args.FirstOffset - prefix1.Length + 1; pos.FirstColumn = pos_args.FirstColumn - prefix1.Length + 1; pos.FirstLine = pos_args.FirstLine; // parses function source code: var counter = new PHP.Core.Parsers.Parser.ReductionsCounter(); var ast = analyzer.BuildAst(pos, code, counter); if (ast == null || ast.Statements == null) return null; // the function cannot be parsed Debug.Assert(counter.FunctionCount == 1); var decl_node = (PHP.Core.AST.FunctionDecl)ast.Statements[0]; // adds declaration to the end of the global code statement list: analyzer.AddLambdaFcnDeclaration(decl_node); // return new PHP.Core.Compiler.AST.FunctionCallEvaluateInfo() { //.inlined = InlinedFunction.CreateFunction; emitDeclareLamdaFunction = true, // modify declaration: newRoutine = Core.Compiler.AST.FunctionDeclCompilerHelper.ConvertToLambda(decl_node, analyzer), }; }
public static PhpBytes Serialize(PHP.Core.Reflection.DTypeDesc caller, object variable) { LibraryConfiguration config = LibraryConfiguration.GetLocal(ScriptContext.CurrentContext); return config.Serialization.DefaultSerializer.Serialize(variable, caller); }