converts a for loop into a context manager wrapped around a for loop
    when access to the `loop` variable has been detected in the for loop body
352877
def mangle_mako_loop(node, printer):
    
    loop_variable = LoopVariable()
    node.accept_visitor(loop_variable)
    if loop_variable.detected:
        node.nodes[-1].has_loop_context = True
        match = _FOR_LOOP.match(node.text)
        if match:
            printer.writelines(
                    'loop = __M_loop._enter(%s)' % match.group(2),
                    'try:'
                    #'with __M_loop(%s) as loop:' % match.group(2)
            )
            text = 'for %s in loop:' % match.group(1)
        else:
            raise SyntaxError("Couldn't apply loop context: %s" % node.text)
    else:
        text = node.text
    return text
252373
def _at_dump_context(self, calculator, rule, scope, block):
        
        sys.stderr.write("%s\n" % repr(rule.namespace._variables))
659954
function process( $tpl, &$textElements, $functionName, $functionChildren, $functionParameters, $functionPlacement, $rootNamespace, $currentNamespace )
    {
        /*
         * Check function parameters
         */

        $loop = new eZTemplateLoop( eZTemplateForFunction::FUNCTION_NAME,
                                    $functionParameters, $functionChildren, $functionPlacement,
                                    $tpl, $textElements, $rootNamespace, $currentNamespace );

        if ( !$loop->initialized() )
            return;

        $loop->parseScalarParamValue( 'first_val', $firstVal, $firstValIsProxy );
        $loop->parseScalarParamValue( 'last_val',  $lastVal,  $lastValIsProxy  );

        if ( $firstValIsProxy || $lastValIsProxy )
        {
            $tpl->error( eZTemplateForFunction::FUNCTION_NAME,
                         "Proxy objects ({section} loop iterators) cannot be used to specify the range \n" .
                         "(this will lead to indefinite loops in compiled mode).\n" .
                         "Please explicitly dereference the proxy object like this: \$current_node.item." );
            return;
        }

        $loop->parseParamVarName( 'loop_var' , $loopVarName );

        if ( $firstVal === null || $lastVal === null || !$loopVarName )
        {
            $tpl->error( eZTemplateForFunction::FUNCTION_NAME, "Wrong arguments passed." );
            return;
        }

        if ( !is_numeric( $firstVal ) || !is_numeric( $lastVal ) )
        {
            $tpl->error( eZTemplateForFunction::FUNCTION_NAME, "Both 'from' and 'to' values can only be numeric." );
            return;
        }

        $loop->initLoopVariable( $loopVarName );

        /*
         * Everything is ok, run the 'for' loop itself
         */
        for ( $i = $firstVal; $firstVal < $lastVal ? $i <= $lastVal : $i >= $lastVal; )
        {
            // set loop variable
            $tpl->setVariable( $loopVarName, $i, $rootNamespace );

            $loop->setSequenceVar(); // set sequence variable (if specified)
            $loop->processDelimiter();
            $loop->resetIteration();

            if ( $loop->processChildren() )
                break;

            // increment loop variable here for delimiter to be processed correctly
            $firstVal < $lastVal ? $i++ : $i--;

            $loop->incrementSequence();
        } // for

        $loop->cleanup();
    }
571224
private void checkLoopInvariant(String msg, Stmt.Loop stmt, Context context) {
		//
		Tuple<WyilFile.Expr> loopInvariant = stmt.getInvariant();
		LocalEnvironment environment = context.getEnvironment();
		WyilFile.Decl.FunctionOrMethod declaration = (WyilFile.Decl.FunctionOrMethod) environment
				.getParent().enclosingDeclaration;
		// Construct argument to invocation
		Tuple<WyilFile.Decl.Variable> localVariables = determineUsedVariables(stmt.getInvariant());
		Expr[] arguments = new Expr[localVariables.size()];
		for (int i = 0; i != arguments.length; ++i) {
			WyilFile.Decl.Variable var = localVariables.get(i);
			arguments[i] = new Expr.VariableAccess(environment.read(var));
		}
		//
		for (int i = 0; i != loopInvariant.size(); ++i) {
			WyilFile.Expr clause = loopInvariant.get(i);
			Name ident = convert(declaration.getQualifiedName(), "_loopinvariant_" + clause.getIndex(), declaration.getName());
			Expr macroCall = new Expr.Invoke(null, ident, null, arguments);
			context.emit(new VerificationCondition(msg, context.assumptions, macroCall,
					clause.getParent(WyilFile.Attribute.Span.class)));
		}
	}
