Execute an AstRoot in the current Session with much assertion-checking
@param ast Rapids expression to execute
@param scope ?
@return the result from the Rapids expression
168351
public Val exec(AstRoot ast, AstFunction scope) {
    sanity_check_refs(null);

    // Execute
    Env env = new Env(this);
    env._scope = scope;
    Val val = ast.exec(env);    // Execute
    assert env.sp() == 0;         // Stack balanced at end
    sanity_check_refs(val);
    return val;                 // Can return a frame, which may point to session-shared Vecs
  }
7578
public CompletableFuture<CreateScopeStatus> createScope(final String scope) {
        Exceptions.checkNotNullOrEmpty(scope, "scope");
        try {
            NameUtils.validateScopeName(scope);
        } catch (IllegalArgumentException | NullPointerException e) {
            log.warn("Create scope failed due to invalid scope name {}", scope);
            return CompletableFuture.completedFuture(CreateScopeStatus.newBuilder().setStatus(
                    CreateScopeStatus.Status.INVALID_SCOPE_NAME).build());
        }
        return streamStore.createScope(scope);
    }
855703
private boolean executeQuantifier(int index, Expr.Quantifier expr, CallStack frame) {
		Tuple<Decl.Variable> vars = expr.getParameters();
		if (index == vars.size()) {
			// This is the base case where we evaluate the condition itself.
			RValue.Bool r = executeExpression(BOOL_T, expr.getOperand(), frame);
			boolean q = (expr instanceof Expr.UniversalQuantifier);
			// If this evaluates to true, then we will continue executing the
			// quantifier.
			return r.boolValue() == q;
		} else {
			Decl.Variable var = vars.get(index);
			RValue.Array range = executeExpression(ARRAY_T, var.getInitialiser(), frame);
			RValue[] elements = range.getElements();
			for (int i = 0; i != elements.length; ++i) {
				frame.putLocal(var.getName(), elements[i]);
				boolean r = executeQuantifier(index + 1, expr, frame);
				if (!r) {
					// early termination
					return r;
				}
			}
			return true;
		}
	}
1095736
private boolean scopeContainsInstance(GraqlCompute query) {
        if (scopeTypeLabels(query).isEmpty()) return false;
        List<Pattern> checkSubtypes = scopeTypeLabels(query).stream()
                .map(type -> Graql.var("x").isa(Graql.type(type.getValue()))).collect(Collectors.toList());

        return tx.stream(Graql.match(Graql.or(checkSubtypes)), false).iterator().hasNext();
    }
143306
public void addScope(ApiAppOauthScopeType scope) {
        if (oauth == null) {
            oauth = new ApiAppOauth();
        }
        oauth.addScope(scope);
    }
951287
private Status executeFail(Stmt.Fail stmt, CallStack frame, EnclosingScope scope) {
		throw new AssertionError("Runtime fault occurred");
	}
886315
private Cache getScopeCache(String scope) throws InvalidScopeException {
        Cache scopeCache = scopeManager.getCache(scope);
        if (scopeCache == null) {
            throw new InvalidScopeException("The scope " + scope + " doesn't exist");
        } else {
            return scopeCache;
        }
    }
1054305
public CompletableFuture<Map<String, StreamConfiguration>> listStreamsInScope(final String scope) {
        Exceptions.checkNotNullOrEmpty(scope, "scope");
        return streamStore.listStreamsInScope(scope);
    }
1102873
def has_scope(self, scope):
        """"""
        if not self.is_oauth_session():
            return False
        if '*' in self._authentication:
            return True
        if isinstance(scope, six.string_types):
            scope = [scope]
        return all(s in self._authentication for s in scope)
280091
public static AstRoot parse(String rapids) {
    Rapids r = new Rapids(rapids);
    AstRoot res = r.parseNext();
    if (r.skipWS() != ' ')
      throw new IllegalASTException("Syntax error: illegal Rapids expression `" + rapids + "`");
    return res;
  }
573044
private RValue executeConvert(Expr.Cast expr, CallStack frame) {
		RValue operand = executeExpression(ANY_T, expr.getOperand(), frame);
		return operand.convert(expr.getType());
	}
