Recursively apply constant binding to functions in a module or class.

    Use as the last line of the module (after everything is defined, but
    before test code).  In modules that need modifiable globals, set
    builtin_only to True.
488616
def bind_all(mc, builtin_only=False, stoplist=[],  verbose=False):
    
    import types
    try:
        d = vars(mc)
    except TypeError:
        return
    for k, v in d.items():
        if isinstance( v, types.FunctionType ) :
            if verbose :
                print( 'make_constants(', v.__name__, ')' )
            newv = _make_constants(v, builtin_only, stoplist,  verbose)
            setattr(mc, k, newv)
        elif type(v) in ( type, types.ModuleType ):
            bind_all(v, builtin_only, stoplist, verbose)
162271
function globalizeDeclaration(node, bindings) {
  return node.declarations.map(declaration =>
    t.expressionStatement(
      t.assignmentExpression(
        "=",
        getAssignmentTarget(declaration.id, bindings),
        declaration.init || t.unaryExpression("void", t.numericLiteral(0))
      )
    )
  );
}
246064
def copy_globals(self, cfg):
        
        for name, setting in cfg.settings.items():
            csetting = self.settings.get(name)
            if (setting.is_global and csetting is not None and
                    not csetting.modified):
                csetting.set(setting.get())
938331
def module2md(self, module):
        
        modname = module.__name__
        path = self.get_src_path(module, append_base=False)
        path = "[{}]({})".format(path, os.path.join(self.github_link, path))
        found = set()

        classes = []
        line_nos = []
        for name, obj in getmembers(module, inspect.isclass):
            # handle classes
            found.add(name)
            if not name.startswith("_") and hasattr(obj, "__module__") and obj.__module__ == modname:
                classes.append(self.class2md(obj))
                line_nos.append(self.get_line_no(obj) or 0)
        classes = order_by_line_nos(classes, line_nos)

        # Since functions can have multiple aliases.
        func2names = defaultdict(list)
        for name, obj in getmembers(module, inspect.isfunction):
            func2names[obj].append(name)

        functions = []
        line_nos = []
        for obj in func2names:
            names = func2names[obj]
            found.update(names)

            # Include if within module or included modules within __init__.py and exclude from global variables
            is_module_within_init = '__init__.py' in path and obj.__module__.startswith(modname)
            if is_module_within_init:
                found.add(obj.__module__.replace(modname + '.', ''))

            if hasattr(obj, "__module__") and (obj.__module__ == modname or is_module_within_init):
                names = list(filter(lambda name: not name.startswith("_"), names))
                if len(names) > 0:
                    functions.append(self.func2md(obj, names=names))
                    line_nos.append(self.get_line_no(obj) or 0)
        functions = order_by_line_nos(functions, line_nos)

        variables = []
        line_nos = []
        for name, obj in module.__dict__.items():
            if not name.startswith("_") and name not in found:
                if hasattr(obj, "__module__") and obj.__module__ != modname:
                    continue
                if hasattr(obj, "__name__") and not obj.__name__.startswith(modname):
                    continue

                comments = inspect.getcomments(obj)
                comments = ": %s" % comments if comments else ""
                variables.append("- **%s**%s" % (name, comments))
                line_nos.append(self.get_line_no(obj) or 0)

        variables = order_by_line_nos(variables, line_nos)
        if variables:
            new_list = ["**Global Variables**", "---------------"]
            new_list.extend(variables)
            variables = new_list

        string = MODULE_TEMPLATE.format(path=path,
                                        global_vars="\n".join(variables) if variables else "",
                                        functions="\n".join(functions) if functions else "",
                                        classes="".join(classes) if classes else "")
        return string
159595
function maintain_this_binding(parent, orig, val) {
        if (parent instanceof AST_UnaryPrefix && parent.operator == "delete"
            || parent instanceof AST_Call && parent.expression === orig
                && (val instanceof AST_PropAccess || val instanceof AST_SymbolRef && val.name == "eval")) {
            return make_node(AST_Seq, orig, {
                car: make_node(AST_Number, orig, {
                    value: 0
                }),
                cdr: val
            });
        }
        return val;
    }
1181542
static Binding from(Module namespaceBoundModule, Node sourceNode) {
    return new AutoValue_Binding(
        namespaceBoundModule.metadata(),
        sourceNode,
        /* originatingExport= */ null,
        /* isModuleNamespace= */ true,
        namespaceBoundModule.closureNamespace(),
        CreatedBy.IMPORT);
  }
