void LeaveBlock(RunSharpFunc <Block, Label?> tryGetJumpLabel)
        {
            BeforeStatement();

            bool useLeave = false;

            foreach (Block blk in _blocks)
            {
                ExceptionBlock xb = blk as ExceptionBlock;

                if (xb != null)
                {
                    if (xb.IsFinally)
                    {
                        throw new InvalidOperationException(Properties.Messages.ErrInvalidFinallyBranch);
                    }

                    useLeave = true;
                }


                Label?label = tryGetJumpLabel(blk);

                if (label != null)
                {
                    IL.Emit(useLeave ? OpCodes.Leave : OpCodes.Br, label.Value);
                    IsReachable = false;
                    return;
                }
            }

            throw new InvalidOperationException(Properties.Messages.ErrInvalidContinue);
        }
示例#2
0
        private void GenerateStaticMethodCode(ILGenerator gen, CodeFlow cf, MethodInfo method)
        {
            var   stackDescriptor  = cf.LastDescriptor();
            Label?skipIfNullTarget = null;

            if (_nullSafe)
            {
                skipIfNullTarget = GenerateNullCheckCode(gen);
            }

            if (stackDescriptor != null)
            {
                // Something on the stack when nothing is needed
                gen.Emit(OpCodes.Pop);
            }

            GenerateCodeForArguments(gen, cf, method, _children);
            gen.Emit(OpCodes.Call, method);

            if (_originalPrimitiveExitTypeDescriptor != null)
            {
                // The output of the accessor will be a primitive but from the block above it might be null,
                // so to have a 'common stack' element at skipIfNull target we need to box the primitive
                CodeFlow.InsertBoxIfNecessary(gen, _originalPrimitiveExitTypeDescriptor);
            }

            if (skipIfNullTarget.HasValue)
            {
                gen.MarkLabel(skipIfNullTarget.Value);
            }
        }
示例#3
0
        private void op_erase_line(ILGenerator il)
        {
            FieldInfo  ioFI        = typeof(ZMachine).GetField("io", BindingFlags.NonPublic | BindingFlags.Instance);
            MethodInfo eraseLineMI = typeof(IZMachineIO).GetMethod("EraseLine");

            Label?skip = null;

            if (argc >= 1)
            {
                if (operandTypes[0] == OperandType.Variable)
                {
                    skip = il.DefineLabel();
                    LoadOperand(il, 0);
                    il.Emit(OpCodes.Ldc_I4_1);
                    il.Emit(OpCodes.Bne_Un, skip.Value);
                }
                else if (operandValues[0] != 1)
                {
                    return;
                }
            }

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, ioFI);
            il.Emit(OpCodes.Call, eraseLineMI);

            if (skip != null)
            {
                il.MarkLabel(skip.Value);
            }
        }
        public override void GenerateCode(ILGenerator gen, CodeFlow cf)
        {
            if (_cachedReadAccessor is not ICompilablePropertyAccessor accessorToUse)
            {
                throw new InvalidOperationException("Property accessor is not compilable: " + _cachedReadAccessor);
            }

            Label?skipIfNullLabel = null;

            if (_nullSafe)
            {
                skipIfNullLabel = gen.DefineLabel();
                gen.Emit(OpCodes.Dup);
                gen.Emit(OpCodes.Ldnull);
                gen.Emit(OpCodes.Cgt_Un);
                gen.Emit(OpCodes.Brfalse, skipIfNullLabel.Value);
            }

            accessorToUse.GenerateCode(_name, gen, cf);
            cf.PushDescriptor(_exitTypeDescriptor);
            if (_originalPrimitiveExitTypeDescriptor != null)
            {
                // The output of the accessor is a primitive but from the block above it might be null,
                // so to have a common stack element type at skipIfNull target it is necessary
                // to box the primitive
                CodeFlow.InsertBoxIfNecessary(gen, _originalPrimitiveExitTypeDescriptor);
            }

            if (skipIfNullLabel.HasValue)
            {
                gen.MarkLabel(skipIfNullLabel.Value);
            }
        }
            protected override void EndImpl()
            {
                if (_test == null)
                {
                    throw new InvalidOperationException("Loop condition has not been initialized");
                }
                if (_iter != null)
                {
                    if (_iterUsed)
                    {
                        G.IL.MarkLabel(_lbIter);
                    }

                    _iter.Emit(G);
                }

                G.IL.MarkLabel(_lbTest);
                var lbFalse = new OptionalLabel(G.IL);

                if (_endUsed)
                {
                    lbFalse = _lbEnd;
                }
                Label?lbLoopCopy = _lbLoop;

                _test.EmitBranch(G, lbLoopCopy, lbFalse);
                if (lbFalse.IsLabelExist)
                {
                    G.IL.MarkLabel(lbFalse.Value);
                }

                G.IsReachable = true;
            }
