Exemple #1
0
 public SubroutineInfo(Subroutine routine, FunctionBuildController functionBuilder, IndexReference[] parameterStores, IndexReference objectStore)
 {
     Subroutine      = routine;
     FunctionBuilder = functionBuilder;
     ParameterStores = parameterStores;
     ObjectStore     = objectStore;
 }
Exemple #2
0
        public override Result ForwardDecode <Data, Result, Visitor> (APC pc, Visitor visitor, Data data)
        {
            Label label;

            if (TryGetLabel(pc.Index, out label))
            {
                return(base.ForwardDecode <Data, Result, Visitor> (pc, visitor, data));
            }

            int endOldIndex;

            if (IsBeginOld(pc.Index, out endOldIndex))
            {
                CFGBlock block = Subroutine.InferredBeginEndBijection(pc);
                return(visitor.BeginOld(pc, new APC(block, endOldIndex, pc.SubroutineContext), data));
            }

            int beginOldIndex;

            if (IsEndOld(pc.Index, out beginOldIndex))
            {
                TypeNode endOldType;
                CFGBlock block = Subroutine.InferredBeginEndBijection(pc, out endOldType);
                return(visitor.EndOld(pc, new APC(block, beginOldIndex, pc.SubroutineContext), endOldType, Dummy.Value, Dummy.Value, data));
            }

            return(visitor.Nop(pc, data));
        }
Exemple #3
0
        private int PatchPriorBeginOld(CFGBlock endBlock, int endOldIndex, out CFGBlock beginBlock)
        {
            for (int i = this == endBlock ? endOldIndex - 2 : Count - 1; i >= 0; i--)
            {
                int endOldI;
                if (IsBeginOld(i, out endOldI))
                {
                    this.overridingLabels [i] = BeginOldMask | (uint)endOldIndex;
                    beginBlock = this;
                    Subroutine.AddInferredOldMap(this.Index, i, endBlock, default(TypeNode));
                    return(i);
                }
            }

            IEnumerator <CFGBlock> enumerator = Subroutine.PredecessorBlocks(this).GetEnumerator();

            if (!enumerator.MoveNext())
            {
                throw new InvalidOperationException("missing begin_old");
            }
            int result = PatchPriorBeginOld(endBlock, endOldIndex, enumerator.Current, out beginBlock);

            enumerator.MoveNext();
            return(result);
        }
        }                                           // The subroutine's return handler.

        public SubroutineCatalogItem(Subroutine subroutine, IParameterHandler parameterHandler, IndexReference objectStack, ReturnHandler returnHandler)
        {
            Subroutine       = subroutine;
            ParameterHandler = parameterHandler;
            ObjectStack      = objectStack;
            ReturnHandler    = returnHandler;
        }
Exemple #5
0
        public static void LoadBMS(string file, ref AABase AudioData)
        {
            AAF         = AudioData;               // copy our data into here.
            BMSData     = File.ReadAllBytes(file); // Read the BMS file
            subroutines = new Subroutine[32];      // Initialize subroutine array.
            halts       = new bool[32];
            mutes       = new bool[32];
            updated     = new int[32];

            // mutes[9] = true;
            // mutes[13] = true;

            ChannelManager = new BMSChannelManager();
            bpm            = 1000;                        // Dummy value, should be set by the root track
            ppqn           = 10;                          // Dummmy, ^
            updateTempo();                                // Generate the trick length, also dummy.
            // Initialize first track.
            var root = new Subroutine(ref BMSData, 0x00); // Should always start at 0x000 of our data.

            subroutine_count = 1;
            subroutines[0]   = root; // stuff it into the subroutines array.
            tickTimer        = new Stopwatch();
            Console.WriteLine("start thread?");
            playbackThread = new Thread(new ThreadStart(doPlayback));
            playbackThread.Start(); // go go go
        }