895094
def func_globals_inject(func, **overrides):
    '''
    
    '''
    # recognize methods
    if hasattr(func, 'im_func'):
        func = func.__func__

    # Get a reference to the function globals dictionary
    func_globals = func.__globals__
    # Save the current function globals dictionary state values for the
    # overridden objects
    injected_func_globals = []
    overridden_func_globals = {}
    for override in overrides:
        if override in func_globals:
            overridden_func_globals[override] = func_globals[override]
        else:
            injected_func_globals.append(override)

    # Override the function globals with what's passed in the above overrides
    func_globals.update(overrides)

    # The context is now ready to be used
    yield

    # We're now done with the context

    # Restore the overwritten function globals
    func_globals.update(overridden_func_globals)

    # Remove any entry injected in the function globals
    for injected in injected_func_globals:
        del func_globals[injected]
1023256
def _compilecode(function, name, impl, args, varargs, kwargs):
    

    newcodestr, generatedname, impl_name = _generatecode(
        function=function, name=name, impl=impl,
        args=args, varargs=varargs, kwargs=kwargs
    )

    try:
        __file__ = getfile(function)
    except TypeError:
        __file__ = '<string>'

    # compile newcodestr
    code = compile(newcodestr, __file__, 'single')

    # define the code with the new function
    _globals = {}
    exec_(code, _globals)

    # get new code
    _var = _globals[generatedname]
    newco = get_function_code(_var)

    # get new consts list
    newconsts = list(newco.co_consts)

    if PY3:
        newcode = list(newco.co_code)
    else:
        newcode = [ord(co) for co in newco.co_code]

    consts_values = {impl_name: impl}

    # change LOAD_GLOBAL to LOAD_CONST
    index = 0
    newcodelen = len(newcode)
    while index < newcodelen:
        if newcode[index] == LOAD_GLOBAL:
            oparg = newcode[index + 1] + (newcode[index + 2] << 8)
            name = newco.co_names[oparg]
            if name in consts_values:
                const_value = consts_values[name]
                if const_value in newconsts:
                    pos = newconsts.index(const_value)
                else:
                    pos = len(newconsts)
                    newconsts.append(consts_values[name])
                newcode[index] = LOAD_CONST
                newcode[index + 1] = pos & 0xFF
                newcode[index + 2] = pos >> 8
        index += 1

    codeobj = getcodeobj(newconsts, newcode, newco, get_function_code(function))
    # instanciate a new function
    if function is None or isbuiltin(function):
        result = FunctionType(codeobj, {})

    else:
        result = type(function)(
            codeobj,
            get_function_globals(function),
            function.__name__,
            get_function_defaults(function),
            get_function_closure(function)
        )

    return result
533435
def global_variable_action(self, text, loc, var):
        """"""
        exshared.setpos(loc, text)
        if DEBUG > 0:
            print("GLOBAL_VAR:",var)
            if DEBUG == 2: self.symtab.display()
            if DEBUG > 2: return
        index = self.symtab.insert_global_var(var.name, var.type)
        self.codegen.global_var(var.name)
        return index