示例#6
0
        public override int VisitWhile_loop_stmt(BRAQParser.While_loop_stmtContext context)
        {
            //сгенерируем условие
            Label beforeCond = il.DefineLabel();

            var prev_loop_begin = loop_begin;
            var prev_loop_end   = loop_end;

            il.MarkLabel(beforeCond); //точка перед условием

            Label after_loop_body = il.DefineLabel();

            loop_begin = beforeCond;
            loop_end   = after_loop_body;

            if (context.cond != null)  // возможно сгенерируем условие
            {
                context.cond.Accept(this);
                il.Emit(OpCodes.Brfalse_S, after_loop_body);
            }


            context.body.Accept(this);
            il.Emit(OpCodes.Br_S, beforeCond); // прыгаем к проверке условий
            il.MarkLabel(after_loop_body);     //точка выхода

            loop_begin = prev_loop_begin;
            loop_end   = prev_loop_end;

            return(0);
        }
示例#7
0
        public override int VisitFunction_def_stmt(BRAQParser.Function_def_stmtContext context)
        {
            if (current_method == null)
            {
                Console.WriteLine("Huh!?");
                return(0);
            }

            method_end = il.DefineLabel();

            foreach (var l in locals)
            {
                il.DeclareLocal(typerResult.local_types[l]);
            }

            if (current_method.return_type != typeof(void))
            {
                return_holder = il.DeclareLocal(current_method.return_type);
            }

            context.function_body.Accept(this);


            il.MarkLabel(method_end.Value);

            if (current_method.return_type != typeof(void))
            {
                il.Emit(OpCodes.Ldloc, return_holder);
            }

            il.Emit(OpCodes.Ret);
            return(0);
        }
示例#8
0
 public static void _WriteIfCondition(Condition condition, Action block, Label?lblEndIf = null, Func <Condition>?fallThroughCondition = null, bool invert = false)
 {
     Context.New(() => {
         block.Invoke();
         //Skip to "EndIf" if the condition succeeded
         if (lblEndIf != null)
         {
             if (fallThroughCondition != null)
             {
                 Branch(fallThroughCondition.Invoke(), CPU6502.Asm.OC["JMP"][CPU6502.Asm.Mode.Absolute].Length, invert);
             }
             GoTo(lblEndIf);
         }
         var len = Context.Length;
         if (len <= HIGHEST_BRANCH_VAL)
         {
             Context.Parent(() => {
                 Branch(condition, len, !invert);
             });
         }
         else
         {
             var lblOptionEnd = Labels.New();
             Context.Parent(() => {
                 Branch(condition, CPU6502.Asm.OC["JMP"][CPU6502.Asm.Mode.Absolute].Length, invert);
                 GoTo(lblOptionEnd);
             });
             Context.Write(lblOptionEnd);
         }
     });
 }
示例#9
0
        public static void MarkBlockBefore(ILGenerator il, ExceptionBlock block, out Label?label)
        {
            label = null;
            switch (block.blockType)
            {
            case ExceptionBlockType.BeginExceptionBlock:
                label = il.BeginExceptionBlock();
                return;

            case ExceptionBlockType.BeginCatchBlock:
                il.BeginCatchBlock(block.catchType);
                return;

            case ExceptionBlockType.BeginExceptFilterBlock:
                il.BeginExceptFilterBlock();
                return;

            case ExceptionBlockType.BeginFaultBlock:
                il.BeginFaultBlock();
                return;

            case ExceptionBlockType.BeginFinallyBlock:
                il.BeginFinallyBlock();
                return;
            }
        }
 protected override void OnApplyTemplate()
 {
     base.OnApplyTemplate();
     LoadingPanel = (StackLayout)GetTemplateChild("pnl_waiting");
     WaitingLabel = (Label)GetTemplateChild("lbl_waiting");
     MainContent  = (ContentPresenter)GetTemplateChild("pnl_main");
 }
示例#11
0
        public static void _WriteAnyCondition(object[] conditions, Action block, Label?lblEndIf = null, Label?lblShortCircuitSuccess = null)
        {
            var lblSuccess = lblShortCircuitSuccess ?? Labels.New();
            var lblEnd     = Labels.New();

            void successBlock() => GoTo(lblSuccess);

            var last = conditions.Last();

            foreach (var condition in conditions)
            {
                _WriteCondition(condition, successBlock, null, lblSuccess /*, true*/);               //, condition == last ? lblEndIf : null);
            }
            //If this is a nested Any, the GoTo(lblSuccess) used above will skip out to the parent Any's success label and this stuff won't be needed
            //TODO: determine if this lblShortCircuitSuccess business is even needed. Who the hell needs to nest Any() conditions?! they could be merged and have the same effect. Maybe if helpers return an Any(), and that's used within another?
            if (lblShortCircuitSuccess == null)
            {
                GoTo(lblEnd);
                Context.Write(lblSuccess);
                block.Invoke();
            }

            if (lblEndIf != null)
            {
                //if (fallThroughCondition != null)
                //	Branch(fallThroughCondition.Invoke(), (U8)Asm.JMP.Absolute.Length);
                Comment("right before goto endif");
                GoTo(lblEndIf);
            }
            Comment("after goto endif and before writeany's lblend");
            Context.Write(lblEnd);
        }
