/// <summary> /// Adds the submitted delegates to the diagram. /// </summary> /// <param name="delegates">A list of delegates to add.</param> private void AddDelegates(IEnumerable <NRDelegate> delegates) { foreach (NRDelegate nrDelegate in delegates) { DelegateType delegateType = diagram.AddDelegate( ); delegateType.Name = nrDelegate.Name; delegateType.AccessModifier = nrDelegate.AccessModifier.ToNClass( ); delegateType.ReturnType = nrDelegate.ReturnType.Name; foreach (NRParameter nrParameter in nrDelegate.Parameters) { delegateType.AddParameter(nrParameter.Declaration( )); } types.Add(nrDelegate, delegateType); } }
ISemantic E(FunctionLiteral x) { var dg = new DelegateType( (ctxt.Options & ResolutionOptions.DontResolveBaseTypes | ResolutionOptions.ReturnMethodReferencesOnly) != 0 ? null : TypeDeclarationResolver.GetMethodReturnType(x.AnonymousMethod, ctxt), x, TypeResolution.TypeDeclarationResolver.HandleNodeMatches(x.AnonymousMethod.Parameters, ctxt)); if (eval) { return(new DelegateValue(dg)); } else { return(dg); } }
static void GenLuaDelegates() { ToLuaExport.Clear(); DelegateType[] list = new DelegateType[] { _DT(typeof(Action <GameObject>)), //_DT(typeof(Action<GameObject, int, string>)), //_DT(typeof(Action<int, int, int, List<int>>)), //_DT(typeof(UIEventListener.VoidDelegate)).SetName("VoidDelegate"), }; ToLuaExport.GenDelegates(list); Debug.Log("Create lua delegate over"); }
public static void practice18() //delegate { //A test = new A(); //DelegateType Delmethod1 = new DelegateType(test.Print); // c# 1.0 이상에서 사용가능 //Delmethod1("Hello world1"); //DelegateType DelMethod2 = test.Print; // c# 2.0 이상에서 사용 가능 //DelMethod2("Hello world2"); A Test = new A(); DelegateType DelFunc = Test.PrintA; DelFunc += Test.PrintB; DelFunc(); DelFunc -= Test.PrintB; DelFunc(); }
public ForeignMacroExpr(DelegateType d, Converters.Converter convert, ForeignHelpers helpers) { _convert = convert; var source = d.Parameters.ToList(); source.Insert(0, new Parameter(d.Source, AttributeList.Empty, 0, d, MacroParam.DelegateArgName, null)); var uparams = source.Select(p => new MacroParam(p, convert, helpers)).ToList(); EntrypointIncludes.AddRange(CalcImportsForExternBlock(d)); EntrypointIncludes.AddRange(uparams.SelectMany(x => x.EntrypointIncludes)); CppSignatureArgs = convert.Signature.GenCppSignature(uparams); Params = uparams; JniSignature = convert.Signature.GenJniSignature(uparams, d.ReturnType); ReturnType = d.ReturnType; CallToUno = GenCppToUnoCall(uparams, false, true, d.Name, d, false); }
private void btn_Proceso_Click(object sender, EventArgs e) { // Set the delegate. TheDelegate = MessageHandler; StartFrom = Convert.ToInt32(txtStart.Text); EndTo = Convert.ToInt32(txtEnd.Text); progressBar1.Minimum = StartFrom; progressBar1.Maximum = EndTo; // Disable button, so that user cannot start again. btn_Proceso.Enabled = false; // Setup thread and start! Thread MyThread = new Thread(ProcessRoutine); MyThread.Start(); }
static void Main(string[] args) { delegateSilnia = new DelegateType(silnia); IAsyncResult ar = delegateSilnia.BeginInvoke(5, new AsyncCallback(SCallback), null); int result = delegateSilnia.EndInvoke(ar); delegateSilniaRek = new DelegateType(silniaRek); IAsyncResult arRek = delegateSilniaRek.BeginInvoke(5, new AsyncCallback(SRekCallback), null); int resultRek = delegateSilniaRek.EndInvoke(arRek); delegateFib = new DelegateType(fib); IAsyncResult arFib = delegateFib.BeginInvoke(5, new AsyncCallback(FibCallback), null); int resultFib = delegateFib.EndInvoke(arFib); Console.WriteLine("Silnia iteracyjnie: " + result); Console.WriteLine("Silnia rekurencyjnie: " + resultRek); Console.WriteLine("Fibonacci: " + resultFib); }
string GenJavaDelegateCode(DelegateType d, ForeignMacroExpr dEntity, string entrypointName) { using (var tw = new StringWriter()) { using (var ftw = new TextFormatter(tw)) { var voidReturn = d.ReturnType.IsVoid; var name = Convert.Name.JavaDelegateName(d); var fullName = Convert.Name.JavaDelegateName(d, true); var package = fullName.Substring(0, fullName.LastIndexOf('.')); var implements = (voidReturn && d.Parameters.Length == 0) ? " implements java.lang.Runnable" : ""; ftw.WriteLine("package " + package + ";"); ftw.WriteLine("import com.foreign.*;"); ftw.WriteLine("import com.uno.BoolArray;"); ftw.WriteLine("import com.uno.ByteArray;"); ftw.WriteLine("import com.uno.CharArray;"); ftw.WriteLine("import com.uno.DoubleArray;"); ftw.WriteLine("import com.uno.FloatArray;"); ftw.WriteLine("import com.uno.IntArray;"); ftw.WriteLine("import com.uno.LongArray;"); ftw.WriteLine("import com.uno.ObjectArray;"); ftw.WriteLine("import com.uno.ShortArray;"); ftw.WriteLine("import com.uno.StringArray;"); ftw.WriteLine("import com.uno.UnoObject;"); ftw.WriteLine(""); ftw.WriteLine("public class " + name + " extends com.uno.UnoObject" + implements); ftw.Indent("{"); ftw.WriteLine("public " + name + "(long ptr) { super(ptr); }"); ftw.Indent("public " + Convert.Type.UnoToJavaType(d.ReturnType, true) + " run(" + string.Join(", ", d.Parameters.Select(Convert.Param.UnoToJavaParameter)) + ") {"); var args = d.Parameters.Select(x => x.Name).ToList(); args.Insert(0, "this"); ftw.WriteLine((voidReturn ? "" : "return ") + dEntity.GenCallToNativeMethod(entrypointName, args) + ";"); ftw.Unindent("}"); ftw.Unindent("}"); var finalStr = tw.ToString(); return(finalStr); } } }
static void Main(string[] args) { delegateSilniaIt = new DelegateType(silniait); delegateSilniaRek = new DelegateType(silniarek); delegateFibo = new DelegateType(fibo); IAsyncResult ar = delegateSilniaIt.BeginInvoke(7, null, null); IAsyncResult ar2 = delegateSilniaRek.BeginInvoke(7, null, null); IAsyncResult ar3 = delegateFibo.BeginInvoke(7, null, null); int result1 = delegateSilniaIt.EndInvoke(ar); int result2 = delegateSilniaRek.EndInvoke(ar2); int result3 = delegateFibo.EndInvoke(ar3); //Console.WriteLine(result1); Console.WriteLine(result2); //Console.WriteLine(result3); Thread.Sleep(5000); }
private static void Simple() { // Instantiate the delegate using an anonymous method. DelegateType d = delegate(int k) { int i = k * 3; return(i); }; // Now use it. int l = 2; int j = d(l); Console.WriteLine("d({0}) = {1}", l, j); l = 3; j = d(l); Console.WriteLine("d({0}) = {1}", l, j); }
static void zad_8() { AutoResetEvent[] resetEvents = new AutoResetEvent[4]; for (int i = 0; i < 4; i++) { resetEvents[i] = new AutoResetEvent(false); } fibIter = fibIteration; fibRec = fibRecursion; silniaIter = silniaIteration; silniaRec = silniaRecursion; fibIter.BeginInvoke(20, ThreadProc, new object[] { fibIter, resetEvents[0] }); fibRec.BeginInvoke(20, ThreadProc, new object[] { fibIter, resetEvents[1] }); silniaRec.BeginInvoke(6, ThreadProc, new object[] { fibIter, resetEvents[2] }); silniaIter.BeginInvoke(6, ThreadProc, new object[] { fibIter, resetEvents[3] }); WaitHandle.WaitAll(resetEvents); }
public List <Parameter> get_async_begin_parameters() { Debug.Assert(this.coroutine); var glib_ns = CodeContext.get().root.scope.lookup("GLib"); var _params = new List <Parameter>(); Parameter ellipsis = null; foreach (var param in parameters) { if (param.ellipsis) { ellipsis = param; } else if (param.direction == ParameterDirection.IN) { _params.Add(param); } } var callback_type = new DelegateType((ValaDelegate)glib_ns.scope.lookup("AsyncReadyCallback")); callback_type.nullable = true; callback_type.value_owned = true; callback_type.is_called_once = true; var callback_param = new Parameter("_callback_", callback_type); callback_param.initializer = new NullLiteral(source_reference); callback_param.initializer.target_type = callback_type.copy(); callback_param.set_attribute_double("CCode", "pos", -1); callback_param.set_attribute_double("CCode", "delegate_target_pos", -0.9); _params.Add(callback_param); if (ellipsis != null) { _params.Add(ellipsis); } return(_params); }
private Parameter[] TypedLambdaParameterList(AstParameterList parameterList, DelegateType dt) { var parameters = dt.Parameters; if (parameterList.Parameters.Count != parameters.Length) { Error(parameterList.Source, ErrorCode.E1593, "Delegate " + dt.Quote() + " does not take " + parameterList.Parameters.Count + " arguments"); return(new Parameter[0]); } Parameter[] result = new Parameter[parameters.Length]; for (var i = 0; i < parameters.Length; ++i) { var param = parameters[i]; var astParam = parameterList.Parameters[i]; var astParamType = astParam.OptionalType != null ? Compiler.NameResolver.GetType(Function.DeclaringType, astParam.OptionalType) : param.Type; if (!astParamType.Equals(param.Type) || param.Modifier != astParam.Modifier || astParam.OptionalValue != null) { Error(parameterList.Source, ErrorCode.E1661, "Cannot convert anonymous method block to delegate type " + dt.Quote() + " because the specified block's parameter types do not match the delegate parameter types"); } var attributes = Compiler.CompileAttributes(Function.DeclaringType, astParam.Attributes); result[i] = new Parameter( astParam.Name.Source, attributes, param.Modifier, param.Type, astParam.Name.Symbol, null); } return(result); }
internal void DeleteActiveParameter( ) { if (ActiveMemberIndex >= 0) { int newIndex; if (ActiveMemberIndex == DelegateType.ArgumentCount - 1) // Last parameter { newIndex = ActiveMemberIndex - 1; } else { newIndex = ActiveMemberIndex; } DelegateType.RemoveParameter(ActiveParameter); ActiveMemberIndex = newIndex; OnActiveMemberChanged(EventArgs.Empty); } }
static void zadanie8() { delegatename = new DelegateType(silniaIt); IAsyncResult ar = delegatename.BeginInvoke(20, null, null); int result = delegatename.EndInvoke(ar); delegatename = new DelegateType(silniaRe); IAsyncResult ar2 = delegatename.BeginInvoke(8, null, null); int result2 = delegatename.EndInvoke(ar2); delegatename = new DelegateType(fibRe); IAsyncResult ar3 = delegatename.BeginInvoke(8, null, null); int result3 = delegatename.EndInvoke(ar3); Console.WriteLine("Silnia1: " + result); Console.WriteLine("Silnia2: " + result2); Console.WriteLine("Fibbonaci: " + result3); Console.ReadKey(); }
public Zad8() { var facRec = new DelegateType(FacRec); var fibIter = new DelegateType(FibIter); var fibRec = new DelegateType(FibRec); FacIter1 = FacIter; const int s = 35; var facRecResult = StopwatchUtil.Time(() => { var result1 = facRec.BeginInvoke(s, null, null); facRec.EndInvoke(result1); }); Console.WriteLine($"Czas obliczenia silni rekurencyjnie: {facRecResult}"); var facIterResult = StopwatchUtil.Time(() => { var result1 = FacIter1.BeginInvoke(s, null, null); FacIter1.EndInvoke(result1); }); Console.WriteLine($"Czas obliczenia silni iteracyjnie {facIterResult}"); var fibRecResult = StopwatchUtil.Time(() => { var result1 = fibRec.BeginInvoke(s, null, null); fibRec.EndInvoke(result1); }); Console.WriteLine($"Czas obliczenia ciągu fibonacciego rekurencyjnie {fibRecResult}"); var fibIterResult = StopwatchUtil.Time(() => { var result1 = fibIter.BeginInvoke(s, null, null); fibIter.EndInvoke(result1); }); Console.WriteLine($"Czas obliczenia ciągu fibonacciego iteracyjnie {fibIterResult}"); }
internal void GenDelegatePlumbing(DelegateType d) { if (!DelegatesSeen.ContainsKey(d)) { DelegateSanityCheck(d); var converted = new ForeignMacroExpr(d, Convert, Helpers); var entrypointName = Convert.Name.GenNativeMethodName(d); // Generate c++ entrypoint BlockHost.AddCppEntrypoint(converted, entrypointName); BlockHost.Include(d); // Generate java native method BlockHost.NativeJavaMethods.Add(converted.GenJavaNativeMethod(entrypointName)); // Generate java runnable/callable class DelegatesSeen.Add(d, GenJavaDelegateCode(d, converted, entrypointName)); } }
public void OnAfterDeserialize() { if (_returnTypeData != null && _returnTypeData.Length > 0) { return; } _returnTypeData = AssemblyReflectionHelper.Serialise(DelegateType.GetMethod("Invoke").ReturnType); if (_paramsTypeData != null && _paramsTypeData.Length > 0) { return; } _paramsTypeData = AssemblyReflectionHelper.Serialise( DelegateType .GetMethod("Invoke"). GetParameters(). Select(e => e.ParameterType).ToArray()); //if (_DelegateTypeData != null && _DelegateTypeData.Length > 0 && _delegateType == null) // _delegateType = DataHelper.Deserialse<Type>(_DelegateTypeData }
static void Zadanie8() { Console.WriteLine("\n ///Zadanie 8/// \n"); delegateName = new DelegateType(silniaI); IAsyncResult ar = delegateName.BeginInvoke(10, null, null); delegateName2 = new DelegateType(silniaR); IAsyncResult ar2 = delegateName2.BeginInvoke(10, null, null); delegateName3 = new DelegateType(fiboI); IAsyncResult ar3 = delegateName3.BeginInvoke(5, null, null); delegateName4 = new DelegateType(fiboR); IAsyncResult ar4 = delegateName4.BeginInvoke(5, null, null); Console.WriteLine("SilniaI " + delegateName.EndInvoke(ar)); Console.WriteLine("SilniaR " + delegateName2.EndInvoke(ar2)); Console.WriteLine("FiboI " + delegateName3.EndInvoke(ar3)); Console.WriteLine("FiboR " + delegateName4.EndInvoke(ar4)); }
static void Main(string[] args) { DelegateType D1 = new DelegateType(SilniaRekurencyjna); DelegateType D2 = new DelegateType(SilniaIteracyjna); DelegateType D3 = new DelegateType(Fibonacci); IAsyncResult IAR1 = D1.BeginInvoke(5, null, null); IAsyncResult IAR2 = D2.BeginInvoke(5, null, null); IAsyncResult IAR3 = D3.BeginInvoke(5, null, null); int wynik1 = D1.EndInvoke(IAR1); Console.WriteLine(wynik1); int wynik2 = D2.EndInvoke(IAR2); Console.WriteLine(wynik2); int wynik3 = D3.EndInvoke(IAR3); Console.WriteLine(wynik3); }
void AppendDelegate(DelegateType dt) { Skip(';'); Append(" "); AppendModifiers(dt.Modifiers); Append("delegate " + dt.ReturnType + " " + dt.GetNestedName()); if (dt.IsGenericDefinition) { Append("<"); for (int i = 0; i < dt.GenericParameters.Length; i++) { if (i > 0) { Append(","); } Append(dt.GenericParameters[i].Name); } Append(">"); } Append("("); bool first = true; foreach (var p in dt.Parameters) { if (!first) { Append(", "); } else { first = false; } Append(p.Modifier.ToLiteral(true) + p.Type + " " + p.Name); } AppendLine(");"); }
public static AbstractType GetMethodReturnType(DelegateType dg, ResolutionContext ctxt) { if (dg == null || ctxt == null) { return(null); } if (dg.IsFunctionLiteral) { return(GetMethodReturnType(((FunctionLiteral)dg.DeclarationOrExpressionBase).AnonymousMethod, ctxt)); } else { var rt = ((DelegateDeclaration)dg.DeclarationOrExpressionBase).ReturnType; var r = Resolve(rt, ctxt); ctxt.CheckForSingleResult(r, rt); return(r[0]); } }
string GetDelegateCall(Source src, DelegateType dt, List <string> arguments) { var parameters = dt.Parameters; // + 1 for the delegate itself if (parameters.Length + 1 != arguments.Count) { Log.Error(src, ErrorCode.E0000, "Foreign CPlusPlus error: Wrong number of arguments for macro call to delegate " + dt.FullName + "."); } string[] foreignParamTypes; string[] unoArgs; ConvertDelegateArguments(src, parameters, out foreignParamTypes, out unoArgs); var returnConversion = GetConversion(src, dt.ReturnType); using (var sw = new StringWriter()) using (var tf = new TextFormatter(sw)) { tf.BeginLine(); tf.Write("[] (" + Helpers.CompiledType(dt) + " __unoDelegate"); for (var i = 0; i < parameters.Length; ++i) { var p = parameters[i]; tf.Write(", " + foreignParamTypes[i] + " " + p.Name); } tf.Write(") -> " + returnConversion.ForeignType); tf.EndLine(); tf.Indent("{"); var call = Helpers.CallDelegate( Helpers.StringExpr(dt, "__unoDelegate"), parameters.Select((p, i) => Helpers.StringExpr(p.Type, unoArgs[i])).ToArray()); tf.WriteLine((dt.ReturnType.IsVoid ? call : "return " + call) + ";"); tf.Unindent(); tf.Write("} (" + string.Join(", ", arguments) + ")"); return(sw.ToString()); } }
static void Zadanie8() { DelegateType recursiveFactorial = new DelegateType(RecursiveFactorial); var ar = recursiveFactorial.BeginInvoke(10, null, null); Console.WriteLine("Recursive factorial: " + recursiveFactorial.EndInvoke(ar)); DelegateType iterativeFactorial = new DelegateType(IterativeFactorial); var ar2 = iterativeFactorial.BeginInvoke(10, null, null); Console.WriteLine("Iterative factorial: " + iterativeFactorial.EndInvoke(ar2)); DelegateType recursivefib = new DelegateType(RecursiveFib); var ar3 = recursivefib.BeginInvoke(10, null, null); Console.WriteLine("Recursive fibonacci: " + recursivefib.EndInvoke(ar3)); DelegateType interativefib = new DelegateType(IterativeFib); var ar4 = interativefib.BeginInvoke(10, null, null); Console.WriteLine("Interative fibonacci: " + interativefib.EndInvoke(ar4)); }
static void Main(string[] args) { silniaN = new DelegateType(silniar); silnia = new DelegateType(silniai); fibonaciN = new DelegateType(fibr); fibonaci = new DelegateType(fibi); IAsyncResult ar = silniaN.BeginInvoke(5, null, null); int result = silniaN.EndInvoke(ar); IAsyncResult ar2 = fibonaciN.BeginInvoke(6, null, null); int result2 = fibonaciN.EndInvoke(ar2); IAsyncResult ar3 = silnia.BeginInvoke(5, null, null); int result3 = silnia.EndInvoke(ar3); IAsyncResult ar4 = fibonaci.BeginInvoke(6, null, null); int result4 = fibonaci.EndInvoke(ar4); Console.WriteLine("5!={0}\nF(6)={1}", result, result2); Console.WriteLine("5!={0}\nF(6)={1}", result3, result4); }
public MethodInfo GetDelegateInvokeMethod(DelegateType dt) { MethodInfo result; if (_typeMethods.TryGetValue(dt, out result)) { return(result); } var type = GetType(dt); if (type.IsTypeBuilder()) { if (!dt.IsMasterDefinition) // Should always be true { result = TypeBuilder.GetMethod(type, GetDelegateInvokeMethod((DelegateType)dt.MasterDefinition)); } } else { try { result = type.GetMethod("Invoke"); } catch (ArgumentException e) { ThrowPrebuiltSignatureException(e, dt, dt.Parameters, GetParameterTypes(dt.Parameters)); } } if (result == null) { throw new FatalException(dt.Source, ErrorCode.E0000, ".NET delegate invoke method not resolved: " + dt + " [flags: " + dt.Stats + "]"); } _typeMethods.Add(dt, result); return(result); }
static void Main(string[] args) { silnia_rek_del = new DelegateType(Silnia_rek); silnia_ite_del = new DelegateType(Silnia_ite); fibonacci_ite_del = new DelegateType(Fibonacci_ite); fibonacci_rek_del = new DelegateType(Fibonacci_rek); IAsyncResult iasyncResult1 = silnia_rek_del.BeginInvoke(5, null, null); IAsyncResult iasyncResult2 = silnia_ite_del.BeginInvoke(5, null, null); IAsyncResult iasyncResult3 = fibonacci_ite_del.BeginInvoke(5, null, null); IAsyncResult iasyncResult4 = fibonacci_rek_del.BeginInvoke(5, null, null); int result1 = silnia_rek_del.EndInvoke(iasyncResult1); int result2 = silnia_ite_del.EndInvoke(iasyncResult2); int result3 = fibonacci_ite_del.EndInvoke(iasyncResult3); int result4 = fibonacci_rek_del.EndInvoke(iasyncResult4); Console.WriteLine(result1); Console.WriteLine(result2); Console.WriteLine(result3); Console.WriteLine(result4); Console.ReadKey(); }
public Zad8() { //Dla silnie podmienić na funkcje silnii delegat1 = new DelegateType(fib); delegat2 = new DelegateType(fibRek); int value = 21; IAsyncResult result = delegat1.BeginInvoke(value, null, null); IAsyncResult resultRek = delegat2.BeginInvoke(value, null, null); int delegateResultRek = delegat2.EndInvoke(resultRek); Console.WriteLine("Rekurencyjnie: " + delegateResultRek); //Z racji, że EndInvoke jest blokowy, wynik dla funkcji iteracyjnej wyświetlany przed zwróceniem jej wyniku. //Może to delikatnie przekłamać wynik, ale przy większych liczbach nie zrobi to większej różnicy. int delegateResult = delegat1.EndInvoke(result); Console.ReadKey(); }
private void RefreshValues() { DelegateType type = shape.DelegateType; Language language = type.Language; SuspendLayout(); // txtReturnType int cursorPosition = txtReturnType.SelectionStart; txtReturnType.Text = type.ReturnType; txtReturnType.SelectionStart = cursorPosition; // txtName cursorPosition = txtName.SelectionStart; txtName.Text = type.Name; txtName.SelectionStart = cursorPosition; SetError(null); needValidation = false; RefreshVisibility(); ResumeLayout(); }
private void txtReturnType_TextChanged(object sender, EventArgs e) { DiagramElement selectedElement = diagram.FirstSelectedElement; if (diagram.SingleSelection && selectedElement is DelegateShape) { DelegateType _delegate = ((DelegateShape)selectedElement).DelegateType; if (_delegate.ReturnType != txtReturnType.Text) { try { _delegate.ReturnType = txtReturnType.Text; txtReturnType.ForeColor = SystemColors.WindowText; } catch (BadSyntaxException) { txtReturnType.ForeColor = Color.Red; } } else { txtReturnType.ForeColor = SystemColors.WindowText; } } }
static void Main(string[] args) { Stopwatch sw = new Stopwatch(); sw.Start(); f1 = new DelegateType(Silnia1); IAsyncResult ar1 = f1.BeginInvoke(999, null, null); f2 = new DelegateType(Silnia2); IAsyncResult ar2 = f2.BeginInvoke(999, null, null); f3 = new DelegateType(Silnia1); IAsyncResult ar3 = f3.BeginInvoke(999, null, null); f4 = new DelegateType(Silnia2); IAsyncResult ar4 = f4.BeginInvoke(999, null, null); WaitHandle.WaitAny(new WaitHandle[] { ar1.AsyncWaitHandle, ar2.AsyncWaitHandle, ar3.AsyncWaitHandle, ar4.AsyncWaitHandle }); sw.Stop(); Console.WriteLine("{0:00}:{1:00}:{2:000}", sw.Elapsed.Minutes, sw.Elapsed.Seconds, sw.Elapsed.Milliseconds); sw.Reset(); Console.ReadKey(); }
bool HandleDecl(TemplateTypeParameter par, DelegateDeclaration d, DelegateType dr) { // Delegate literals or other expressions are not allowed if(dr==null || dr.IsFunctionLiteral) return false; var dr_decl = (DelegateDeclaration)dr.DeclarationOrExpressionBase; // Compare return types if( d.IsFunction == dr_decl.IsFunction && dr.ReturnType != null && HandleDecl(par, d.ReturnType,dr.ReturnType)) { // If no delegate args expected, it's valid if ((d.Parameters == null || d.Parameters.Count == 0) && dr_decl.Parameters == null || dr_decl.Parameters.Count == 0) return true; // If parameter counts unequal, return false else if (d.Parameters == null || dr_decl.Parameters == null || d.Parameters.Count != dr_decl.Parameters.Count) return false; // Compare & Evaluate each expected with given parameter var dr_paramEnum = dr_decl.Parameters.GetEnumerator(); foreach (var p in d.Parameters) { // Compare attributes with each other if (p is DNode) { if (!(dr_paramEnum.Current is DNode)) return false; var dn = (DNode)p; var dn_arg = (DNode)dr_paramEnum.Current; if ((dn.Attributes == null || dn.Attributes.Count == 0) && (dn_arg.Attributes == null || dn_arg.Attributes.Count == 0)) return true; else if (dn.Attributes == null || dn_arg.Attributes == null || dn.Attributes.Count != dn_arg.Attributes.Count) return false; foreach (var attr in dn.Attributes) { if(!dn_arg.ContainsAttribute(attr)) return false; } } // Compare types if (p.Type!=null && dr_paramEnum.MoveNext() && dr_paramEnum.Current.Type!=null) { var dr_resolvedParamType = TypeDeclarationResolver.ResolveSingle(dr_paramEnum.Current.Type, ctxt); if (dr_resolvedParamType == null || !HandleDecl(par, p.Type, dr_resolvedParamType)) return false; } else return false; } } return false; }
public static void GenDelegates(DelegateType[] list) { usingList.Add("System"); usingList.Add("System.Collections.Generic"); for (int i = 0; i < list.Length; i++) { Type t = list[i].type; //if (t.Namespace != null && t.Namespace != string.Empty) //{ // usingList.Add(t.Namespace); //} if (!typeof(System.Delegate).IsAssignableFrom(t)) { Debug.LogError(t.FullName + " not a delegate type"); return; } //MethodInfo mi = t.GetMethod("Invoke"); //ParameterInfo[] pi = mi.GetParameters(); //int n = pi.Length; //for (int j = 0; j < n; j++) //{ // ParameterInfo param = pi[j]; // t = param.ParameterType; // if (!t.IsPrimitive && t.Namespace != null && t.Namespace != string.Empty) // { // usingList.Add(t.Namespace); // } //} } sb.AppendLine("public static class DelegateFactory"); sb.AppendLine("{"); sb.AppendLine("\tdelegate Delegate DelegateValue(LuaFunction func);"); sb.AppendLine("\tstatic Dictionary<Type, DelegateValue> dict = new Dictionary<Type, DelegateValue>();"); sb.AppendLine(); sb.AppendLine("\t[NoToLuaAttribute]"); sb.AppendLine("\tpublic static void Register(IntPtr L)"); sb.AppendLine("\t{"); for (int i = 0; i < list.Length; i++) { string type = list[i].strType; string name = list[i].name; sb.AppendFormat("\t\tdict.Add(typeof({0}), new DelegateValue({1}));\r\n", type, name); } sb.AppendLine("\t}\r\n"); sb.AppendLine("\t[NoToLuaAttribute]"); sb.AppendLine("\tpublic static Delegate CreateDelegate(Type t, LuaFunction func)"); sb.AppendLine("\t{"); sb.AppendLine("\t\tDelegateValue create = null;\r\n"); sb.AppendLine("\t\tif (!dict.TryGetValue(t, out create))"); sb.AppendLine("\t\t{"); sb.AppendLine("\t\t\tDebugger.LogError(\"Delegate {0} not register\", t.FullName);"); sb.AppendLine("\t\t\treturn null;"); sb.AppendLine("\t\t}"); sb.AppendLine("\t\treturn create(func);"); sb.AppendLine("\t}\r\n"); for (int i = 0; i < list.Length; i++) { Type t = list[i].type; string type = list[i].strType; string name = list[i].name; sb.AppendFormat("\tpublic static Delegate {0}(LuaFunction func)\r\n", name); sb.AppendLine("\t{"); sb.AppendFormat("\t\t{0} d = ", type); GenDelegateBody(t, "\t\t", false); sb.AppendLine("\t\treturn d;"); sb.AppendLine("\t}\r\n"); } sb.AppendLine("}"); SaveFile(AppConst.uLuaPath + "/Source/Base/DelegateFactory.cs"); Clear(); }
public static AbstractType GetMethodReturnType(DelegateType dg, ResolutionContext ctxt) { if (dg == null || ctxt == null) return null; if (dg.IsFunctionLiteral) return GetMethodReturnType(((FunctionLiteral)dg.DeclarationOrExpressionBase).AnonymousMethod, ctxt); else { var rt = ((DelegateDeclaration)dg.DeclarationOrExpressionBase).ReturnType; var r = Resolve(rt, ctxt); ctxt.CheckForSingleResult(r, rt); return r[0]; } }
static void GenLuaDelegates() { ToLuaExport.Clear(); DelegateType[] list = new DelegateType[] { _DT(typeof(Action<GameObject>)), //_DT(typeof(Action<GameObject, int, string>)), //_DT(typeof(Action<int, int, int, List<int>>)), //_DT(typeof(UIEventListener.VoidDelegate)).SetName("VoidDelegate"), }; ToLuaExport.GenDelegates(list); Debug.Log("Create lua delegate over"); }
ISemantic E(FunctionLiteral x) { var dg = new DelegateType(TypeDeclarationResolver.GetMethodReturnType(x.AnonymousMethod, ctxt),x); if (eval) return new DelegateValue(dg); else return dg; }
/// <summary> /// If not null, it will be used as the new creation method to make StreamReader instances. /// Will reset to the default creation logic in case the given <c>callback</c> is <c>null</c>. /// </summary> public static void SetCallback(DelegateType callback) { m_Delegate.Set(callback); }
static void GenLuaBinder() { if (!beAutoGen && EditorApplication.isCompiling) { EditorUtility.DisplayDialog("警告", "请等待编辑器完成编译再执行此功能", "确定"); return; } allTypes.Clear(); ToLuaTree<string> tree = InitTree(); StringBuilder sb = new StringBuilder(); List<DelegateType> dtList = new List<DelegateType>(); List<DelegateType> list = new List<DelegateType>(); list.AddRange(CustomSettings.customDelegateList); HashSet<Type> set = GetCustomTypeDelegates(); List<BindType> backupList = new List<BindType>(); backupList.AddRange(allTypes); ToLuaNode<string> root = tree.GetRoot(); foreach (Type t in set) { if (null == list.Find((p) => { return p.type == t; })) { DelegateType dt = new DelegateType(t); AddSpaceNameToTree(tree, root, dt.type.Namespace); list.Add(dt); } } sb.AppendLineEx("//this source code was auto-generated by tolua#, do not modify it"); sb.AppendLineEx("using System;"); sb.AppendLineEx("using UnityEngine;"); sb.AppendLineEx("using LuaInterface;"); sb.AppendLineEx(); sb.AppendLineEx("public static class LuaBinder"); sb.AppendLineEx("{"); sb.AppendLineEx("\tpublic static void Bind(LuaState L)"); sb.AppendLineEx("\t{"); sb.AppendLineEx("\t\tfloat t = Time.realtimeSinceStartup;"); sb.AppendLineEx("\t\tL.BeginModule(null);"); GenRegisterInfo(null, sb, list, dtList); Action<ToLuaNode<string>> begin = (node) => { if (node.value == null) { return; } sb.AppendFormat("\t\tL.BeginModule(\"{0}\");\r\n", node.value); string space = GetSpaceNameFromTree(node); GenRegisterInfo(space, sb, list, dtList); }; Action<ToLuaNode<string>> end = (node) => { if (node.value != null) { sb.AppendLineEx("\t\tL.EndModule();"); } }; tree.DepthFirstTraversal(begin, end, tree.GetRoot()); sb.AppendLineEx("\t\tL.EndModule();"); if (CustomSettings.dynamicList.Count > 0) { sb.AppendLineEx("\t\tL.BeginPreLoad();"); for (int i = 0; i < CustomSettings.dynamicList.Count; i++) { Type t1 = CustomSettings.dynamicList[i]; BindType bt = backupList.Find((p) => { return p.type == t1; }); sb.AppendFormat("\t\tL.AddPreLoad(\"{0}\", LuaOpen_{1}, typeof({0}));\r\n", bt.name, bt.wrapName); } sb.AppendLineEx("\t\tL.EndPreLoad();"); } sb.AppendLineEx("\t\tDebugger.Log(\"Register lua type cost time: {0}\", Time.realtimeSinceStartup - t);"); sb.AppendLineEx("\t}"); for (int i = 0; i < dtList.Count; i++) { ToLuaExport.GenEventFunction(dtList[i].type, sb); } if (CustomSettings.dynamicList.Count > 0) { for (int i = 0; i < CustomSettings.dynamicList.Count; i++) { Type t = CustomSettings.dynamicList[i]; BindType bt = backupList.Find((p) => { return p.type == t; }); GenPreLoadFunction(bt, sb); } } sb.AppendLineEx("}\r\n"); allTypes.Clear(); string file = CustomSettings.saveDir + "LuaBinder.cs"; using (StreamWriter textWriter = new StreamWriter(file, false, Encoding.UTF8)) { textWriter.Write(sb.ToString()); textWriter.Flush(); textWriter.Close(); } AssetDatabase.Refresh(); Debugger.Log("Generate LuaBinder over !"); }
public static void GenDelegates(DelegateType[] list) { usingList.Add("System"); usingList.Add("System.Collections.Generic"); for (int i = 0; i < list.Length; i++) { Type t = list[i].type; if (!typeof(System.Delegate).IsAssignableFrom(t)) { Debug.LogError(t.FullName + " not a delegate type"); return; } } sb.Append("public static class DelegateFactory\r\n"); sb.Append("{\r\n"); sb.Append("\tpublic delegate Delegate DelegateValue(LuaFunction func);\r\n"); sb.Append("\tpublic static Dictionary<Type, DelegateValue> dict = new Dictionary<Type, DelegateValue>();\r\n"); sb.AppendLineEx(); sb.Append("\tstatic DelegateFactory()\r\n"); sb.Append("\t{\r\n"); sb.Append("\t\tRegister();\r\n"); sb.AppendLineEx("\t}\r\n"); sb.Append("\t[NoToLuaAttribute]\r\n"); sb.Append("\tpublic static void Register()\r\n"); sb.Append("\t{\r\n"); sb.Append("\t\tdict.Clear();\r\n"); for (int i = 0; i < list.Length; i++) { string type = list[i].strType; string name = list[i].name; sb.AppendFormat("\t\tdict.Add(typeof({0}), {1});\r\n", type, name); } sb.Append("\t}\r\n"); sb.Append(CreateDelegate); sb.AppendLineEx(RemoveDelegate); for (int i = 0; i < list.Length; i++) { Type t = list[i].type; string strType = list[i].strType; string name = list[i].name; MethodInfo mi = t.GetMethod("Invoke"); string args = GetDelegateParams(mi); sb.AppendFormat("\tclass {0}_Event : LuaDelegate\r\n", name); sb.AppendLineEx("\t{"); sb.AppendFormat("\t\tpublic {0}_Event(LuaFunction func) : base(func) {{ }}\r\n", name); sb.AppendLineEx(); sb.AppendFormat("\t\tpublic {0} Call({1})\r\n", GetTypeStr(mi.ReturnType), args); GenDelegateBody(sb, t, "\t\t"); sb.AppendLineEx("\t}\r\n"); sb.AppendFormat("\tpublic static Delegate {0}(LuaFunction func)\r\n", name); sb.AppendLineEx("\t{"); sb.AppendLineEx("\t\tif (func == null)"); sb.AppendLineEx("\t\t{"); if (mi.ReturnType == typeof(void)) { sb.AppendLineEx("\t\t\t" + strType + " fn = delegate { };"); } else { GenDefaultDelegate(mi.ReturnType, "\t\t\t", strType); } sb.AppendLineEx("\t\t\treturn fn;"); sb.AppendLineEx("\t\t}\r\n"); sb.AppendFormat("\t\t{0} d = (new {1}_Event(func)).Call;\r\n", strType, name); sb.AppendLineEx("\t\treturn d;"); sb.AppendLineEx("\t}\r\n"); } sb.AppendLineEx("}\r\n"); SaveFile(CustomSettings.saveDir + "DelegateFactory.cs"); Clear(); }
public ISymbolValue Visit(FunctionLiteral x) { var dg = new DelegateType( (ctxt.Options & ResolutionOptions.DontResolveBaseTypes | ResolutionOptions.ReturnMethodReferencesOnly) != 0 ? null : TypeDeclarationResolver.GetMethodReturnType (x.AnonymousMethod, ctxt), x, TypeResolution.TypeDeclarationResolver.HandleNodeMatches(x.AnonymousMethod.Parameters, ctxt)); return new DelegateValue(dg); }