public Result Execute(ICommunicationObject client, string service, System.Reflection.MethodBase method, params object[] data) { RemoteInvokeArgs info = new RemoteInvokeArgs(); info.Interface = service; info.Method = method.Name; info.Parameters = data; info.CommunicationObject = client; info.ParameterInfos = method.GetParameters(); foreach (System.Reflection.ParameterInfo pi in method.GetParameters()) { info.ParameterTypes.Add(pi.ParameterType.Name); } return(Handler.Execute(info)); }
private void GetOneStackTraceText(StackTrace stackTrace, StringBuilder builder) { builder.AppendLine("<------------------------------StackTrace One Begin------------------------------>"); StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames) // write call stack method names foreach (StackFrame stackFrame in stackFrames) { System.Reflection.MethodBase method = stackFrame.GetMethod(); builder.AppendLine("<---Method Begin--->"); builder.AppendLine("File Name: " + stackFrame.GetFileName()); builder.AppendLine("Line Number: " + stackFrame.GetFileLineNumber()); builder.AppendLine("Column Number: " + stackFrame.GetFileColumnNumber()); builder.AppendLine("Name: " + method.Name); builder.AppendLine("Class: " + method.DeclaringType.Name); System.Reflection.ParameterInfo[] param = method.GetParameters(); builder.AppendLine("Params Count: " + param.Length); int i = 1; foreach (System.Reflection.ParameterInfo p in param) { builder.AppendLine("Param " + i + ":" + p.ParameterType.Name); i++; } builder.AppendLine("<---Method End--->"); } builder.AppendLine("<------------------------------StackTrace One End------------------------------>"); }
private static string Serialize(System.Reflection.MethodBase methodBase) { StringBuilder st = new StringBuilder(); st.Append(Serialize(methodBase.DeclaringType)); st.Append(" "); st.Append(methodBase.Name); st.Append(SerializeGeneric(methodBase.GetGenericArguments())); st.Append("("); bool t = false; foreach (var item in methodBase.GetParameters()) { if (t) { st.Append(", "); } st.Append(Serialize(item.ParameterType)); t = true; } st.Append(")"); return(st.ToString()); }
public override void CompileTimeInitialize(System.Reflection.MethodBase method, AspectInfo aspectInfo) { if (this.cacheName == null) { this.cacheName = method.DeclaringType.FullName; } this.className = method.DeclaringType.FullName; this.methodName = method.Name; var parameters = method.GetParameters(); this.parameterTypeNames = parameters.Select(p => p.ParameterType.FullName).ToArray(); var indexes = new List <int>(); for (int cnt = 0; cnt < parameters.Length; cnt++) { var doNotIncludeInCacheKey = parameters[cnt].CustomAttributes .Any(a => a.GetType() == typeof(DoNotIncludeInCacheKeyAttribute)); if (doNotIncludeInCacheKey) { indexes.Add(cnt); } } this.indexesNotToCache = indexes.ToArray(); }
public MethodParamList(ICLRSharp_Environment env, System.Reflection.MethodBase method) { foreach (var p in method.GetParameters()) { this.Add(env.GetType(p.ParameterType)); } }
public static void Log(StackTrace stack, string name, string value) { if (!LogTypes.ContainsKey(name)) { return; } System.Reflection.MethodBase method = stack.GetFrame(1).GetMethod(); StringBuilder parameters = new StringBuilder(); System.Reflection.ParameterInfo[] param = method.GetParameters(); foreach (System.Reflection.ParameterInfo i in param) { parameters.AppendFormat("{0} {1}, ", i.ParameterType, i.Name); } if (parameters.Length > 2) { parameters.Remove(parameters.Length - 2, 2); } string outline = String.Format("{0}.{1}({2})> {3}", method.DeclaringType, method.Name, parameters, value); LogData.Add(name, outline); Console.WriteLine("{0}: {1}", name, outline ); }
private string GetParameters(System.Reflection.MethodBase methodBase) { StringBuilder builder = new StringBuilder(1); foreach (var item in methodBase.GetParameters()) { builder.Append(item.ParameterType.Name); } return(builder.ToString()); }
System.Runtime.Remoting.Messaging.IMessage DoInvoke(System.Runtime.Remoting.Messaging.IMessage inputMessage) { var inmsg = (System.Runtime.Remoting.Messaging.IMethodCallMessage)inputMessage; var od = channel.Contract.Operations.FirstOrDefault(o => inmsg.MethodBase.Equals(o.SyncMethod) || inmsg.MethodBase.Equals(o.BeginMethod) || inmsg.MethodBase.Equals(o.EndMethod)); if (od == null) { var ret = inmsg.MethodBase.Invoke(channel, inmsg.InArgs); return(new System.Runtime.Remoting.Messaging.ReturnMessage(ret, null, 0, null, inmsg)); } else { object[] pl; System.Reflection.MethodBase method = null; List <object> outArgs = null; object ret; if (inmsg.MethodBase.Equals(od.SyncMethod)) { pl = new object[inmsg.MethodBase.GetParameters().Length]; Array.Copy(inmsg.Args, pl, inmsg.ArgCount); ret = channel.Process(inmsg.MethodBase, od.Name, pl, System.ServiceModel.OperationContext.Current); method = od.SyncMethod; } else if (inmsg.MethodBase.Equals(od.BeginMethod)) { pl = new object[inmsg.ArgCount - 2]; Array.Copy(inmsg.Args, 0, pl, 0, pl.Length); ret = channel.BeginProcess(inmsg.MethodBase, od.Name, pl, (AsyncCallback)inmsg.Args[inmsg.ArgCount - 2], inmsg.Args[inmsg.ArgCount - 1]); saved_params[ret] = pl; wait.Set(); } else { var result = (IAsyncResult)inmsg.InArgs[0]; wait.WaitOne(); pl = saved_params[result]; wait.Reset(); saved_params.Remove(result); ret = channel.EndProcess(inmsg.MethodBase, od.Name, pl, result); method = od.BeginMethod; } if (method != null && method.GetParameters().Any(pi => pi.IsOut || pi.ParameterType.IsByRef)) { return(new System.Runtime.Remoting.Messaging.ReturnMessage(ret, pl, pl.Length, null, inmsg)); } else { return(new System.Runtime.Remoting.Messaging.ReturnMessage(ret, outArgs != null ? outArgs.ToArray() : null, outArgs != null ? outArgs.Count : 0, null, inmsg)); } } }
public override void CompileTimeInitialize(System.Reflection.MethodBase method, AspectInfo aspectInfo) { // ReSharper disable once PossibleNullReferenceException this.className = method.DeclaringType.FullName; if (string.IsNullOrEmpty(this.logName)) { this.logName = this.className; } var parameterTypes = string.Join(", ", method.GetParameters().Select(p => p.ParameterType.FullName).ToArray()); this.fullMethodName = string.Concat(className, '.', method.Name, '(', parameterTypes, ')'); }
public MethodParamList(ICLRSharp_Environment env, System.Reflection.MethodBase method) { { var __array5 = method.GetParameters(); var __arrayLength5 = __array5.Length; for (int __i5 = 0; __i5 < __arrayLength5; ++__i5) { var p = __array5[__i5]; { this.Add(env.GetType(p.ParameterType)); } } } }
internal MethodBaseInfo(System.Reflection.MethodBase methodInfo, TypeInfoProvider typeInfoProvider) : base(methodInfo, typeInfoProvider) { var genericArguments = methodInfo.IsGenericMethod ? methodInfo.GetGenericArguments() : null; GenericArgumentTypes = genericArguments is null || genericArguments.Length == 0 ? null : genericArguments.Select(x => typeInfoProvider.Get(x, false, false)).ToList(); var parameters = methodInfo.GetParameters(); ParameterTypes = parameters.Length == 0 ? null : parameters.Select(x => typeInfoProvider.Get(x.ParameterType, false, false)).ToList(); }
protected MethodBaseInfo(System.Reflection.MethodBase method, TypeInfoProvider typeInfoProvider) : base(method, typeInfoProvider) { var genericArguments = method.CheckNotNull(nameof(method)).IsGenericMethod ? method.GetGenericArguments() : null; GenericArgumentTypes = genericArguments .AsNullIfEmpty()? .Select(x => typeInfoProvider.GetTypeInfo(x, false, false)) .ToList(); ParameterTypes = method .GetParameters() .AsNullIfEmpty()? .Select(x => typeInfoProvider.GetTypeInfo(x.ParameterType, false, false)) .ToList(); }
/// <summary> /// Prints a set of method parameters to a string. /// </summary> /// <param name="method"></param> /// <returns></returns> private static string GetMethodParamsAsString(System.Reflection.MethodBase method) { StringBuilder sb = new StringBuilder(); var mparams = method.GetParameters(); if (mparams != null) { foreach (var mp in mparams) { sb.Append(mp.ToString() + ","); } } return(sb.ToString().TrimEnd(',')); }
/// <summary> /// Formats the full stack trace. Removes calls from logger classes which would just bloat the logs /// </summary> /// <param name="stack"Stack trace info></param> /// <returns></returns> protected virtual string FormatStackTrace(StackTrace stack) { string formattedStack = "\n\n--- STACK TRACE ---"; #if !UNITY_EDITOR int startingIndex = GetIndexForFirstValidFrame(stack); if (startingIndex >= 0) { StackFrame[] frames = stack.GetFrames(); StackFrame frame; for (int frameIndex = startingIndex; frameIndex < frames.Length; ++frameIndex) { frame = frames[frameIndex]; System.Reflection.MethodBase method = frame.GetMethod(); formattedStack += "\n" + method.DeclaringType.FullName + ":" + method.Name + "("; System.Reflection.ParameterInfo[] parameters = method.GetParameters(); if (parameters != null) { System.Reflection.ParameterInfo parameter; for (int paramIndex = 0; paramIndex < parameters.Length; ++paramIndex) { parameter = parameters[paramIndex]; if (paramIndex != 0) { formattedStack += ", "; } formattedStack += parameter.ParameterType.Name; } } string fileName = frame.GetFileName(); int assetIndex = fileName.LastIndexOf("Assets"); formattedStack += ") (at " + fileName.Substring(assetIndex) + ":" + frame.GetFileLineNumber() + ")"; } formattedStack += "\n--- STACK TRACE END ---\n\n"; } #endif return(formattedStack); }
private string[] GetMethodParameterNames(System.Reflection.MethodBase methodBase) { ArrayList methodParameterNames = new ArrayList(); try { System.Reflection.ParameterInfo[] methodBaseGetParameters = methodBase.GetParameters(); int methodBaseGetParametersCount = methodBaseGetParameters.GetUpperBound(0); for (int i = 0; i <= methodBaseGetParametersCount; i++) { methodParameterNames.Add(methodBaseGetParameters[i].ParameterType + " " + methodBaseGetParameters[i].Name); } } catch (Exception ex) { LogLog.Error(declaringType, "An exception ocurred while retreiving method parameters.", ex); } return((string[])methodParameterNames.ToArray(typeof(string))); }
internal MethodBaseInfo(System.Reflection.MethodBase methodInfo, TypeInfoProvider typeInfoProvider) : base(methodInfo, typeInfoProvider) { var bindingFlags = methodInfo.IsStatic ? BindingFlags.Static : BindingFlags.Instance; bindingFlags |= methodInfo.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic; BindingFlags = bindingFlags; var genericArguments = methodInfo.IsGenericMethod ? methodInfo.GetGenericArguments() : null; GenericArgumentTypes = genericArguments is null || genericArguments.Length == 0 ? null : genericArguments.Select(x => typeInfoProvider.Get(x, false, false)).ToList(); var parameters = methodInfo.GetParameters(); ParameterTypes = parameters.Length == 0 ? null : parameters.Select(x => typeInfoProvider.Get(x.ParameterType, false, false)).ToList(); }
/// <summary> /// Generates the signature string for the specified method. /// </summary> /// <param name="aMethod">The method to generate the signature of.</param> /// <returns>The signature string.</returns> private static string GetMethodSignature(System.Reflection.MethodBase aMethod) { string[] paramTypes = aMethod.GetParameters().Select(x => x.ParameterType).Select(x => x.FullName).ToArray(); string returnType = ""; string declaringType = ""; string methodName = ""; if (aMethod.IsConstructor || aMethod is System.Reflection.ConstructorInfo) { returnType = typeof(void).FullName; declaringType = aMethod.DeclaringType.FullName; methodName = aMethod.Name; } else { returnType = ((System.Reflection.MethodInfo)aMethod).ReturnType.FullName; declaringType = aMethod.DeclaringType.FullName; methodName = aMethod.Name; } return(GetMethodSignature(returnType, declaringType, methodName, paramTypes)); }
private static System.Xml.XmlNode MakeMethodNode(System.Reflection.MethodBase memberInfo, System.Xml.XmlDocument ownerdoc, bool SkipSpecialName) { System.Xml.XmlNode nodeMember; if (!memberInfo.IsPrivate && !(memberInfo.IsSpecialName && SkipSpecialName)) { nodeMember = Utility.xmlHelpers.NewElement(ownerdoc, memberInfo.MemberType.ToString(), memberInfo.Name); nodeMember.Attributes.Append(Utility.xmlHelpers.NewBoolAttribute(ownerdoc, "MustInherit", memberInfo.IsAbstract)); nodeMember.Attributes.Append(Utility.xmlHelpers.NewBoolAttribute(ownerdoc, "NotOverridable", memberInfo.IsFinal)); nodeMember.Attributes.Append(Utility.xmlHelpers.NewBoolAttribute(ownerdoc, "ShadowOverload", memberInfo.IsHideBySig)); nodeMember.Attributes.Append(Utility.xmlHelpers.NewAttribute(ownerdoc, "Scope", GetScope(memberInfo.IsPrivate, memberInfo.IsPublic, memberInfo.IsAssembly, memberInfo.IsFamily, memberInfo.IsFamilyOrAssembly))); nodeMember.Attributes.Append(Utility.xmlHelpers.NewBoolAttribute(ownerdoc, "Shared", memberInfo.IsStatic)); nodeMember.Attributes.Append(Utility.xmlHelpers.NewBoolAttribute(ownerdoc, "Overridable", memberInfo.IsVirtual)); if (memberInfo is System.Reflection.MethodInfo) { nodeMember.Attributes.Append(Utility.xmlHelpers.NewAttribute(ownerdoc, "ReturnType", ((System.Reflection.MethodInfo)memberInfo).ReturnType.ToString())); } MakeParameterNodes(nodeMember, memberInfo.GetParameters()); return(nodeMember); } return(null); }
public static Mono.Cecil.MethodDefinition ConvertToMonoCecilMethodDefinition(System.Reflection.MethodBase mi) { // Get assembly name which encloses code for kernel. String kernel_assembly_file_name = mi.DeclaringType.Assembly.Location; // Get directory containing the assembly. String full_path = Path.GetFullPath(kernel_assembly_file_name); full_path = Path.GetDirectoryName(full_path); String kernel_full_name = null; // Get full name of kernel, including normalization because they cannot be compared directly with Mono.Cecil names. if (mi as System.Reflection.MethodInfo != null) { System.Reflection.MethodInfo mik = mi as System.Reflection.MethodInfo; kernel_full_name = string.Format("{0} {1}.{2}({3})", mik.ReturnType.FullName, Campy.Utils.Utility.RemoveGenericParameters(mi.ReflectedType), mi.Name, string.Join(",", mi.GetParameters().Select(o => string.Format("{0}", o.ParameterType)).ToArray())); } else { kernel_full_name = string.Format("{0}.{1}({2})", Campy.Utils.Utility.RemoveGenericParameters(mi.ReflectedType), mi.Name, string.Join(",", mi.GetParameters().Select(o => string.Format("{0}", o.ParameterType)).ToArray())); } kernel_full_name = Campy.Utils.Utility.NormalizeSystemReflectionName(kernel_full_name); // Decompile entire module. Mono.Cecil.ModuleDefinition md = Mono.Cecil.ModuleDefinition.ReadModule(kernel_assembly_file_name); // Examine all types, and all methods of types in order to find the lambda in Mono.Cecil. List <Type> types = new List <Type>(); StackQueue <Mono.Cecil.TypeDefinition> type_definitions = new StackQueue <Mono.Cecil.TypeDefinition>(); StackQueue <Mono.Cecil.TypeDefinition> type_definitions_closure = new StackQueue <Mono.Cecil.TypeDefinition>(); foreach (Mono.Cecil.TypeDefinition td in md.Types) { type_definitions.Push(td); } while (type_definitions.Count > 0) { Mono.Cecil.TypeDefinition ty = type_definitions.Pop(); type_definitions_closure.Push(ty); foreach (Mono.Cecil.TypeDefinition ntd in ty.NestedTypes) { type_definitions.Push(ntd); } } foreach (Mono.Cecil.TypeDefinition td in type_definitions_closure) { foreach (Mono.Cecil.MethodDefinition md2 in td.Methods) { String md2_name = Campy.Utils.Utility.NormalizeMonoCecilName(md2.FullName); if (md2_name.Contains(kernel_full_name)) { return(md2); } } } return(null); }
/// <summary> /// Receives a MethodInfo as a parameter and returns the number of parameters for /// that method. Instead of calling this method by passing the MethodInfo you can also use /// System.Reflection.MethodBase.GetCurrentMethod().GetParameters().Length; /// right from your method to get the parameter count. /// </summary> /// <example> /// private string GetStatus(string tcCustomer) /// { /// //Gets the number of parameters for this method. In this case 1 /// int lnPCount = VFPToolkit.common.PCount(System.Reflection.MethodBase.GetCurrentMethod()); /// } /// </example> /// <param name="ms"></param> /// <returns></returns> public static int PCount(System.Reflection.MethodBase mb) { return(mb.GetParameters().Length); }
static string GetFunctionHeader(int frameOffset = 0, bool fileInfo = false) { if (frameOffset <= -BaseFunctionHeader) { frameOffset = -BaseFunctionHeader; } //get stacktrace info StackTrace stackTrace = new StackTrace(true); StackFrame stackFrame = stackTrace.GetFrame(BaseFunctionHeader + frameOffset); System.Reflection.MethodBase method = stackFrame.GetMethod(); Type classType = method.ReflectedType; string class_name = classType.Name; bool isIEnumerator = false; //we're in a coroutine, get a better set of info if (class_name.Contains(">c__Iterator")) { isIEnumerator = true; classType = method.ReflectedType.DeclaringType; class_name = classType.Name; } //build parameters string string parameters_name = ""; if (DevLog.Settings.showMethodParameters) { System.Reflection.ParameterInfo[] parameters = method.GetParameters(); bool add_comma = false; foreach (System.Reflection.ParameterInfo parameter in parameters) { if (add_comma) { parameters_name += ", "; } parameters_name += Dev.Colorize(parameter.ParameterType.Name, _param_color); parameters_name += " "; parameters_name += Dev.Colorize(parameter.Name, _log_color); add_comma = true; } } //build function header string function_name = ""; if (isIEnumerator) { string realMethodName = method.ReflectedType.Name.Substring(method.ReflectedType.Name.IndexOf('<') + 1, method.ReflectedType.Name.IndexOf('>') - 1); function_name = "IEnumerator:" + realMethodName; } else { function_name = method.Name + "(" + parameters_name + ")"; } //string file = stackFrame.GetFileName().Remove(0, Application.dataPath.Length); string file = System.IO.Path.GetFileName(stackFrame.GetFileName()); int line = stackFrame.GetFileLineNumber(); string fileLineHeader = ""; if (fileInfo) { fileLineHeader = file + "(" + line + "):"; } if (DevLog.Settings.showClassName) { return(fileLineHeader + class_name + "." + function_name + " "); } else { return(fileLineHeader + function_name + " "); } }
protected CILMethodBaseImpl( CILReflectionContextImpl ctx, Int32 anID, System.Reflection.MethodBase method ) : base(ctx, anID, (method is System.Reflection.ConstructorInfo) ? CILElementKind.Constructor : CILElementKind.Method, () => new CustomAttributeDataEventArgs(ctx, method)) { ArgumentValidator.ValidateNotNull("Method", method); if (method.DeclaringType #if WINDOWS_PHONE_APP .GetTypeInfo() #endif .IsGenericType&& !method.DeclaringType #if WINDOWS_PHONE_APP .GetTypeInfo() #endif .IsGenericTypeDefinition) { throw new ArgumentException("This constructor may be used only on methods declared in genericless types or generic type definitions."); } if (method is System.Reflection.MethodInfo && method.GetGenericArguments().Any() && !method.IsGenericMethodDefinition) { throw new ArgumentException("This constructor may be used only on genericless methods or generic method definitions."); } InitFields( ref this.callingConvention, ref this.methodAttributes, ref this.methodKind, ref this.declaringType, ref this.parameters, ref this.il, ref this.methodImplementationAttributes, ref this.securityInfo, new SettableValueForEnums <CallingConventions>((CallingConventions)method.CallingConvention), new SettableValueForEnums <MethodAttributes>((MethodAttributes)method.Attributes), this.cilKind == CILElementKind.Constructor ? MethodKind.Constructor : MethodKind.Method, () => (CILType)ctx.Cache.GetOrAdd(method.DeclaringType), () => ctx.CollectionsFactory.NewListProxy <CILParameter>(method.GetParameters().Select(param => ctx.Cache.GetOrAdd(param)).ToList()), () => { MethodIL result; if (ctx.Cache.ResolveMethodBaseID(this.id).HasILMethodBody()) { var args = new MethodBodyLoadArgs(method); ctx.LaunchMethodBodyLoadEvent(args); result = new CILAssemblyManipulator.Implementation.Physical.MethodILImpl(this.DeclaringType.Module, args); } else { result = null; } return(result); }, new SettableLazy <MethodImplAttributes>(() => { var args = new MethodImplAttributesEventArgs(method); ctx.LaunchMethodImplAttributesEvent(args); return(args.MethodImplementationAttributes); }), new Lazy <DictionaryWithRoles <SecurityAction, ListProxy <SecurityInformation>, ListProxyQuery <SecurityInformation>, ListQuery <SecurityInformation> > >(this.SecurityInfoFromAttributes, LazyThreadSafetyMode.ExecutionAndPublication), true ); }
static public void CustomAssert(bool condition, string assertString, bool pauseOnFail = false) { if (!condition) { System.Text.StringBuilder message = new System.Text.StringBuilder(); System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true); System.Diagnostics.StackFrame[] stackFrames = stackTrace.GetFrames(); int line = 0; string file = ""; int col = 0; bool foundStart = false; //message.Append("<color=white>"); message.Append(assertString); //message.Append("</color>"); message.Append("\n"); for (int i = 0; i < stackFrames.Length; i++) { System.Reflection.MethodBase mb = stackFrames[i].GetMethod(); if (!foundStart && mb.DeclaringType != typeof(PrintSystem)) { file = formatFileName(stackFrames[i].GetFileName()); line = stackFrames[i].GetFileLineNumber(); col = stackFrames[i].GetFileColumnNumber(); foundStart = true; } if (foundStart) { //message.Append(mb.DeclaringType.FullName); message.Append(mb.DeclaringType.Namespace); message.Append("."); message.Append(mb.DeclaringType.Name); message.Append(":"); message.Append(mb.Name); message.Append("("); if (showParameters) { System.Reflection.ParameterInfo[] paramters = mb.GetParameters(); for (int k = 0; k < paramters.Length; k++) { message.Append(paramters[k].ParameterType.Name); if (k + 1 < paramters.Length) { message.Append(", "); } } } message.Append(")"); message.Append(" (at "); message.Append(formatFileName(stackFrames[i].GetFileName())); message.Append(":"); message.Append(stackFrames[i].GetFileLineNumber()); message.Append(")"); message.Append("\n"); } } unityLog = typeof(UnityEngine.Debug).GetMethod("LogPlayerBuildError", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); unityLog.Invoke(null, new object[] { message.ToString(), file, line, col }); if (pauseOnFail) { Debug.Break(); } } }
/// <summary> /// Emits the arguments set. /// </summary> private void EmitArguments(ILGenerator generator, OptimizationInfo optimizationInfo) { // Get the args: IList <Expression> arguments = null; Expression argumentsOperand = null; if (OperandCount > 1) { argumentsOperand = this.GetRawOperand(1); ListExpression argList = argumentsOperand as ListExpression; if (argList != null) { // Multiple parameters were recieved. arguments = argList.Items; // Set the operand to null so it doesn't try to emit it as a single arg: argumentsOperand = null; } } int paraCount = 0; int parameterOffset = 0; bool staticMethod = false; System.Reflection.ParameterInfo[] paraSet = null; IList <ArgVariable> argsSet = null; if (UserDefined == null) { // - Is the first arg ScriptEngine? // - Does it have thisObj / does it want an instance object? paraSet = ResolvedMethod.GetParameters(); paraCount = paraSet.Length; staticMethod = ResolvedMethod.IsStatic || ResolvedMethod.IsConstructor; if (paraSet.Length > 0) { if (paraSet[0].ParameterType == typeof(ScriptEngine)) { // Emit an engine reference now: EmitHelpers.LoadEngine(generator); parameterOffset++; } if (paraSet.Length > parameterOffset && paraSet[parameterOffset].Name == "thisObj") { // It's acting like an instance method. parameterOffset++; staticMethod = false; } } if (!staticMethod) { // Generate the 'this' ref: var baseExpression = ((MemberAccessExpression)this.Target).Base; baseExpression.GenerateCode(generator, optimizationInfo); } } else { // These are always static. paraCount = UserDefined.Arguments.Count; argsSet = UserDefined.Arguments; // Skip 'this' - it's emitted separately: parameterOffset = 1; } // Next, we're matching params starting from parameterOffset with the args, // type casting if needed. for (int i = parameterOffset; i < paraCount; i++) { Expression expression = null; object defaultValue = null; Type paramType = null; if (paraSet == null) { // Get the type: paramType = argsSet[i].Type; } else { // Get the parameter info: var param = paraSet[i]; // Get the parameters type: paramType = param.ParameterType; // Get the default value: defaultValue = param.RawDefaultValue; // Is it a params array? if (Attribute.IsDefined(param, typeof(ParamArrayAttribute))) { // It's always an array - get the element type: paramType = paramType.GetElementType(); // For each of the remaining args.. int offset = i - parameterOffset; int argCount = 0; if (arguments != null) { // Get the full count: argCount = arguments.Count; } else if (argumentsOperand != null) { // Just one arg and it's still hanging around. argCount = offset + 1; } // Define an array: generator.LoadInt32(argCount); generator.NewArray(paramType); for (int a = offset; a < argCount; a++) { if (arguments != null) { // One of many args: expression = arguments[a]; } else { // Just one arg: expression = argumentsOperand; } generator.Duplicate(); generator.LoadInt32(a - offset); expression.GenerateCode(generator, optimizationInfo); Type res = expression.GetResultType(optimizationInfo); EmitConversion.Convert(generator, res, paramType); generator.StoreArrayElement(paramType); } // All done - can't be anymore. break; } } if (arguments != null && (i - parameterOffset) <= arguments.Count) { // Get one of many args: expression = arguments[i - parameterOffset]; } else if (argumentsOperand != null) { // Just the one argument. expression = argumentsOperand; // By setting it to null after, it can't get emitted again // (in the event that this method actually accepts >1 args) argumentsOperand = null; } if (expression == null) { // Emit whatever the default is for the parameters type: if (defaultValue != null) { // Emit the default value: EmitHelpers.EmitValue(generator, defaultValue); } else if (paramType.IsValueType) { // E.g. an integer 0 EmitHelpers.EmitValue(generator, Activator.CreateInstance(paramType)); } else { // Just a null (a real one): generator.LoadNull(); } } else if (expression is TemplateLiteralExpression) { // Tagged template literal. TemplateLiteralExpression templateLiteral = (TemplateLiteralExpression)expression; GenerateTemplateArgumentsArray(generator, optimizationInfo, templateLiteral); return; } else { // Output the arg: expression.GenerateCode(generator, optimizationInfo); // Convert: EmitConversion.Convert(generator, expression.GetResultType(optimizationInfo), paramType); } } }