Exemple #6
0
        public override IEnumerable <APC> Predecessors(APC pc)
        {
            if (pc.Index > 0)
            {
                yield return(new APC(pc.Block, pc.Index - 1, pc.SubroutineContext));
            }

            else if (IsSubroutineStart(pc.Block))
            {
                if (!pc.SubroutineContext.IsEmpty())
                {
                    foreach (APC apc in ComputeSubroutinePreContinuation(pc))
                    {
                        yield return(apc);
                    }
                }
            }
            else
            {
                foreach (CFGBlock block in pc.Block.Subroutine.PredecessorBlocks(pc.Block))
                {
                    LispList <Pair <EdgeTag, Subroutine> > diffs = EdgeSubroutinesOuterToInner(block, pc.Block, pc.SubroutineContext);
                    if (diffs.IsEmpty())
                    {
                        yield return(APC.ForEnd(block, pc.SubroutineContext));
                    }
                    else
                    {
                        Subroutine sub  = diffs.Head.Value;
                        var        edge = new Edge <CFGBlock, EdgeTag> (block, pc.Block, diffs.Head.Key);
                        yield return(APC.ForEnd(sub.Exit, pc.SubroutineContext.Cons(edge)));
                    }
                }
            }
        }
Exemple #7
0
        private APC ComputeSubroutinePreContinuation(APC point, out bool hasSinglePredecessor)
        {
            Edge <CFGBlock, EdgeTag> head = point.SubroutineContext.Head;
            bool isExceptionHandlerEdge;
            LispList <Edge <CFGBlock, EdgeTag> >   tail  = point.SubroutineContext.Tail;
            LispList <Pair <EdgeTag, Subroutine> > flist = EdgeSubroutinesOuterToInner(head.From, head.To, out isExceptionHandlerEdge, tail);

            while (flist.Head.Value != this)
            {
                flist = flist.Tail;
            }
            if (flist.Tail.IsEmpty())
            {
                if (isExceptionHandlerEdge && head.From.Count > 1)
                {
                    hasSinglePredecessor = false;
                    return(APC.Dummy);
                }

                hasSinglePredecessor = true;
                return(APC.ForEnd(head.From, tail));
            }
            Pair <EdgeTag, Subroutine> first = flist.Tail.Head;
            Subroutine sub = first.Value;

            hasSinglePredecessor = true;

            return(APC.ForEnd(sub.Exit, point.SubroutineContext.Cons(new Edge <CFGBlock, EdgeTag> (head.From, head.To, first.Key))));
        }
Exemple #8
0
        private LispList <Pair <EdgeTag, Subroutine> > InsertInvariant(CFGBlock from, LispList <Pair <EdgeTag, Subroutine> > list,
                                                                       Method calledMethod, ref TypeNode type,
                                                                       LispList <Edge <CFGBlock, EdgeTag> > context)
        {
            IMetaDataProvider metadataDecoder = this.SubroutineFacade.MetaDataProvider;

            Property property;

            if (metadataDecoder.IsPropertySetter(calledMethod, out property) &&
                (metadataDecoder.IsAutoPropertyMember(calledMethod) || WithinConstructor(from, context)))
            {
                return(list);
            }

            if (metadataDecoder.IsConstructor(calledMethod))
            {
                type = metadataDecoder.DeclaringType(calledMethod);
            }

            Subroutine invariant = this.SubroutineFacade.GetInvariant(type);

            if (invariant != null)
            {
                var methodCallBlock = from as MethodCallBlock <Label>;
                if (methodCallBlock != null)
                {
                    EdgeTag first = methodCallBlock.IsNewObj ? EdgeTag.AfterNewObj : EdgeTag.AfterCall;
                    return(list.Cons(new Pair <EdgeTag, Subroutine> (first, invariant)));
                }
            }

            return(list);
        }
Exemple #9
0
        private IEnumerable <APC> ComputeSubroutinePreContinuation(APC point)
        {
            Edge <CFGBlock, EdgeTag>             edge = point.SubroutineContext.Head;
            LispList <Edge <CFGBlock, EdgeTag> > tail = point.SubroutineContext.Tail;

            bool isHandlerEdge;
            LispList <Pair <EdgeTag, Subroutine> > diffs = EdgeSubroutinesOuterToInner(edge.From, edge.To, out isHandlerEdge, tail);

            while (diffs.Head.Value != this)
            {
                diffs = diffs.Tail;
            }

            if (diffs.Tail == null)
            {
                if (isHandlerEdge)
                {
                    for (int i = 0; i < edge.From.Count; i++)
                    {
                        yield return(new APC(edge.From, i, tail));
                    }
                }
                else
                {
                    yield return(APC.ForEnd(edge.From, tail));
                }
            }
            else
            {
                Pair <EdgeTag, Subroutine> first = diffs.Tail.Head;
                Subroutine nextSubroutine        = first.Value;
                yield return(APC.ForEnd(nextSubroutine.Exit, point.SubroutineContext.Cons(new Edge <CFGBlock, EdgeTag> (edge.From, edge.To, first.Key))));
            }
        }