示例#12
0
        /// <summary>Multi-condition If block</summary>
        /// <example>
        /// If.Block(c => c
        ///		.Option(() => A.Equals(1),	() => A.Set(2))
        ///     .Option(() => A.Equals(2),	() => A.Set(9))
        ///     .Default(					() => A.Set(5))
        /// );
        /// </example>
        /// <param name="options"></param>
        public static void Block(Func <_IfBlock, _IfBlock> block)
        {
            var ifBlock = block.Invoke(new _IfBlock());

            var   numOptions       = ifBlock._options.Count;
            var   optionConditions = ifBlock._options.Where(x => x is _IfBlock._Option).Cast <_IfBlock._Option>().ToList();
            var   optionDefault    = ifBlock._options.Where(x => x is _IfBlock._Default).Cast <_IfBlock._Default>().ToList();
            var   hasElse          = optionDefault.Any();
            Label?lblEnd           = null;

            if (numOptions > 1 || hasElse)
            {
                lblEnd = Labels.New();
            }
            var lastCondition = optionConditions.Last();

            foreach (var oc in optionConditions)
            {
                var isLast = oc == lastCondition;
                Branching._WriteCondition(oc.Condition, oc.Block, hasElse || !isLast ? lblEnd : null, null, oc.Invert);                 //don't output "GoTo EndIf" if this is the last condition
            }
            if (numOptions > 1)
            {
                if (hasElse)
                {
                    optionDefault[0].Block?.Invoke();
                }
                if (lblEnd != null)                 //always true in this block, suppressing nullable complaint
                {
                    Context.Write(lblEnd);
                }
            }
            Reset();
        }
示例#13
0
 void RestoreEndLabel(Label?e)
 {
     if (TargetEntity is Script s)
     {
         s.End = e;
     }
 }
示例#14
0
            static IEnumerable <CodeInstruction> DontSpamFullyHealedMessaged(IEnumerable <CodeInstruction> instructions)
            {
                const int localHealedBool = 7;
                var       phase           = 0;
                Label?    skipMessage     = null;

                foreach (var instruction in instructions)
                {
                    switch (phase)
                    {
                    case 0:
                        if (instruction.opcode == OpCodes.Call &&
                            (MethodInfo)instruction.operand == AccessTools.Method(
                                typeof(PawnUtility),
                                nameof(PawnUtility.ShouldSendNotificationAbout)))
                        {
                            phase = 1;
                        }
                        break;

                    case 1:
                        if (instruction.opcode == OpCodes.Brfalse)
                        {
                            phase       = 2;
                            skipMessage = instruction.operand as Label?;
                        }
                        break;

                    case 2:
                        phase = -1;

                        yield return(new CodeInstruction(OpCodes.Ldloc, localHealedBool));

                        yield return(new CodeInstruction(OpCodes.Ldarg_0));

                        yield return(new CodeInstruction(OpCodes.Ldfld,
                                                         AccessTools.Field(
                                                             typeof(Pawn_HealthTracker),
                                                             "pawn")));

                        yield return(new CodeInstruction(
                                         OpCodes.Call,
                                         AccessTools.Method(
                                             typeof(Harmony_Pawn_HealthTracker_HealthTick_LogSpam),
                                             nameof(ShouldSendMessage))));

                        yield return(new CodeInstruction(OpCodes.Brfalse, skipMessage.Value));

                        break;
                    }

                    yield return(instruction);
                }

                if (phase > 0)
                {
                    Log.Error("Failed to patch Pawn_HealthTracker.HealthTick for DontSpamFullyHealedMessaged, phase reached " + phase);
                }
            }
示例#15
0
        private void GenerateInstanceMethodCode(ILGenerator gen, CodeFlow cf, MethodInfo targetMethod, Type targetType)
        {
            var stackDescriptor = cf.LastDescriptor();

            if (stackDescriptor == null)
            {
                // Nothing on the stack but something is needed
                CodeFlow.LoadTarget(gen);
                stackDescriptor = TypeDescriptor.OBJECT;
            }

            Label?skipIfNullTarget = null;

            if (_nullSafe)
            {
                skipIfNullTarget = GenerateNullCheckCode(gen);
            }

            if (targetType.IsValueType)
            {
                if (stackDescriptor.IsBoxed || stackDescriptor.IsReferenceType)
                {
                    gen.Emit(OpCodes.Unbox_Any, targetType);
                }

                var local = gen.DeclareLocal(targetType);
                gen.Emit(OpCodes.Stloc, local);
                gen.Emit(OpCodes.Ldloca, local);
            }
            else
            {
                if (stackDescriptor.Value != targetType)
                {
                    CodeFlow.InsertCastClass(gen, new TypeDescriptor(targetType));
                }
            }

            GenerateCodeForArguments(gen, cf, targetMethod, _children);
            if (targetType.IsValueType)
            {
                gen.Emit(OpCodes.Call, targetMethod);
            }
            else
            {
                gen.Emit(OpCodes.Callvirt, targetMethod);
            }

            if (_originalPrimitiveExitTypeDescriptor != null)
            {
                // The output of the accessor will be a primitive but from the block above it might be null,
                // so to have a 'common stack' element at skipIfNull target we need to box the primitive
                CodeFlow.InsertBoxIfNecessary(gen, _originalPrimitiveExitTypeDescriptor);
            }

            if (skipIfNullTarget.HasValue)
            {
                gen.MarkLabel(skipIfNullTarget.Value);
            }
        }