374644
@Override public ValFrame apply(Env env, Env.StackHelp stk, AstRoot asts[]) {
    Frame fr = stk.track(asts[1].exec(env)).getFrame(); // first argument is dataframe
    int[] groupbycols = ((AstParameter)asts[2]).columns(fr.names());
    int[] sortcols =((AstParameter)asts[3]).columns(fr.names());  // sort columns

    int[] sortAsc;
    if (asts[4] instanceof AstNumList)
      sortAsc = ((AstNumList) asts[4]).expand4();
    else
      sortAsc = new int[]{(int) ((AstNum) asts[4]).getNum()};  // R client can send 1 element for some reason
    String newcolname = asts[5].str();
    Boolean sortColsOrder = ((AstNum) asts[6]).getNum()==1;
    
    assert sortAsc.length==sortcols.length;
    SortnGrouby sortgroupbyrank = new SortnGrouby(fr, groupbycols, sortcols, sortAsc, newcolname);
    sortgroupbyrank.doAll(sortgroupbyrank._groupedSortedOut);  // sort and add rank column
    RankGroups rankgroups = new RankGroups(sortgroupbyrank._groupedSortedOut, groupbycols,
            sortcols, sortgroupbyrank._chunkFirstG, sortgroupbyrank._chunkLastG,
            sortgroupbyrank._newRankCol).doAll(sortgroupbyrank._groupedSortedOut);

    if (sortColsOrder)
      return new ValFrame(rankgroups._finalResult.sort(sortcols, sortAsc));
    else
      return new ValFrame(rankgroups._finalResult);
  }
2204
public synchronized T get(Scope scope) {
    if (instance != null) {
      return instance;
    }

    if (providerInstance != null) {
      if (isProvidingSingletonInScope) {
        instance = providerInstance.get();
        //gc
        providerInstance = null;
        return instance;
      }

      return providerInstance.get();
    }

    if (factoryClass != null && factory == null) {
      factory = FactoryLocator.getFactory(factoryClass);
      //gc
      factoryClass = null;
    }

    if (factory != null) {
      if (!factory.hasScopeAnnotation() && !isCreatingSingletonInScope) {
        return factory.createInstance(scope);
      }
      instance = factory.createInstance(scope);
      //gc
      factory = null;
      return instance;
    }

    if (providerFactoryClass != null && providerFactory == null) {
      providerFactory = FactoryLocator.getFactory(providerFactoryClass);
      //gc
      providerFactoryClass = null;
    }

    if (providerFactory != null) {
      if (providerFactory.hasProvidesSingletonInScopeAnnotation() || isProvidingSingletonInScope) {
        instance = providerFactory.createInstance(scope).get();
        //gc
        providerFactory = null;
        return instance;
      }
      if (providerFactory.hasScopeAnnotation() || isCreatingSingletonInScope) {
        providerInstance = providerFactory.createInstance(scope);
        //gc
        providerFactory = null;
        return providerInstance.get();
      }

      return providerFactory.createInstance(scope).get();
    }

    throw new IllegalStateException("A provider can only be used with an instance, a provider, a factory or a provider factory. Should not happen.");
  }
5175
function asyncDefineMethod(ast) {
        return treeWalk(ast, function (node, descend, path) {
            var transform = getMemberFunction(node);
            descend();
            if (!transform || !examine(transform).isAsync) 
                return;
            if (node.kind == 'set') {
                var ex = new SyntaxError(where(transform) + "method 'async set' cannot be invoked", pr.filename, node.start);
                ex.pos = node.start;
                ex.loc = node.loc.start;
                throw ex;
            }
            transform.async = false;
            var usesArgs = replaceArguments(transform);
            if (!containsAsyncExit(transform) && (transform.body.body.length === 0 || transform.body.body[transform.body.body.length - 1].type !== 'ReturnStatement')) {
                transform.body.body.push({
                    type: 'ReturnStatement'
                });
            }
            var funcback = bindAsync(setExit({
                type: 'FunctionExpression',
                params: [genIdent.return,genIdent.error],
                body: asyncDefineMethod(mapReturns(transform.body, path)),
                $wasAsync: true
            }, opts), opts.promises || opts.generators || opts.engine ? null : literal(opts.lazyThenables ? 0 : true));
            if (opts.promises) {
                transform.body = {
                    type: 'BlockStatement',
                    body: [{
                        type: 'ReturnStatement',
                        argument: {
                            type: 'NewExpression',
                            callee: genIdent.Promise,
                            arguments: [funcback]
                        }
                    }]
                };
            } else {
                transform.body = {
                    type: 'BlockStatement',
                    body: [{
                        type: 'ReturnStatement',
                        argument: funcback
                    }]
                };
            }
            if (usesArgs) {
                afterDirectives(transform.body.body, [assign$Args]);
            }
        });
    }