1077923
public static Map<String, Object> findFreeMarkerContextVariables(Variables variables, String... varNames)
    {
        Map<String, Object> results = new HashMap<>();

        for (String varName : varNames)
        {
            WindupVertexFrame payload = null;
            try
            {
                payload = Iteration.getCurrentPayload(variables, null, varName);
            }
            catch (IllegalStateException | IllegalArgumentException e)
            {
                // oh well
            }

            if (payload != null)
            {
                results.put(varName, payload);
            }
            else
            {
                Iterable<? extends WindupVertexFrame> var = variables.findVariable(varName);
                if (var != null)
                {
                    results.put(varName, var);
                }
            }
        }
        return results;
    }
319669
def bind(self, context) -> None:
        

        # make a computation context based on the enclosing context.
        self.__computation_context = ComputationContext(self, context)

        # re-bind is not valid. be careful to set the computation after the data item is already in document.
        for variable in self.variables:
            assert variable.bound_item is None
        for result in self.results:
            assert result.bound_item is None

        # bind the variables
        for variable in self.variables:
            self.__bind_variable(variable)

        # bind the results
        for result in self.results:
            self.__bind_result(result)
460607
function (loopcount) {
			this.writeDebug('_createLocationVariables',arguments);
			var value;
			locationData = {};

			for (var key in locationset[loopcount]) {
				if (locationset[loopcount].hasOwnProperty(key)) {
					value = locationset[loopcount][key];

					if (key === 'distance' || key === 'altdistance') {
						value = this.roundNumber(value, 2);
					}

					locationData[key] = value;
				}
			}
		}
131803
def for_context(context)
      contexts = hash.keys.select { |ckey| context.matches?([ckey]) }
      contexts.map { |exc| hash[exc] }
    end
263190
function LoopStopInjector() {

    var t = {};

    t.inject = inject;

    return t;

    /**
     * This method is for struggle with some possible infinite loops.
     *
     * @public
     * @param {String} code The source code.
     */
    function inject(code) {

        var LOOP_CHECK = 'if (LoopStopManager.shouldStopExecution(%d)) break; ';
        var LOOP_EXIT = '\nLoopStopManager.exitedLoop(%d);\n';

        var loopId = 1;
        var patches = [];

        var loopStatements = ["ForOfStatement",
                              "ForStatement",
                              "ForInStatement",
                              "WhileStatement",
                              "DoWhileStatement"];

        esprima.parse(code, { range: true }, function(node) {

            var isItLoopStatement = loopStatements.indexOf(node.type) != -1;

            if (isItLoopStatement) {

                var start = 1 + node.body.range[0];
                var end = node.body.range[1];
                var prolog = LOOP_CHECK.replace('%d', loopId);
                var epilog = '';

                if (node.body.type !== 'BlockStatement') {

                    // `while(1) doThat()` becomes `while(1) {doThat()}`
                    prolog = '{' + prolog;
                    epilog = '}';
                    --start;

                }

                patches.push({ pos: start, str: prolog });
                patches.push({ pos: end, str: epilog });
                patches.push({ pos: node.range[1] + 1, str: LOOP_EXIT.replace('%d', loopId) });

                loopId++;

            }

        });

        patches.sort(function (a, b) { return b.pos - a.pos }).forEach(function (patch) {

            code = code.slice(0, patch.pos) + patch.str + code.slice(patch.pos);

        });

        return code;

    }

}
339172
function processValuesFromContext(node, params, msg, varList) {
                let pMsg = {};
                Object.assign(pMsg, params);
                varList.forEach((varItem) => {
                    if (varItem.type === undefined || params[varItem.type] === undefined) {
                        pMsg[varItem.name] = params[varItem.name];
                    } else if (params[varItem.type] === 'flow' || params[varItem.type] === 'global') {
                        pMsg[varItem.name] = RED.util.evaluateNodeProperty(params[varItem.name], params[varItem.type], node, msg);
                        pMsg[varItem.type] = params[varItem.type];
                        console.log('Inside flow or global');
                        console.log(varItem.name + ' - - ' + pMsg[varItem.name]);
                    } else {
                        pMsg[varItem.name] = params[varItem.name];
                        pMsg[varItem.type] = params[varItem.type];
                    }
                });
                return pMsg;
            }