Exemple #10
0
 public SubroutineInfo(Subroutine routine, ReturnHandler returnHandler, IndexReference[] parameterStores, IndexReference objectStore)
 {
     Subroutine      = routine;
     ReturnHandler   = returnHandler;
     ParameterStores = parameterStores;
     ObjectStore     = objectStore;
 }
        public void Parse_WithParamtersAndEmptyBody_IsCorrect()
        {
            var subroutine = Subroutine.Parse(new Tokenizer(new Token[]
            {
                Keyword.Function,
                new Identifier("Point"),
                new Identifier("f"),
                Symbol.OpenParenthesis,
                new Identifier("Point"),
                new Identifier("p"),
                Symbol.Commna,
                Keyword.Int,
                new Identifier("i"),
                Symbol.CloseParenthesis,
                Symbol.OpenCurly,
                Symbol.CloseCurly
            }));

            subroutine.Name.Value.Should().Be("f");
            subroutine.ReturnType.Name.Should().Be("Point");
            subroutine.LocalVaribles.Should().BeEmpty();
            subroutine.Statements.Should().BeEmpty();
            subroutine.Arguments.Should().ContainInOrder(
                new Varible(new VaribleType(new Identifier("Point")), new Identifier("p")),
                new Varible(new VaribleType(Keyword.Int), new Identifier("i"))
                );
        }
Exemple #12
0
        protected void InsertPostConditionEdges(BlockWithLabels <Label> previousBlock, BlockWithLabels <Label> newBlock)
        {
            var methodCallBlock = previousBlock as MethodCallBlock <Label>;

            if (methodCallBlock == null)
            {
                return;
            }

            if (CurrentSubroutine.IsMethod)
            {
                var      methodInfo = CurrentSubroutine as IMethodInfo;
                Property property;
                if (methodInfo != null && MetaDataProvider.IsConstructor(methodInfo.Method) &&
                    MetaDataProvider.IsPropertyGetter(methodCallBlock.CalledMethod, out property) &&
                    MetaDataProvider.IsAutoPropertyMember(methodCallBlock.CalledMethod))
                {
                    return;
                }
            }

            EdgeTag    callTag = methodCallBlock.IsNewObj ? EdgeTag.AfterNewObj : EdgeTag.AfterCall;
            Subroutine ensures = this.SubroutineFacade.GetEnsures(methodCallBlock.CalledMethod);

            CurrentSubroutine.AddEdgeSubroutine(previousBlock, newBlock, ensures, callTag);
        }
