public override ASTN VisitWhile([NotNull] WhileContext context)
        {
            WhileNode node = new WhileNode(context)
            {
                condition = VisitExpr(context.@while) as ExprNode,
                loop_body = VisitExpr(context.loop) as ExprNode
            };

            return(node);
        }
Exemple #2
0
 public static bool IsContainingContext(WhileContext ctxt, WhileContext maybe_containing_ctxt)
 {
     while (ctxt != maybe_containing_ctxt)
     {
         if (ctxt == null)
         {
             return(false);
         }
         ctxt = ctxt.outer_context as WhileContext;
     }
     return(true);
 }
Exemple #3
0
 public override void ExitWhile([NotNull] WhileContext context)
 {
     base.ExitWhile(context);
     Log("ExitWhile");
     if (phase == Phase.Building)
     {
         symbolTableCreator.ExitWhile(context);
     }
     else
     {
         symbolTableTraverser.ExitWhile(context);
         semanticErrorChecker.ExitWhile(context);
     }
 }
 private void _testWhileContextHelper(int?maximum_iterations = null)
 {
     // TODO: implement missing code dependencies
     with <Session>(this.cached_session(), sess =>
     {
         var i = constant_op.constant(0, name: "i");
         var c = new Func <Tensor, Tensor>(x => gen_math_ops.less(x, 10, name: "c"));
         var b = new Func <Tensor, Tensor>(x => gen_math_ops.add(x, 1, name: "c"));
         control_flow_ops.while_loop(
             c, b, new[] { i }, maximum_iterations);
         foreach (Operation op in sess.graph.get_operations())
         {
             var control_flow_context = op._get_control_flow_context();
             if (control_flow_context != null)
             {
                 self.assertProtoEquals(control_flow_context.to_proto(),
                                        WhileContext.from_proto(
                                            control_flow_context.to_proto()).to_proto());
             }
         }
     });
 }
        public static (Dictionary <string, IVariableV1>, ITensorOrOperation[]) import_scoped_meta_graph_with_return_elements(MetaGraphDef meta_graph_or_file,
                                                                                                                             bool clear_devices  = false,
                                                                                                                             string import_scope = "",
                                                                                                                             Dictionary <string, Tensor> input_map = null,
                                                                                                                             string unbound_inputs_col_name        = "unbound_inputs",
                                                                                                                             string[] return_elements = null)
        {
            var meta_graph_def = meta_graph_or_file;

            if (!string.IsNullOrEmpty(unbound_inputs_col_name))
            {
                foreach (var col in meta_graph_def.CollectionDef)
                {
                    if (col.Key == unbound_inputs_col_name)
                    {
                        throw new NotImplementedException("import_scoped_meta_graph_with_return_elements");
                    }
                }
            }

            // Sets graph to default graph if it's not passed in.
            var graph = ops.get_default_graph();

            // Gathers the list of nodes we are interested in.
            OpList producer_op_list = null;

            if (meta_graph_def.MetaInfoDef.StrippedOpList != null)
            {
                producer_op_list = meta_graph_def.MetaInfoDef.StrippedOpList;
            }
            var input_graph_def = meta_graph_def.GraphDef;

            // Remove all the explicit device specifications for this node. This helps to
            // make the graph more portable.
            if (clear_devices)
            {
                foreach (var node in input_graph_def.Node)
                {
                    node.Device = "";
                }
            }

            var scope_to_prepend_to_names = graph.unique_name("", mark_as_used: false);
            var imported_return_elements  = importer.import_graph_def(input_graph_def,
                                                                      name: scope_to_prepend_to_names,
                                                                      input_map: input_map,
                                                                      producer_op_list: producer_op_list,
                                                                      return_elements: return_elements);

            // Restores all the other collections.
            var variable_objects = new Dictionary <ByteString, IVariableV1>();

            foreach (var col in meta_graph_def.CollectionDef.OrderBy(x => x.Key))
            {
                // Don't add unbound_inputs to the new graph.
                if (col.Key == unbound_inputs_col_name)
                {
                    continue;
                }

                switch (col.Value.KindCase)
                {
                case KindOneofCase.NodeList:
                    foreach (var value in col.Value.NodeList.Value)
                    {
                        var col_op = graph.as_graph_element(ops.prepend_name_scope(value, scope_to_prepend_to_names));
                        graph.add_to_collection(col.Key, col_op);
                    }
                    break;

                case KindOneofCase.BytesList:
                    //var proto_type = ops.get_collection_proto_type(key)
                    if (tf.GraphKeys._VARIABLE_COLLECTIONS.Contains(col.Key))
                    {
                        foreach (var value in col.Value.BytesList.Value)
                        {
                            IVariableV1 variable = null;
                            if (!variable_objects.ContainsKey(value))
                            {
                                var proto = VariableDef.Parser.ParseFrom(value);
                                if (proto.IsResource)
                                {
                                    variable = new ResourceVariable(variable_def: proto, import_scope: scope_to_prepend_to_names);
                                }
                                else
                                {
                                    variable = new RefVariable(variable_def: proto, import_scope: scope_to_prepend_to_names);
                                }
                                variable_objects[value] = variable;
                            }
                            variable = variable_objects[value];
                            graph.add_to_collection(col.Key, variable);
                        }
                    }
                    else
                    {
                        foreach (var value in col.Value.BytesList.Value)
                        {
                            switch (col.Key)
                            {
                            case "cond_context":
                            {
                                var proto       = CondContextDef.Parser.ParseFrom(value);
                                var condContext = new CondContext().from_proto(proto, import_scope);
                                graph.add_to_collection(col.Key, condContext);
                            }
                            break;

                            case "while_context":
                            {
                                var proto        = WhileContextDef.Parser.ParseFrom(value);
                                var whileContext = new WhileContext().from_proto(proto, import_scope);
                                graph.add_to_collection(col.Key, whileContext);
                            }
                            break;

                            default:
                                Console.WriteLine($"import_scoped_meta_graph_with_return_elements {col.Key}");
                                continue;
                            }
                        }
                    }

                    break;

                default:
                    Console.WriteLine($"Cannot identify data type for collection {col.Key}. Skipping.");
                    break;
                }
            }

            var variables = graph.get_collection <IVariableV1>(tf.GraphKeys.GLOBAL_VARIABLES,
                                                               scope: scope_to_prepend_to_names);
            var var_list = new Dictionary <string, IVariableV1>();

            variables.ForEach(v => var_list[ops.strip_name_scope(v.Name, scope_to_prepend_to_names)] = v);

            return(var_list, imported_return_elements);
        }
        public GradLoopState(WhileContext forward_ctxt, GradLoopState outer_grad_state_)
        {
            // Information needed by backprop.
            _unused_exits       = new List <Tensor>();
            _deferred_exits     = new List <Tensor>();
            _forward_loop_exits = list(forward_ctxt.loop_exits);
            pending_exits_count = len(forward_ctxt.loop_exits);

            _outer_grad_state = outer_grad_state_;

            ControlFlowContext outer_forward_ctxt = null;

            if (outer_grad_state_ != null)
            {
                outer_forward_ctxt = outer_grad_state_.forward_context;
            }

            // Add the forward loop counter.
            // with forward_ctxt._graph.as_default():
            Tensor cnt, forward_index;

            {
                if (outer_forward_ctxt != null)
                {
                    outer_forward_ctxt.Enter();
                }
                (cnt, forward_index) = forward_ctxt.AddForwardLoopCounter(outer_grad_state);
                if (outer_forward_ctxt != null)
                {
                    outer_forward_ctxt.Exit();
                }
            }
            _forward_context = forward_ctxt;
            _forward_index   = forward_index;

            // Add the backprop WhileContext, and the backprop loop counter.
            if (outer_grad_state != null)
            {
                // This is a nested loop. Remember the iteration counts for each
                // execution of this inner loop.
                throw new NotImplementedException("GradLoopState");
            }
            else
            {
                if (outer_forward_ctxt != null)
                {
                    outer_forward_ctxt.Enter();
                }
                _grad_context = new WhileContext(
                    maximum_iterations: forward_ctxt.maximum_iterations,
                    parallel_iterations: forward_ctxt.parallel_iterations,
                    back_prop: forward_ctxt.back_prop,
                    swap_memory: forward_ctxt.swap_memory,
                    name: forward_ctxt.Name,
                    grad_state: this);
                _grad_index = _grad_context.AddBackpropLoopCounter(cnt, outer_grad_state);
                if (outer_forward_ctxt != null)
                {
                    outer_forward_ctxt.Exit();
                }
            }
        }
	private ExprContext expr(int _p) {
		ParserRuleContext _parentctx = Context;
		int _parentState = State;
		ExprContext _localctx = new ExprContext(Context, _parentState);
		ExprContext _prevctx = _localctx;
		int _startState = 12;
		EnterRecursionRule(_localctx, 12, RULE_expr, _p);
		int _la;
		try {
			int _alt;
			EnterOuterAlt(_localctx, 1);
			{
			State = 120;
			ErrorHandler.Sync(this);
			switch ( Interpreter.AdaptivePredict(TokenStream,6,Context) ) {
			case 1:
				{
				_localctx = new Call_methodContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;

				State = 68; Match(ID);
				State = 69; Match(T__3);
				State = 70; args_call();
				State = 71; Match(T__4);
				}
				break;
			case 2:
				{
				_localctx = new IfContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 73; Match(IF);
				State = 74; expr(0);
				State = 75; Match(THEN);
				State = 76; expr(0);
				State = 77; Match(ELSE);
				State = 78; expr(0);
				State = 79; Match(FI);
				}
				break;
			case 3:
				{
				_localctx = new WhileContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 81; Match(WHILE);
				State = 82; expr(0);
				State = 83; Match(LOOP);
				State = 84; expr(0);
				State = 85; Match(POOL);
				}
				break;
			case 4:
				{
				_localctx = new BodyContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 87; Match(T__1);
				State = 88; expr_list();
				State = 89; Match(T__2);
				}
				break;
			case 5:
				{
				_localctx = new New_typeContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 91; Match(NEW);
				State = 92; Match(TYPE);
				}
				break;
			case 6:
				{
				_localctx = new IsvoidContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 93; Match(ISVOID);
				State = 94; expr(12);
				}
				break;
			case 7:
				{
				_localctx = new Unary_expContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 95;
				((Unary_expContext)_localctx).op = TokenStream.LT(1);
				_la = TokenStream.LA(1);
				if ( !(_la==T__16 || _la==NOT) ) {
					((Unary_expContext)_localctx).op = ErrorHandler.RecoverInline(this);
				}
				else {
					ErrorHandler.ReportMatch(this);
				    Consume();
				}
				State = 96; expr(8);
				}
				break;
			case 8:
				{
				_localctx = new ParentesisContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 97; Match(T__3);
				State = 98; expr(0);
				State = 99; Match(T__4);
				}
				break;
			case 9:
				{
				_localctx = new IntContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 101; Match(INTEGER);
				}
				break;
			case 10:
				{
				_localctx = new BoolContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 102;
				((BoolContext)_localctx).cons = TokenStream.LT(1);
				_la = TokenStream.LA(1);
				if ( !(_la==TRUE || _la==FALSE) ) {
					((BoolContext)_localctx).cons = ErrorHandler.RecoverInline(this);
				}
				else {
					ErrorHandler.ReportMatch(this);
				    Consume();
				}
				}
				break;
			case 11:
				{
				_localctx = new StringContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 103; Match(STR);
				}
				break;
			case 12:
				{
				_localctx = new AssignContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 104; Match(ID);
				State = 105; Match(T__6);
				State = 106; expr(3);
				}
				break;
			case 13:
				{
				_localctx = new LetContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 107; Match(LET);
				State = 108; attr();
				State = 113;
				ErrorHandler.Sync(this);
				_la = TokenStream.LA(1);
				while (_la==T__17) {
					{
					{
					State = 109; Match(T__17);
					State = 110; attr();
					}
					}
					State = 115;
					ErrorHandler.Sync(this);
					_la = TokenStream.LA(1);
				}
				State = 116; Match(IN);
				State = 117; expr(2);
				}
				break;
			case 14:
				{
				_localctx = new IdContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 119; Match(ID);
				}
				break;
			}
			Context.Stop = TokenStream.LT(-1);
			State = 144;
			ErrorHandler.Sync(this);
			_alt = Interpreter.AdaptivePredict(TokenStream,9,Context);
			while ( _alt!=2 && _alt!=global::Antlr4.Runtime.Atn.ATN.INVALID_ALT_NUMBER ) {
				if ( _alt==1 ) {
					if ( ParseListeners!=null )
						TriggerExitRuleEvent();
					_prevctx = _localctx;
					{
					State = 142;
					ErrorHandler.Sync(this);
					switch ( Interpreter.AdaptivePredict(TokenStream,8,Context) ) {
					case 1:
						{
						_localctx = new MultdivContext(new ExprContext(_parentctx, _parentState));
						PushNewRecursionContext(_localctx, _startState, RULE_expr);
						State = 122;
						if (!(Precpred(Context, 11))) throw new FailedPredicateException(this, "Precpred(Context, 11)");
						State = 123;
						((MultdivContext)_localctx).op = TokenStream.LT(1);
						_la = TokenStream.LA(1);
						if ( !(_la==T__9 || _la==T__10) ) {
							((MultdivContext)_localctx).op = ErrorHandler.RecoverInline(this);
						}
						else {
							ErrorHandler.ReportMatch(this);
						    Consume();
						}
						State = 124; expr(12);
						}
						break;
					case 2:
						{
						_localctx = new SumarestaContext(new ExprContext(_parentctx, _parentState));
						PushNewRecursionContext(_localctx, _startState, RULE_expr);
						State = 125;
						if (!(Precpred(Context, 10))) throw new FailedPredicateException(this, "Precpred(Context, 10)");
						State = 126;
						((SumarestaContext)_localctx).op = TokenStream.LT(1);
						_la = TokenStream.LA(1);
						if ( !(_la==T__11 || _la==T__12) ) {
							((SumarestaContext)_localctx).op = ErrorHandler.RecoverInline(this);
						}
						else {
							ErrorHandler.ReportMatch(this);
						    Consume();
						}
						State = 127; expr(11);
						}
						break;
					case 3:
						{
						_localctx = new CompContext(new ExprContext(_parentctx, _parentState));
						PushNewRecursionContext(_localctx, _startState, RULE_expr);
						State = 128;
						if (!(Precpred(Context, 9))) throw new FailedPredicateException(this, "Precpred(Context, 9)");
						State = 129;
						((CompContext)_localctx).op = TokenStream.LT(1);
						_la = TokenStream.LA(1);
						if ( !((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__13) | (1L << T__14) | (1L << T__15))) != 0)) ) {
							((CompContext)_localctx).op = ErrorHandler.RecoverInline(this);
						}
						else {
							ErrorHandler.ReportMatch(this);
						    Consume();
						}
						State = 130; expr(10);
						}
						break;
					case 4:
						{
						_localctx = new DispatchContext(new ExprContext(_parentctx, _parentState));
						PushNewRecursionContext(_localctx, _startState, RULE_expr);
						State = 131;
						if (!(Precpred(Context, 18))) throw new FailedPredicateException(this, "Precpred(Context, 18)");
						State = 134;
						ErrorHandler.Sync(this);
						_la = TokenStream.LA(1);
						if (_la==T__7) {
							{
							State = 132; Match(T__7);
							State = 133; Match(TYPE);
							}
						}

						State = 136; Match(T__8);
						State = 137; Match(ID);
						State = 138; Match(T__3);
						State = 139; args_call();
						State = 140; Match(T__4);
						}
						break;
					}
					} 
				}
				State = 146;
				ErrorHandler.Sync(this);
				_alt = Interpreter.AdaptivePredict(TokenStream,9,Context);
			}
			}
		}
		catch (RecognitionException re) {
			_localctx.exception = re;
			ErrorHandler.ReportError(this, re);
			ErrorHandler.Recover(this, re);
		}
		finally {
			UnrollRecursionContexts(_parentctx);
		}
		return _localctx;
	}