685113
function(context) {
      var varName,
          localVars = [];
      for (varName in context) {
        localVars.push('var ' + varName + ' = context.' + varName + ';');
      }
      return localVars.join('\n');
    }
1088245
def resolve(self, var, context):
        """"""
        if var is None:
            return var
        if var[0] in ('"', "'") and var[-1] == var[0]:
            return var[1:-1]
        else:
            return template.Variable(var).resolve(context)
415695
def _handle_for(self, node, scope, ctxt, stream):
        
        self._dlog("handling for")
        if node.init is not None:
            # perform the init
            self._handle_node(node.init, scope, ctxt, stream)

        while node.cond is None or self._handle_node(node.cond, scope, ctxt, stream):
            if node.stmt is not None:
                try:
                    # do the for body
                    self._handle_node(node.stmt, scope, ctxt, stream)
                except errors.InterpBreak as e:
                    break
                
                # we still need to interpret the "next" statement,
                # so just pass
                except errors.InterpContinue as e:
                    pass

            if node.next is not None:
                # do the next statement
                self._handle_node(node.next, scope, ctxt, stream)
239632
def variable_matrix(
    variables: VarType, parent: str = None, iterator: str = "product"
) -> Iterable[Dict[str, YamlValue]]:
    
    _iters: Dict[str, Callable] = {"product": product, "zip": zip}
    _special_keys: Dict[str, Callable[[VarType, Any], Iterable[VarMatrix]]] = {
        "zip": iterator_zip,
        "product": iterator_product,
        "arange": iterator_arange,
        "chain": iterator_chain,
        "append": iterator_chain,
        "cycle": iterator_cycle,
        "repeat": iterator_cycle,
    }

    if isinstance(variables, dict):
        key_vars: List[List[Dict[str, YamlValue]]] = []

        # Handling of specialised iterators
        for key, function in _special_keys.items():
            if variables.get(key):
                item = variables[key]
                assert item is not None
                for val in function(item, parent):
                    key_vars.append(val)

                del variables[key]

        for key, value in variables.items():
            key_vars.append(list(variable_matrix(value, key, iterator)))

        logger.debug("key vars: %s", key_vars)

        # Iterate through all possible products generating a dictionary
        for i in _iters[iterator](*key_vars):
            logger.debug("dicts: %s", i)
            yield combine_dictionaries(i)

    # Iterate through a list of values
    elif isinstance(variables, list):
        for item in variables:
            yield from variable_matrix(item, parent, iterator)

    # Stopping condition -> we have either a single value from a list
    # or a value had only one item
    else:
        assert parent is not None
        yield {parent: variables}
1315171
def _detect_loop(self):
        
        for source, dests in self.flowtable.items():
            if source in dests:
                raise conferr('Loops detected: %s --> %s' % (source, source))
425777
def _resolve_looppart(parts, assign_path, context):
    """"""
    assign_path = assign_path[:]
    index = assign_path.pop(0)
    for part in parts:
        if part is util.Uninferable:
            continue
        if not hasattr(part, "itered"):
            continue
        try:
            itered = part.itered()
        except TypeError:
            continue
        for stmt in itered:
            index_node = nodes.Const(index)
            try:
                assigned = stmt.getitem(index_node, context)
            except (
                AttributeError,
                exceptions.AstroidTypeError,
                exceptions.AstroidIndexError,
            ):
                continue
            if not assign_path:
                # we achieved to resolved the assignment path,
                # don't infer the last part
                yield assigned
            elif assigned is util.Uninferable:
                break
            else:
                # we are not yet on the last part of the path
                # search on each possibly inferred value
                try:
                    yield from _resolve_looppart(
                        assigned.infer(context), assign_path, context
                    )
                except exceptions.InferenceError:
                    break
313643
def p_for_stmt(p):
    
    if len(p) == 8:
        if not isinstance(p[2], node.ident):
            raise_exception(SyntaxError, "Not implemented: for loop", new_lexer)
        p[2].props = "I"  # I= for-loop iteration variable
        p[0] = node.for_stmt(ident=p[2], expr=p[4], stmt_list=p[6])