Exemple #13
0
        protected void InsertPreConditionEdges(BlockWithLabels <Label> previousBlock, BlockWithLabels <Label> newBlock)
        {
            var methodCallBlock = newBlock as MethodCallBlock <Label>;

            if (methodCallBlock == null || CurrentSubroutine.IsContract || CurrentSubroutine.IsOldValue)
            {
                return;
            }

            if (CurrentSubroutine.IsMethod)
            {
                var      methodInfo = CurrentSubroutine as IMethodInfo;
                Property property;
                if (methodInfo != null && MetaDataProvider.IsConstructor(methodInfo.Method) &&
                    MetaDataProvider.IsPropertySetter(methodCallBlock.CalledMethod, out property) &&
                    MetaDataProvider.IsAutoPropertyMember(methodCallBlock.CalledMethod))
                {
                    return;
                }
            }

            EdgeTag    callTag  = methodCallBlock.IsNewObj ? EdgeTag.BeforeNewObj : EdgeTag.BeforeCall;
            Subroutine requires = this.SubroutineFacade.GetRequires(methodCallBlock.CalledMethod);

            CurrentSubroutine.AddEdgeSubroutine(previousBlock, newBlock, requires, callTag);
        }
        public SubroutineCatalogItem Initiate()
        {
            // Setup the subroutine element.
            Subroutine subroutine = _deltinScript.SubroutineCollection.NewSubroutine(_context.ElementName);

            // Create the rule.
            _subroutineRule = new TranslateRule(_deltinScript, subroutine, _context.RuleName, _context.VariableGlobalDefault);

            // Setup the return handler.
            _actionSet = _subroutineRule.ActionSet
                         .ContainVariableAssigner()
                         .SetThisTypeLinker(_context.TypeLinker)
                         .New(_context.Controller.Attributes.IsRecursive);

            // Create the function builder.
            var controller = _context.Controller;

            // Create the parameter handlers.
            _parameterHandler = controller.CreateParameterHandler(_actionSet, null);

            // If the subroutine is an object function inside a class, create a variable to store the class object.
            if (controller.Attributes.IsInstance)
            {
                _objectStore = _actionSet.VarCollection.Assign(_context.ObjectStackName, true, !controller.Attributes.IsRecursive);

                // Set the objectStore as an empty array if the subroutine is recursive.
                if (controller.Attributes.IsRecursive)
                {
                    // Initialize as empty array.
                    _actionSet.InitialSet().AddAction(_objectStore.SetVariable(Element.EmptyArray()));

                    // Add to assigner with the last of the objectStore stack being the object instance.
                    _context.ContainingType?.AddObjectVariablesToAssigner(_actionSet.ToWorkshop, Element.LastOf(_objectStore.GetVariable()), _actionSet.IndexAssigner);

                    // Set the actionSet.
                    _actionSet = _actionSet.New(Element.LastOf(_objectStore.Get())).PackThis().New(_objectStore.CreateChild(Element.CountOf(_objectStore.Get()) - 1));
                }
                else
                {
                    // Add to assigner with the objectStore being the object instance.
                    _context.ContainingType?.AddObjectVariablesToAssigner(_actionSet.ToWorkshop, _objectStore.GetVariable(), _actionSet.IndexAssigner);

                    // Set the actionSet.
                    _actionSet = _actionSet.New(_objectStore.Get()).PackThis().New(_objectStore);
                }
            }

            _functionBuilder = new WorkshopFunctionBuilder(_actionSet, controller);
            _functionBuilder.ModifySet(a => a.PackThis()); // TODO: is this required?
            _functionBuilder.SetupReturnHandler();
            _parameterHandler.AddParametersToAssigner(_actionSet.IndexAssigner);

            // Done.
            return(Result = new SubroutineCatalogItem(
                       subroutine: subroutine,
                       parameterHandler: _parameterHandler,
                       objectStack: _objectStore,
                       returnHandler: _functionBuilder.ReturnHandler));
        }
Exemple #15
0
        public void EndOldWithoutInstruction(TypeNode nextEndOldType)
        {
            int      endOldIndex = this.overridingLabels.Count;
            CFGBlock beginBlock;

            this.overridingLabels.Add((uint)(EndOldMask | PatchPriorBeginOld(this, endOldIndex, out beginBlock)));
            Subroutine.AddInferredOldMap(this.Index, endOldIndex, beginBlock, nextEndOldType);
        }
Exemple #16
0
 private APCMap <int> LocalStackMap(Subroutine subroutine)
 {
     if (this.local_stack_depth_cache == null || this.cached_subroutine != subroutine.Id)
     {
         this.local_stack_depth_cache = GetStackDepthMap(subroutine);
         this.cached_subroutine       = subroutine.Id;
     }
     return(this.local_stack_depth_cache);
 }