示例#16
0
 public override void _Ready()
 {
     ColumnTemplate = GetNode <VBoxContainer>("ScrollContainer/Table/Columns/ColumnTemplate");
     RowsLabel      = GetNode <Label>("ScrollContainer/Table/TableControls/RowsLabel");
     ColumnsLabel   = GetNode <Label>("ScrollContainer/Table/TableControls/ColumnsLabel");
     ColumnsNode    = GetNode <HBoxContainer>("ScrollContainer/Table/Columns");
     IDCol          = ColumnsNode.GetNode <VBoxContainer>("IDCol");
 }
示例#17
0
 public void EmitLoop(ILGenerator ilg)
 {
     if (Cont == null)
     {
         Cont = ilg.DefineLabel();
     }
     ilg.Emit(OpCodes.Br, Cont.Value);
 }
示例#18
0
        void EmitWrite(SerializerCodeGen g, Label?endLabel, MetaType metaType, Local actualValue, Local actualType, int recursionLevel = 0)
        {
            using (g.ctx.StartDebugBlockAuto(this, metaType.GetFinalSettingsCopy().Name + ", level = " + recursionLevel))
            {
                WriterGen dest       = g.Writer;
                var       breakLabel = g.DefineLabel();
                g.If(metaType.Type != actualType.AsOperand);
                {
                    foreach (var subType in metaType.GetSubtypes().OrderBy(st => st.FieldNumber))
                    {
                        MetaType derivedType = subType.DerivedType;
                        if (derivedType.Type == metaType.Type)
                        {
                            continue;
                        }
                        g.If(actualValue.AsOperand.Is(derivedType.Type));
                        {
                            if (recursionLevel == 0)
                            {
                                g.If(derivedType.Type == actualType.AsOperand);
                                {
                                    dest.WriteFieldHeaderComplete(WireType.Variant);
                                    dest.WriteInt32(subType.FieldNumber + 1);
                                    g.Goto(endLabel ?? breakLabel);
                                }
                                g.End();

                                using (var token = g.ctx.Local(typeof(SubItemToken)))
                                {
                                    g.Assign(token, g.WriterFunc.StartSubItem(null, true));
                                    dest.WriteFieldHeaderIgnored(WireType.Variant);
                                    dest.WriteInt32(subType.FieldNumber + 1);

                                    EmitWrite(g, null, derivedType, actualValue, actualType, 1);

                                    dest.EndSubItem(token);
                                }
                            }
                            else
                            {
                                dest.WriteFieldHeaderIgnored(WireType.Variant);
                                dest.WriteInt32(subType.FieldNumber + 1);
                                EmitWrite(g, null, derivedType, actualValue, actualType, recursionLevel + 1);
                            }
                            g.Goto(endLabel ?? breakLabel);
                        }
                        g.End();
                    }
                }
                g.End();
                g.MarkLabel(breakLabel);
                if (recursionLevel == 0)
                {
                    dest.WriteFieldHeaderComplete(WireType.Variant);
                    dest.WriteInt32(0);
                }
            }
        }
        static IEnumerable <CodeInstruction> Transpiler(IEnumerable <CodeInstruction> instructions, MethodBase source, ILGenerator il)
        {
            // another new thing, find the desired parameter instead of assuming it will be the same.
            ParameterInfo[] args     = source.GetParameters();
            int             argIndex = -1;

            for (int i = 0; i < args.Length; i++)
            {
                if (args[i].ParameterType.Equals(typeof(Pawn)))
                {
                    argIndex = i + 1; // parrameters are 0 based because of instance.
                    break;
                }
            }

            Label branchFalse = il.DefineLabel(); // since the logic is gettin changed more than I thought, need a new label.

            Label?branchTrue = null;

            int patchPhase = 0;

            foreach (CodeInstruction instruction in instructions)
            {
                // Looking for the ldnull instruction to add a label to it.
                if (patchPhase == 1 && instruction.opcode.Equals(OpCodes.Ldnull))
                {
                    instruction.labels.Add(branchFalse);

                    patchPhase = 2;
                }

                // The first branch we find is the one to remember.  This is also the insertion point...
                if (patchPhase == 0 && instruction.opcode.Equals(OpCodes.Brtrue_S))
                {
                    branchTrue = instruction.operand as Label?;

                    // If the inventory isn't set to unload mode, short circuit and jump to return null path...
                    yield return(new CodeInstruction(OpCodes.Brfalse, branchFalse));

                    // load the arg which is the pawn.
                    yield return(new CodeInstruction(OpCodes.Ldarg, argIndex));

                    // load call to see if the pawn has anything they can drop according to loadout/holdtracker.
                    yield return(new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(Utility_HoldTracker), "HasAnythingForDrop")));

                    // leave the current instruction, branch true, alone...

                    patchPhase = 1;
                }

                yield return(instruction);
            }

            if (patchPhase < 2)
            {
                Log.Warning("CombatExtended :: Harmony-JobGiver_UnloadYourInventory patch failed to complete all its steps");
            }
        }