598816
function asyncLoops_1(ast, state) {
        treeWalk(ast, function (node, descend, path) {
            function mapContinue(label) {
                return {
                    type: 'ReturnStatement',
                    argument: {
                        type: 'UnaryExpression',
                        operator: 'void',
                        prefix: true,
                        argument: thisCall(label || symContinue)
                    }
                };
            }
            
            ;
            function mapExits(n, descend) {
                if (n.type === 'BreakStatement') {
                    coerce(n, cloneNode(mapBreak(n.label && opts.generatedSymbolPrefix + "Loop_" + n.label.name + "_exit")));
                } else if (n.type === 'ContinueStatement') {
                    coerce(n, cloneNode(mapContinue(n.label && opts.generatedSymbolPrefix + "Loop_" + n.label.name + "_next")));
                } else if (examine(n).isFunction) {
                    return true;
                }
                descend();
            }
            
            if (node.type === 'ForInStatement' && containsAwait(node)) {
                transformForIn(node, path);
            } else if (node.type === 'ForOfStatement' && containsAwait(node)) {
                iterizeForOf(node, path);
            }
            descend();
            var p;
            if (examine(node).isLoop && containsAwait(node)) {
                var init = node.init;
                var condition = node.test || literal(true);
                var step = node.update;
                var body = node.body;
                var loopUsesThis = containsThis(body);
                if (init) {
                    if (!examine(init).isStatement) {
                        init = {
                            type: 'ExpressionStatement',
                            expression: init
                        };
                    }
                }
                step = step && {
                    type: 'ExpressionStatement',
                    expression: step
                };
                body = examine(body).isBlockStatement ? cloneNode(body).body : [cloneNode(body)];
                var label = node.$label && node.$label.name;
                label = "Loop_" + (label || generatedSymbol++);
                var symExit = opts.generatedSymbolPrefix + (label + "_exit");
                var symContinue = opts.generatedSymbolPrefix + (label + "_next");
                var loop = ident(opts.generatedSymbolPrefix + label);
                // How to exit the loop
                var mapBreak = function (label) {
                    return {
                        type: 'ReturnStatement',
                        argument: {
                            type: 'UnaryExpression',
                            operator: 'void',
                            prefix: true,
                            argument: {
                                type: 'CallExpression',
                                callee: ident(label || symExit),
                                arguments: []
                            }
                        }
                    };
                };
                // How to continue the loop
                var defContinue = makeContinuation(symContinue, [{
                    type: 'ReturnStatement',
                    argument: {
                        type: 'CallExpression',
                        callee: loopUsesThis ? bindAsync(loop) : loop,
                        arguments: [ident(symExit),genIdent.error]
                    }
                }]);
                if (step) 
                    defContinue.body.body.unshift(step);
                for (var i = 0;i < body.length; i++) {
                    treeWalk(body[i], mapExits);
                }
                body.push(cloneNode(mapContinue()));
                var subCall = {
                    type: 'FunctionExpression',
                    id: loop,
                    params: [ident(symExit),genIdent.error],
                    body: {
                        type: 'BlockStatement',
                        body: [defContinue]
                    }
                };
                if (node.type === 'DoWhileStatement') {
                    defContinue.body.body = [{
                        type: 'IfStatement',
                        test: cloneNode(condition),
                        consequent: {
                            type: 'BlockStatement',
                            body: cloneNode(defContinue.body.body)
                        },
                        alternate: {
                            type: 'ReturnStatement',
                            argument: {
                                type: 'CallExpression',
                                callee: ident(symExit),
                                arguments: []
                            }
                        }
                    }];
                    subCall.body.body = [defContinue].concat(body);
                } else {
                    var nextTest = {
                        type: 'IfStatement',
                        test: cloneNode(condition),
                        consequent: {
                            type: 'BlockStatement',
                            body: body
                        },
                        alternate: cloneNode(mapBreak())
                    };
                    subCall.body.body.push(nextTest);
                }
                var replace = {
                    type: 'ExpressionStatement',
                    expression: {
                        type: 'AwaitExpression',
                        argument: bindAsync(subCall, literal(0))
                    }
                };
                if (init && init.type === 'VariableDeclaration' && (init.kind === 'let' || init.kind === 'const')) {
                    if (init.kind === 'const') 
                        init.kind = 'let';
                    replace = {
                        type: 'BlockStatement',
                        body: [cloneNode(init),replace]
                    };
                    init = null;
                }
                for (p = 0; p < path.length; p++) {
                    var ref = path[p];
                    if ('index' in ref) {
                        if (init) {
                            ref.parent[ref.field].splice(ref.index, 1, cloneNode(init), replace);
                        } else {
                            ref.parent[ref.field][ref.index] = replace;
                        }
                        return true;
                    }
                }
            }
            return true;
        }, state);
        return ast;
    }
1080650
public static Collection<IAction> getRegisteredActions(ActionScope scope) {
        Map<String, IAction> actions = new HashMap<>();
        
        if (scope == ActionScope.BOTH || scope == ActionScope.GLOBAL) {
            actions.putAll(getRegistry(true).map);
        }
        
        if (scope == ActionScope.BOTH || scope == ActionScope.LOCAL) {
            actions.putAll(getRegistry(false).map);
        }
        
        return actions.values();
    }
364265
public TypeUsage.Builder scope(Optional<? extends QualifiedName> scope) {
    if (scope.isPresent()) {
      return scope(scope.get());
    } else {
      return clearScope();
    }
  }