Exemple #17
0
        private void HashSubroutine(Subroutine subroutine)
        {
            var ilDecoder = this.mDriver.StackLayer.Decoder;

            if (hashedSubroutines.Contains(subroutine))
            {
                return;
            }

            this.hashedSubroutines.Add(subroutine);

            // Hash the name
            this.tw.WriteLine("SUBROUTINE{0} {1}", this.subroutineIdentifier(subroutine), subroutine.Kind);

            // Hash all the blocks
            foreach (var block in subroutine.Blocks)
            {
                this.tw.WriteLine("Block {0}", block.Index);
                this.tw.WriteLine("  Handlers: ");

                // TODO : handlers - we ignore them now, as in Clousot's analysis we do it too!
                this.tw.WriteLine("  Code:");
                foreach (var apc in block.APCs())
                {
                    ilDecoder.ForwardDecode <Unit, Unit, ILHasher>(apc, this.ilHasher, Unit.Value);
                }

                var subroutinesToVisit = new Set <Subroutine>(subroutine.UsedSubroutines());
                var stackCFG           = this.mDriver.StackLayer.Decoder.Context.MethodContext.CFG;

                this.tw.WriteLine("  Successors:");
                foreach (var taggedSucc in subroutine.SuccessorEdgesFor(block))
                {
                    this.tw.Write("({0},{1}", taggedSucc.One, taggedSucc.Two.Index);

                    // The order of successors edges is not deterministic (why?), hence the OrderBy
                    var edgesubs = stackCFG.GetOrdinaryEdgeSubroutines(block, taggedSucc.Two, null).GetEnumerable()
                                   .Select(edgesub => new Tuple <string, Subroutine>(String.Format(" SUBROUTINE{0}({1})", this.subroutineIdentifier(edgesub.Two), edgesub.One), edgesub.Two))
                                   .OrderBy(x => x.Item1);

                    foreach (var edgesub in edgesubs)
                    {
                        this.tw.Write(edgesub.Item1);
                        subroutinesToVisit.Add(edgesub.Item2);
                    }
                    this.tw.Write(") ");
                }
                this.tw.WriteLine();

                // Go recursively
                //foreach (var usedSubroutine in subroutine.UsedSubroutines().OrderBy(s => this.subroutineIdentifier(s)))
                foreach (var usedSubroutine in subroutinesToVisit.OrderBy(s => this.subroutineIdentifier(s)))
                {
                    HashSubroutine(usedSubroutine);
                }
            }
        }
 public TranslateRule(DeltinScript deltinScript, Subroutine subroutine, string name, bool defaultGlobal)
 {
     DeltinScript = deltinScript;
     IsGlobal     = defaultGlobal;
     Name         = name;
     EventType    = RuleEvent.Subroutine;
     Subroutine   = subroutine;
     ActionSet    = new ActionSet(this, null, Actions);
 }
                public Refiner(APC pc, IMethodDriver <Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions> mdriver)
                {
                    Contract.Requires(mdriver != null);

                    this.mdriver    = mdriver;
                    this.subroutine = pc.Block.Subroutine;
                    Contract.Assert(mdriver.MetaDataDecoder != null);
                    this.False = BoxedExpression.ConstBool(0, mdriver.MetaDataDecoder);
                }
Exemple #20
0
        /****************************************************************
         *                       Subroutine Node
         ***************************************************************/

        public Node Subroutine()
        {
            var subroutToken = Expect(TokenCategory.SUBROUTINE);
            var subroutName  = new Identifier()
            {
                AnchorToken = Expect(TokenCategory.IDENTIFIER)
            };

            Expect(TokenCategory.PARENTHESIS_OPEN);
            var args = new ArgumentList();

            if (CurrentToken != TokenCategory.PARENTHESIS_CLOSE)
            {
                args.Add(new Identifier()
                {
                    AnchorToken = Expect(TokenCategory.IDENTIFIER)
                });

                while (CurrentToken == TokenCategory.COMMA)
                {
                    Expect(TokenCategory.COMMA);
                    args.Add(new Identifier()
                    {
                        AnchorToken = Expect(TokenCategory.IDENTIFIER)
                    });
                }
            }
            Expect(TokenCategory.PARENTHESIS_CLOSE);

            var declList = EvaluateDeclarations();
            var stmtList = EvaluateStatements();

            var ret = new Return()
            {
                AnchorToken = Expect(TokenCategory.RETURN)
            };

            if (this.labelCache != null)
            {
                ret.Add(this.labelCache);
                this.labelCache = null;
            }

            var end = new End()
            {
                AnchorToken = Expect(TokenCategory.END)
            };

            var subroutResult = new Subroutine()
            {
                subroutName, args, declList, stmtList, ret, end
            };

            subroutResult.AnchorToken = subroutToken;
            return(subroutResult);
        }
Exemple #21
0
        private int OldStartDepth(Subroutine subroutine)
        {
            Method method = ((IMethodInfo)subroutine).Method;
            int    count  = MetaDataProvider.Parameters(method).Count;

            if (!MetaDataProvider.IsConstructor(method) && !MetaDataProvider.IsStatic(method))
            {
                ++count;
            }
            return(count);
        }