示例#20
0
        public Label CreateReturnLabel()
        {
            if (!return_label.HasValue)
            {
                return_label = DefineLabel();
            }

            return(return_label.Value);
        }
示例#21
0
        /// <summary>
        /// Generates the IL code for <c>continue</c> construction
        /// </summary>
        /// <param name="This">The [continue] node.</param>
        void IStatementVisitor.Visit(ContinueStatement This)
        {
            Label?label = generator.ContinueLabel;

            if (!label.HasValue)
            {
                throw new AnalizeException("No enclosing loop out of which to continue", This);
            }
            IL.Emit(OpCodes.Br, label.Value);
        }
示例#22
0
 /// <summary>Tests if the code instruction branches</summary>
 /// <param name="code">The <see cref="CodeInstruction"/></param>
 /// <param name="label">The label if the instruction is a branch operation or <see langword="null"/> if not</param>
 /// <returns>True if the instruction branches</returns>
 ///
 public static bool Branches(this CodeInstruction code, out Label?label)
 {
     if (branchCodes.Contains(code.opcode))
     {
         label = (Label)code.operand;
         return(true);
     }
     label = null;
     return(false);
 }
        /*
         * private VariableReference BinaryOp(BinaryExpression binaryOp, OpCode oper, XzaarType tempVariableType)
         * {
         *  var left = Visit(binaryOp.Left) as VariableReference;
         *  var right = Visit(binaryOp.Right) as VariableReference;
         *  var createTempVariableLeft = !(oper == OpCode.CmpEq || oper == OpCode.CmpGt || oper == OpCode.CmpLt || oper == OpCode.CmpGte || oper == OpCode.CmpLte);
         *  var createTempVariableRight = createTempVariableLeft;
         *  if (!createTempVariableLeft && left is FieldReference) createTempVariableLeft = true;
         *  if (!createTempVariableLeft && right is FieldReference) createTempVariableRight = true;
         *  return BinaryOp(left, right, oper, tempVariableType, createTempVariableLeft, createTempVariableRight); // true, true
         * }
         *
         * private VariableReference BinaryOp(VariableReference left, VariableReference right, OpCode oper, XzaarType tempVariableType, bool createTempVariableLeft, bool createTempVariableRight)
         * {
         *  var lv = left;
         *  var rv = right;
         *
         *  if (left == null || right == null)
         *  {
         *      insideBinaryOperation = false;
         *      return null;
         *  }
         *
         *  if (createTempVariableLeft) lv = TempVariable(left.Type);
         *  if (createTempVariableRight) rv = TempVariable(right.Type);
         *  var cv = TempVariable(tempVariableType);
         *  if (createTempVariableLeft)
         *  {
         *      var fRef = left as FieldReference;
         *      if (fRef != null)
         *      {
         *          ctx.AddInstruction(left.ArrayIndex != null
         *              ? Instruction.Create(OpCode.StructGet, lv, fRef.Instance, fRef, left.ArrayIndex as VariableReference)
         *              : Instruction.Create(OpCode.StructGet, lv, fRef.Instance, fRef));
         *      }
         *      else
         *          ctx.AddInstruction(Instruction.Create(OpCode.Assign, lv, left));
         *  }
         *  if (createTempVariableRight)
         *  {
         *      var fRef = right as FieldReference;
         *      if (fRef != null)
         *      {
         *          ctx.AddInstruction(right.ArrayIndex != null
         *              ? Instruction.Create(OpCode.StructGet, rv, fRef.Instance, fRef, right.ArrayIndex as VariableReference)
         *              : Instruction.Create(OpCode.StructGet, rv, fRef.Instance, fRef));
         *      }
         *      else
         *          ctx.AddInstruction(Instruction.Create(OpCode.Assign, rv, right));
         *  }
         *  ctx.AddInstruction(Instruction.Create(oper, cv, lv, rv));
         *  insideBinaryOperation = false;
         *  return cv; // return the temp variable we used to return the result of the comparison
         * }
         */

        public object Visit(IfElseExpression ifElse)
        {
            var il   = ctx.GetILGenerator();
            var test = Visit(ifElse.Test);

            TryLoadReference(test, il);

            // 1. create temp variable
            var tempVariable = ctx.CurrentMethod.DefineVariable(typeof(bool));

            // 2. assign temp variable with value
            il.StoreInLocal(tempVariable);

            // 3. load temp variable
            il.LoadLocal(tempVariable);

            // 4. create a label <end_label> that we want to mark last
            var endOfTrue = il.DefineLabel();

            // 5. brfalse.s <end_label> ---- branch to end label
            il.BranchIfFalse(endOfTrue);

            // 6. Visit IfTrue
            if (ifElse.IfTrue != null)
            {
                Visit(ifElse.IfTrue);
            }

            Label?endOfFalse = null;

            if (ifElse.IfFalse != null)
            {
                // if we do have an 'else'
                // then we want to branch out to end of conditional

                endOfFalse = il.DefineLabel();
                il.BranchToShortForm(endOfFalse.Value);
            }

            // 8. Mark label here
            il.MarkLabel(endOfTrue);


            // 9. Visit IfFalse (if not null)
            if (ifElse.IfFalse != null)
            {
                Visit(ifElse.IfFalse);

                // 10. mark the endOfFalse label
                // ReSharper disable once PossibleInvalidOperationException
                il.MarkLabel(endOfFalse.Value);
            }

            return(true);
        }