332814
function _bindAll(methods, ctx) {
	var ret = {};
	for (var key in methods) {
		ret[key] = (typeof methods[key] !== "function" ? _bindAll(methods[key], ctx) : methods[key].bind(ctx));
	}
	return ret;
}
1103927
function addModuleProperty(module, symbol, modulePath, opt_wrap, opt_obj) {
    var val = null;
    if (opt_wrap) {
        module.exports[symbol] = function() {
            val = val || module.require(modulePath);
            if (arguments.length && typeof arguments[arguments.length - 1] === 'function') {
                // If args exist and the last one is a function, it's the callback.
                var args = Array.prototype.slice.call(arguments);
                var cb = args.pop();
                val.apply(module.exports, args).done(function(result) { cb(undefined, result); }, cb);
            } else {
                val.apply(module.exports, arguments).done(null, function(err) { throw err; });
            }
        };
    } else {
        Object.defineProperty(opt_obj || module.exports, symbol, {
            get : function() { val = val || module.require(modulePath); return val; },
            set : function(v) { val = v; }
        });
    }

    // Add the module.raw.foo as well.
    if(module.exports.raw) {
        Object.defineProperty(module.exports.raw, symbol, {
            get : function() { val = val || module.require(modulePath); return val; },
            set : function(v) { val = v; }
        });
    }
}
651178
function applyGlobals (obj, target, key) {
            let prop;

            // Check for previously applied global substitution
            if (target != null && typeof target === 'object' && target._global_prop && target._global_prop[key]) {
                prop = target._global_prop[key];
            }
            // Check string for new global substitution
            else if (typeof obj === 'string' && obj.slice(0, 7) === 'global.') {
                prop = obj;
            }

            // Found global property to substitute
            if (prop) {
                // Mark property as global substitution
                if (target._global_prop == null) {
                    Object.defineProperty(target, '_global_prop', { value: {} });
                }
                target._global_prop[key] = prop;

                // Get current global value
                let val = globals[prop];
                let stack;
                while (typeof val === 'string' && val.slice(0, 7) === 'global.') {
                    // handle globals that refer to other globals, detecting any cyclical references
                    stack = stack || [prop];
                    if (stack.indexOf(val) > -1) {
                        log({ level: 'warn', once: true }, 'Global properties: cyclical reference detected', stack);
                        val = null;
                        break;
                    }
                    stack.push(val);
                    val = globals[val];
                }

                // Create getter/setter
                Object.defineProperty(target, key, {
                    enumerable: true,
                    get: function () {
                        return val; // return substituted value
                    },
                    set: function (v) {
                        // clear the global substitution and remove the getter/setter
                        delete target._global_prop[key];
                        delete target[key];
                        target[key] = v; // save the new value
                    }
                });
            }
            // Loop through object keys or array indices
            else if (Array.isArray(obj)) {
                for (let p=0; p < obj.length; p++) {
                    applyGlobals(obj[p], obj, p);
                }
            }
            else if (typeof obj === 'object') {
                for (let p in obj) {
                    applyGlobals(obj[p], obj, p);
                }
            }
            return obj;
        }
557338
private void updateCurrentFunction(AbstractFunctionExpression parentExpr) {
        GroovyExpression expr = parentExpr.getCaller();
        if (expr instanceof AbstractFunctionExpression) {
            AbstractFunctionExpression exprAsFunction = (AbstractFunctionExpression) expr;
            GroovyExpression exprCaller = exprAsFunction.getCaller();
            parentExpr.setCaller(exprCaller);
            updateCurrentFunctionDefintion(exprAsFunction);
        }
    }
709237
function boundMethod(target, key, descriptor) {
    // console.log('target, key, descriptor', target, key, descriptor)
    let fn = descriptor.value

    if (typeof fn !== 'function') {
        throw new Error(`@autobind decorator can only be applied to methods not: ${typeof fn}`)
    }

    // In IE11 calling Object.defineProperty has a side-effect of evaluating the
    // getter for the property which is being replaced. This causes infinite
    // recursion and an "Out of stack space" error.
    let definingProperty = false

    return {
        configurable: true,
        get() {
            if (definingProperty || this === target.prototype || this.hasOwnProperty(key)
                || typeof fn !== 'function') {
                return fn
            }

            let boundFn = bind(fn, this)//fn.bind(this)
            definingProperty = true
            Object.defineProperty(this, key, {
                configurable: true,
                get() {
                    return boundFn
                },
                set(value) {
                    fn = value
                    delete this[key]
                }
            })
            definingProperty = false
            return boundFn
        },
        set(value) {
            fn = value
        }
    }
}
949868
def function_end_action(self, text, loc, fun):
        """"""
        if DEBUG > 0:
            print("FUN_END:",fun)
            if DEBUG == 2: self.symtab.display()
            if DEBUG > 2: return
        #set function's attribute to number of function parameters
        self.symtab.set_attribute(self.shared.function_index, self.shared.function_params)
        #clear local function symbols (but leave function name)
        self.symtab.clear_symbols(self.shared.function_index + 1)
        self.codegen.function_end()
86486
def prepare_namespace(self, func):
        
        if self.is_imethod:
            to_run = getattr(self.obj, self.imethod_name)
        else:
            to_run = func

        for varname, modulename in self.global_modules.items():
            to_run.__globals__[varname] = __import__(modulename)
        if self.global_closure:
            to_run.__globals__.update(self.global_closure)
        if self.global_functions:
            to_run.__globals__.update(self.global_functions)
        return to_run
808417
function maybeBindToGlobal(func) {
    if (func && global &&
        global['EventTarget'] &&
        typeof global['EventTarget'].prototype.addEventListener === 'function' &&
        typeof func.bind === 'function') {
      return func.bind(global);
    }
    return func;
  }