Exemple #22
0
        public MethodSubroutine(SubroutineFacade SubroutineFacade,
                                Method method, Label startLabel,
                                SubroutineWithHandlersBuilder <Label, Handler> builder) : base(SubroutineFacade, startLabel, builder)
        {
            this.method = method;
            IMetaDataProvider metaDataProvider = this.SubroutineFacade.MetaDataProvider;

            builder.BuildBlocks(startLabel, this);
            BlockWithLabels <Label> targetBlock = GetTargetBlock(startLabel);

            Commit();

            TypeNode   type      = metaDataProvider.DeclaringType(method);
            Subroutine invariant = this.SubroutineFacade.GetInvariant(type);

            if (invariant != null && !metaDataProvider.IsConstructor(method) && !metaDataProvider.IsStatic(method))
            {
                AddEdgeSubroutine(Entry, targetBlock, invariant, EdgeTag.Entry);
                Subroutine requires = this.SubroutineFacade.GetRequires(method);
                if (requires != null)
                {
                    AddEdgeSubroutine(Entry, targetBlock, requires, EdgeTag.Entry);
                }
            }
            else
            {
                AddEdgeSubroutine(Entry, targetBlock, this.SubroutineFacade.GetRequires(method), EdgeTag.Entry);
            }

            if (this.blocks_ending_in_return_point == null)
            {
                return;
            }

            Subroutine ensures = this.SubroutineFacade.GetEnsures(method);
            bool       putInvariantAfterExit = !metaDataProvider.IsStatic(method) &&
                                               !metaDataProvider.IsFinalizer(method) && !metaDataProvider.IsDispose(method);

            foreach (var block in this.blocks_ending_in_return_point)
            {
                if (putInvariantAfterExit)
                {
                    AddEdgeSubroutine(block, Exit, invariant, EdgeTag.Exit);
                }
                AddEdgeSubroutine(block, Exit, ensures, EdgeTag.Exit);
            }

            if (ensures != null)
            {
                throw new NotImplementedException();
            }

            this.blocks_ending_in_return_point = null;
        }
        public Subroutine NewSubroutine(string name)
        {
            // Get the next available name.
            name = MetaElement.WorkshopNameFromCodeName(name, Subroutines.Select(sr => sr.Name).ToArray());

            Subroutine newRoutine = new Subroutine(CurrentID, name);

            CurrentID++;
            Subroutines.Add(newRoutine);

            return(newRoutine);
        }
Exemple #24
0
        private APCMap <int> GetStackDepthMap(Subroutine subroutine)
        {
            APCMap <int> result;
            var          key = new TypedKey("stackDepthKey");

            if (!subroutine.TryGetValue(key, out result))
            {
                result = ComputeStackDepthMap(subroutine);
                subroutine.Add(key, result);
            }
            return(result);
        }
Exemple #25
0
        void visit_subroutine(Subroutine m)
        {
            if (m.body == null)
            {
                return;
            }

            m.entry_block  = BasicBlock.entry();
            m.return_block = new BasicBlock();
            m.exit_block   = BasicBlock.exit();

            m.return_block.connect(m.exit_block);

            if (m is Method)
            {
                // ensure out parameters are defined at end of method
                foreach (var param in ((Method)m).get_parameters())
                {
                    if (param.direction == ParameterDirection.OUT)
                    {
                        var param_ma = MemberAccess.simple(param.name, param.source_reference);
                        param_ma.symbol_reference = param;
                        m.return_block.add_node(param_ma);
                    }
                }
            }

            current_block = new BasicBlock();
            m.entry_block.connect(current_block);
            current_block.add_node(m);

            jump_stack.Add(JumpTarget.return_target(m.return_block));
            jump_stack.Add(JumpTarget.exit_target(m.exit_block));

            m.accept_children(this);

            jump_stack.RemoveAt(jump_stack.Count - 1);

            if (current_block != null)
            {
                // end of method body reachable

                if (m.has_result)
                {
                    Report.error(m.source_reference, "missing return statement at end of subroutine body");
                    m.error = true;
                }

                current_block.connect(m.return_block);
            }

            analyze_body(m.entry_block);
        }