示例#24
0
        protected void ImplementGetPrimitive(Member[] primitiveMember, FieldInstance[] f_primitives, FieldInstance[] f_nullFlags)
        {
            MethodInstance template_m_getPrimitive = new MethodInstance(null, typeof(RootCacheValue), typeof(Object), "GetPrimitive", typeof(int));

            IMethodVisitor mv = VisitMethod(template_m_getPrimitive);

            if (f_primitives.Length > 0)
            {
                Label   l_default    = mv.NewLabel();
                Label[] l_primitives = new Label[f_primitives.Length];
                for (int primitiveIndex = 0, size = f_primitives.Length; primitiveIndex < size; primitiveIndex++)
                {
                    l_primitives[primitiveIndex] = mv.NewLabel();
                }

                mv.LoadArg(0);
                mv.Switch(0, l_primitives.Length - 1, l_default, l_primitives);

                for (int primitiveIndex = 0, size = f_primitives.Length; primitiveIndex < size; primitiveIndex++)
                {
                    FieldInstance f_primitive = f_primitives[primitiveIndex];
                    FieldInstance f_nullFlag  = f_nullFlags[primitiveIndex];

                    mv.Mark(l_primitives[primitiveIndex]);

                    Label?l_fieldIsNull = null;

                    if (f_nullFlag != null)
                    {
                        l_fieldIsNull = mv.NewLabel();
                        // only do something if the field is non-null
                        mv.GetThisField(f_nullFlag);
                        mv.IfZCmp(CompareOperator.NE, l_fieldIsNull.Value);
                    }
                    mv.GetThisField(f_primitive);
                    mv.ValueOf(f_primitive.Type.Type);
                    mv.ReturnValue();

                    if (f_nullFlag != null)
                    {
                        mv.Mark(l_fieldIsNull.Value);
                        mv.PushNull();
                    }
                    mv.ReturnValue();
                }
                mv.Mark(l_default);
            }
            mv.ThrowException(typeof(ArgumentException), "Given relationIndex not known");
            mv.PushNull();
            mv.ReturnValue();
            mv.EndMethod();
        }
示例#25
0
        protected override void Open()
        {
            base.Open();

            _window          = new ApcWindow();
            _window.OnClose += Close;
            _window.OpenCentered();

            _breakerButton            = _window.BreakerButton;
            _breakerButton.OnPressed += _ => SendMessage(new ApcToggleMainBreakerMessage());

            _externalPowerStateLabel = _window.ExternalPowerStateLabel;
            _chargeBar = _window.ChargeBar;
        }
示例#26
0
        public override void _Ready()
        {
            label    = GetNode <Label>("Label");
            lineEdit = GetNode <ReactiveLineEdit>("LineEdit");

            lineEdit.Text
            .Subscribe(x => label.Text = x)
            .DisposeWith(this);

            lineEdit.Text
            .Where(x => x == "bye")
            .Take(1)
            .Delay(TimeSpan.FromSeconds(0.2), TimeBasedScheduler.Inherit)
            .Subscribe(_ => QueueFree())
            .DisposeWith(this);
        }
示例#27
0
        public ShowCardUI(FluxxVMData model, ActionContainer actionContainer, KeeperContainer keeperContainer, EnumShowCategory category)
        {
            BindingContext = actionContainer;
            switch (category)
            {
            case EnumShowCategory.MainScreen:
                Text    = "Card Information";
                _detail = model.CardDetail;
                break;

            case EnumShowCategory.CurrentAction:
                Text    = "Current Card Information";
                _detail = actionContainer.CurrentDetail;
                break;

            case EnumShowCategory.MainAction:
                SetBinding(TextProperty, new Binding(nameof(ActionContainer.ActionFrameText)));
                _detail = actionContainer.ActionDetail;
                break;

            case EnumShowCategory.KeeperScreen:
                Text    = "Current Card Information";
                _detail = keeperContainer.CardDetail;
                break;

            default:
                throw new BasicBlankException("Category Not Found");
            }
            _detail !.Card = this;
            Grid tempGrid = new Grid();

            SetUpMarginsOnParentControl(tempGrid); //i think.
            AddAutoColumns(tempGrid, 1);
            AddLeftOverColumn(tempGrid, 1);
            _graphics   = new CardGraphicsXF();
            _label      = GetDefaultLabel();
            _label.Text = _detail.CurrentCard.Description; //no wrap unfortunately.
            _graphics.SendSize("", _detail.CurrentCard);
            AddControlToGrid(tempGrid, _graphics, 0, 0);
            _label.Margin = new Thickness(10, 3, 5, 3);
            AddControlToGrid(tempGrid, _label, 0, 1);
            Grid grid = new Grid();

            grid.Children.Add(ThisDraw);
            grid.Children.Add(tempGrid);
            Content = grid;
        }