Exemple #26
0
        public override bool HasSinglePredecessor(APC point, out APC ifFound)
        {
            if (point.Index > 0)
            {
                ifFound = new APC(point.Block, point.Index - 1, point.SubroutineContext);
                return(true);
            }

            if (IsSubroutineStart(point.Block))
            {
                if (point.SubroutineContext == null)
                {
                    ifFound = APC.Dummy;
                    return(false);
                }

                bool hasSinglePredecessor;
                ifFound = ComputeSubroutinePreContinuation(point, out hasSinglePredecessor);
                return(hasSinglePredecessor);
            }


            CFGBlock onlyOne = null;

            foreach (CFGBlock predecessor in point.Block.Subroutine.PredecessorBlocks(point.Block))
            {
                if (onlyOne != null)
                {
                    ifFound = APC.Dummy;
                    return(false);
                }
                onlyOne = predecessor;
            }
            if (onlyOne == null)
            {
                ifFound = APC.Dummy;
                return(false);
            }

            LispList <Pair <EdgeTag, Subroutine> > list = EdgeSubroutinesOuterToInner(onlyOne, point.Block, point.SubroutineContext);

            if (list.IsEmpty())
            {
                ifFound = APC.ForEnd(onlyOne, point.SubroutineContext);
                return(true);
            }

            var        edge = new Edge <CFGBlock, EdgeTag> (onlyOne, point.Block, list.Head.Key);
            Subroutine sub  = list.Head.Value;

            ifFound = APC.ForEnd(sub.Exit, point.SubroutineContext.Cons(edge));
            return(true);
        }
Exemple #27
0
        public static Subroutine OldEvalPopSubroutine <Local, Parameter, Type, Method, Field, Property, Attribute, Assembly>(
            MethodCache <Local, Parameter, Type, Method, Field, Property, Attribute, Assembly> methodCache,
            Subroutine oldEval
            )
        {
            Debug.Assert(oldEval.StackDelta == 1);
            var sub = new SimpleILCodeProvider <Local, Parameter, Type, Method, Field, Property, Attribute, Assembly>(
                new Instruction[] { Instruction.Pop },
                0).GetSubroutine(methodCache);

            sub.AddEdgeSubroutine(sub.Entry, sub.EntryAfterRequires, oldEval, "oldmanifest");
            return(sub);
        }
Exemple #28
0
        //****************************************************************************************************
		public void Step(Subroutine.Moment pos, int forpos) {
			Namespace cn = InterprEnvironment.Instance.CurrentNamespace;
			VarBase res = cn[m_counter_var];
			if (!res.IsInt())
				throw new CalcException("“ип переменной - счетчика цикла был изменен");
			int resval = (res as IntVar).Val;
			resval++;
			res = new IntVar(resval);
			cn[m_counter_var] = res;
			if (resval > m_end_res.Val)
				pos.GoTo(m_next_pos + 1);
			else
				pos.GoTo(forpos + 1);
		}
Exemple #29
0
        public override sealed void AddEdgeSubroutine(CFGBlock from, CFGBlock to, Subroutine subroutine, EdgeTag tag)
        {
            if (subroutine == null)
            {
                return;
            }

            var key = Pair.From(from, to);

            Sequence <Pair <EdgeTag, Subroutine> > list;

            this.edge_subroutines.TryGetValue(key, out list);
            this.edge_subroutines[key] = list.Cons(Pair.From(tag, subroutine));
        }
Exemple #30
0
 public override IEnumerator <RST> Run(Sandbox sb)
 {
     if (sb.Objects[Name]?.Value is Subroutine sub)             // Subroutine exists, simply add overload
     {
         sub.DefineOverload(Parameters, Body);
     }
     else             // Create new subroutine object and add overload
     {
         var s = new Subroutine(Name);
         sb.Objects[Name] = new RantObject(s);
         s.DefineOverload(Parameters, Body);
     }
     yield break;
 }
Exemple #31
0
        public override sealed void AddEdgeSubroutine(CFGBlock from, CFGBlock to, Subroutine subroutine, EdgeTag tag)
        {
            if (subroutine == null)
            {
                return;
            }

            var key = new Pair <CFGBlock, CFGBlock> (from, to);
            LispList <Pair <EdgeTag, Subroutine> > list;
            var item = new Pair <EdgeTag, Subroutine> (tag, subroutine);

            this.edge_subroutines.TryGetValue(key, out list);
            this.edge_subroutines [key] = list.Cons(item);
        }
Exemple #32
0
        //****************************************************************************************************
		public void Execute(Subroutine.Moment pos) {
			VarBase resb, rese;
			resb = m_begin.Calculate();
			if (!resb.IsInt())
				throw new CalcException("√раницы изменени¤ счетчика должны быть целыми");
			IntVar resbi = resb as IntVar;
			Namespace cn = InterprEnvironment.Instance.CurrentNamespace;
			cn[m_counter_var] = resb;
			rese = m_end.Calculate();
			if (!rese.IsInt())
				throw new CalcException("√раницы изменени¤ счетчика должны быть целыми");
			m_end_res = rese as IntVar;
			if (resbi.Val > m_end_res.Val)
				pos.GoTo(m_next_pos + 1);
			else
				pos.Next();
		}
    public static void Add(Subroutine newlyActive)
    {
        if (!List.Contains(newlyActive))
        {
            List.Add(newlyActive);

            //notify viruses of this
            foreach(IMalware iMal in MalwareList)
            {
                //todo: check for ISubroutineListener instead
                if (iMal is VirusAI)
                {
                    (iMal as VirusAI).OnSubroutineActive(newlyActive);
                }
            }
        }
    }
Exemple #34
0
        public SubCallBlueprint(Interpreter interpreter, Source source, Subroutine subroutine, IEnumerable<Token<TokenType>>[] args) : base(interpreter)
        {
            _subroutine = subroutine;
            if (args == null)
            {
                _args = Enumerable.Empty<TagArg>().ToArray();
            }
            else
            {
                // Insert token arguments into the array, set string args to null.
                _args = args.Select((a, i) => _subroutine.Parameters[i].Item2 == TagArgType.Tokens ? TagArg.FromTokens(a) : null).ToArray();

                // Queue string arguments on the stack.
                for (int i = 0; i < _subroutine.ParamCount; i++)
                {
                    if (_subroutine.Parameters[i].Item2 == TagArgType.Result)
                    {
                        interpreter.PushState(Interpreter.State.CreateDerivedDistinct(source, args[i], interpreter));
                    }
                }
            }
        }
 public void Execute(Subroutine.Moment pos)
 {
     pos.GoTo(m_whilepos);
 }
    private void FireAtEnemy(Vector3 relativePos, Subroutine s)
    {
        if (OrbitScript != null)
            OrbitScript.IsOrbiting = false;

        CooldownRemaining = this.Cooldown;

        Transform t = (Transform)GameObject.Instantiate(this.LazerPrefab, this.LazerStart.position, this.LazerStart.rotation);
        LazerTorpedo lb = t.GetComponent<LazerTorpedo>();

        if (lb != null)
        {
            lb.origin = this;
            lb.FireTorpedo(s);
        }

        Physics.IgnoreCollision(this.GetComponent<Collider>(), t.GetComponent<Collider>(), true);

        StartCoroutine(this.WaitAndStopLaser());
    }
Exemple #37
0
 /// <summary>
 /// Subroutine parameter not guaranteed to be non null
 /// </summary>
 /// <param name="sub"></param>
 public void OnSubroutineActive(Subroutine sub)
 {
     //if you aren't forced, then get the target
     if (!this.IsAggroForced)
         TargetClosestActiveSubroutine();
 }
Exemple #38
0
    public void OnSubroutineInactive(Subroutine sub)
    {
        //keep aggro'd if you have a target, you're forced, and the inactive subroutine isn't the one you're targeting
        if ((this.targetT != null) && this.IsAggroForced && (sub.transform != this.targetT))
            return;

        TargetClosestActiveSubroutine();
    }
 void Awake()
 {
     LockedOnRenderer.enabled = false;
     BoundSubroutine = GetComponent<Subroutine>();
 }
Exemple #40
0
        //****************************************************************************************************
		public void Execute(Subroutine.Moment moment) {
			throw new CalcException("¬ыполнение прервано оператором error");
		}
Exemple #41
0
        //****************************************************************************************************
		public void Execute(Subroutine.Moment pos) {
			pos.GoTo(m_nextpos + 1);
		}
Exemple #42
0
        //****************************************************************************************************
		public void Execute(Subroutine.Moment pos) {
			pos.Return();
		}
Exemple #43
0
 public ControlFlowGraph (Subroutine subroutine, SubroutineFacade methodRepository)
 {
         this.method_subroutine = subroutine;
         this.method_repository = methodRepository;
 }
Exemple #44
0
        //****************************************************************************************************
		public void Execute(Subroutine.Moment pos) {
			pos.Next();
		}
 private void OnCollideWithSubroutine(Subroutine s)
 {
     this.DoAttack(s);
     this.OnVirusDead();
 }