示例#28
0
        public static Dictionary <string, object> GenerateProperties(FieldType f, Label?l, Caption?c, Search?s, Match?m, Web?w, Highlight?h, Require?r, DateTimeDefault?d)
        {
            var properties = new Dictionary <string, object>
            {
                [PropertyName.SType.GetEnumStringValue()] = (int)f,
                [PropertyName.Label.GetEnumStringValue()] = LabelMapperValue[l ?? Label.Min],
            };

            CaptionMapperValue[c ?? Caption.Missing](properties);
            SearchMapperValue[s ?? Search.Missing](properties);
            MatchMapperValue[m ?? Match.Missing](properties);
            WebMapperValue[w ?? Web.Missing](properties);
            HighlightMapperValue[h ?? Highlight.Missing](properties);
            RequireMapperValue[r ?? Require.Missing](properties);
            DefaultDateMapper[d ?? DateTimeDefault.Missing](properties);
            return(properties);
        }
示例#29
0
        public static IEnumerable <CodeInstruction> Transpiler(IEnumerable <CodeInstruction> instructions)
        {
            var          instructionList = instructions.ToList();
            var          TryGetValue     = AccessTools.Method(typeof(ToolExtensions), "TryGetValue", new Type[] { typeof(ToolComp), typeof(ToolType), typeof(float).MakeByRefType() });
            var          NoToolWorkSpeed = AccessTools.Method(typeof(Utility), nameof(Utility.NoToolWorkSpeed));
            LocalBuilder val             = null;
            Label?       brLabel         = null;

            for (int i = 0; i < instructionList.Count; i++)
            {
                var instruction = instructionList[i];
                if (instruction.Calls(TryGetValue))
                {
                    for (int j = 1; j < i; j++)
                    {
                        if (instructionList[i - 1].operand is LocalBuilder builder && builder.LocalType == typeof(float))
                        {
                            val = builder;
                            break;
                        }
                    }
                    var nextInstruction = instructionList[i + 1];
                    if (!nextInstruction.Branches(out brLabel))
                    {
                        Log.Error("ST_BaseMessage".Translate() + "ST_Error_Harmony_MapToolTracker".Translate());
                        break;
                    }
                }
                if (brLabel.HasValue && instruction.labels.Contains(brLabel.Value))
                {
                    Log.Warning("ST_BaseMessage".Translate() + "ST_Error_Harmony_MapToolTracker".Translate());
                }
                if (instruction.IsLdloc(val) && instructionList[i + 1].LoadsConstant(1f) && instructionList[i + 2].Branches(out _))
                {
                    instructionList.RemoveAt(i + 1);
                    instructionList.InsertRange(i + 1, new List <CodeInstruction>()
                    {
                        new CodeInstruction(OpCodes.Ldarg_1, null),
                        new CodeInstruction(OpCodes.Call, NoToolWorkSpeed),
                    });
                    break;
                }
            }
            return(instructionList);
        }
示例#30
0
        private static IEnumerable <CodeInstruction> Transpiler(IEnumerable <CodeInstruction> instructions)
        {
            List <CodeInstruction> instructionList = instructions.ToList();
            bool  foundLabel  = false;
            bool  foundBounds = false;
            Label?label       = null;

            for (int i = 0; i < instructionList.Count; i++)
            {
                if (!foundLabel &&
                    instructionList[i].operand is Label operandLabel &&
                    instructionList[i].operand.GetHashCode() == 0)
                {
                    foundLabel = true;

                    label = operandLabel;
                }

                if (!foundBounds &&
                    label.HasValue &&
                    instructionList[i].opcode == OpCodes.Callvirt &&
                    ((MethodInfo)instructionList[i].operand).Name == "get_bounds")
                {
                    foundBounds = true;

                    instructionList.Insert(i - 1, new CodeInstruction(OpCodes.Ldloc_1));
                    instructionList.Insert(i, new CodeInstruction(OpCodes.Call, FakeNoteHelper._boundsNullCheck));
                    instructionList.Insert(i + 1, new CodeInstruction(OpCodes.Brtrue_S, label.Value));
                }
            }

            if (!foundLabel)
            {
                NoodleLogger.Log("Failed to find br to IL_0134!", IPA.Logging.Logger.Level.Error);
            }

            if (!foundBounds)
            {
                NoodleLogger.Log("Failed to find callvirt to get_bounds!", IPA.Logging.Logger.Level.Error);
            }

            return(instructionList.AsEnumerable());
        }
示例#31
0
文件: codegen.cs 项目: blinds52/mono
		public Label CreateReturnLabel ()
		{
			if (!return_label.HasValue)
				return_label = DefineLabel ();

			return return_label.Value;
		}
示例#32
0
		/// <summary>
		/// Default case in the by-number resolution switch
		/// </summary>
		private void EmitDefaultCase()
		{
			Label else_label = il.DefineLabel();
			this.minArgOverloadTypeResolutionLabel = il.DefineLabel();

			// IF (stack.ArgCount > <max param count>) THEN
			stack.EmitLoad(il);
			il.Emit(OpCodes.Ldfld, Fields.PhpStack_ArgCount);
			il.LdcI4(maxArgCount);
			il.Emit(OpCodes.Bge, else_label);

			EmitMissingParameterCountHandling(minArgOverloadTypeResolutionLabel.Value);

			// ELSE
			il.MarkLabel(else_label);
			
			int max_mandatory_arg_count;
			List<Overload> vararg_overloads = GetVarArgOverloads(out max_mandatory_arg_count);

			// do we have any vararg overloads?
			if (vararg_overloads != null)
			{
				// load fixed arguments from stack to valLocals and refLocals locals
				BitArray aliases = EmitLoadArguments(max_mandatory_arg_count, vararg_overloads, false);

				Label callSwitch = il.DefineLabel();
				List<LocalBuilder[]> formalOverloadParams = new List<LocalBuilder[]>();

				// bestOverload = -1
				LocalBuilder bestOverload = il.DeclareLocal(Types.Int[0]);
				il.LdcI4(-1);
				il.Stloc(bestOverload);

				// bestStrictness = Int32.MaxValue
				LocalBuilder bestStrictness = il.DeclareLocal(typeof(ConversionStrictness));
				il.LdcI4(Int32.MaxValue);
				il.Stloc(bestStrictness);


				for (int i = 0; i < vararg_overloads.Count; i++)
				{
					Label jump_on_error = il.DefineLabel();
					Overload current_overload = vararg_overloads[i];

					BitArray overload_aliases;
					if (current_overload.MandatoryParamCount < max_mandatory_arg_count)
					{
						overload_aliases = new BitArray(aliases);
						overload_aliases.Length = current_overload.MandatoryParamCount;
					}
					else 
						overload_aliases = aliases;

					// convert mandatory parameters
					// strictness_i = ImplExactMatch;
					LocalBuilder overloadStrictness = il.GetTemporaryLocal(typeof(int), false);
					il.LdcI4(0); // ConversionStrictness.ImplExactMatch
					il.Stloc(overloadStrictness);

					// alloc local variables
					LocalBuilder[] formals = new LocalBuilder[current_overload.ParamCount];
					formalOverloadParams.Add(formals);
					// convert parameters and tests after conversion
					EmitConversions(overload_aliases, current_overload, jump_on_error, overloadStrictness, formals, false);

					// load remaining arguments and construct the params array
					EmitLoadRemainingArgs(current_overload.MandatoryParamCount, 
						current_overload.Parameters[current_overload.MandatoryParamCount].ParameterType, 
						jump_on_error, formals, overloadStrictness);
					EmitConversionEpilogue(callSwitch, bestOverload, bestStrictness, i, i == (vararg_overloads.Count - 1), overloadStrictness);
	
					// reuse locals
					il.ReturnTemporaryLocal(overloadStrictness);
					il.MarkLabel(jump_on_error);
				}

				// stack.RemoveFrame
				if (!emitParentCtorCall)
				{
					stack.EmitLoad(il);
					il.Emit(OpCodes.Call, Methods.PhpStack.RemoveFrame);
				}

				// call the best overload
				EmitBestOverloadSelection(vararg_overloads, callSwitch, bestOverload, bestStrictness, formalOverloadParams);
			}
			else 
				EmitMoreParameterCountHandling(caseLabels[caseLabels.Length - 1]);
			// END IF;
		}
示例#33
0
 public ClrCodegen(ILGenerator body, Label targetLabel, bool onTrue) : this(body)
 {
     _targetLabel = targetLabel;
     _onTrue = onTrue;
 }
示例#34
0
文件: Gen.cs 项目: josiahdj/SDFCalc
		private bool generated; // Invariant: generated implies label.HasValue

		public Gen(Action generate) {
			this.generate = generate;
			label = null;
			generated = false;
		}
示例#35
0
文件: Gen.cs 项目: josiahdj/SDFCalc
		// A Generate object has a unique label
		public Label GetLabel(ILGenerator ilg) {
			if (!label.HasValue) {
				label = ilg.DefineLabel();
			}
			return label.Value;
		}