Generates a module for each namespace.

        Each namespace will have Obj C classes to represent data types and
        routes in the Stone spec.
511123
def generate(self, api):
        
        rsrc_folder = os.path.join(os.path.dirname(__file__), 'obj_c_rsrc')
        rsrc_output_folder = os.path.join(self.target_folder_path, 'Resources')

        if not os.path.exists(rsrc_output_folder):
            os.makedirs(rsrc_output_folder)

        self.logger.info('Copying DBStoneValidators.{h,m} to output folder')
        shutil.copy(
            os.path.join(rsrc_folder, 'DBStoneValidators.h'),
            rsrc_output_folder)
        shutil.copy(
            os.path.join(rsrc_folder, 'DBStoneValidators.m'),
            rsrc_output_folder)
        self.logger.info('Copying DBStoneSerializers.{h,m} to output folder')
        shutil.copy(
            os.path.join(rsrc_folder, 'DBStoneSerializers.h'),
            rsrc_output_folder)
        shutil.copy(
            os.path.join(rsrc_folder, 'DBStoneSerializers.m'),
            rsrc_output_folder)
        self.logger.info('Copying DBStoneBase.{h,m} to output folder')
        shutil.copy(
            os.path.join(rsrc_folder, 'DBStoneBase.h'), rsrc_output_folder)
        shutil.copy(
            os.path.join(rsrc_folder, 'DBStoneBase.m'), rsrc_output_folder)
        self.logger.info('Copying DBSerializableProtocol.h to output folder')
        shutil.copy(
            os.path.join(rsrc_folder, 'DBSerializableProtocol.h'),
            rsrc_output_folder)

        jazzy_cfg = None

        if self.args.documentation:
            jazzy_cfg_path = os.path.join('../Format', 'jazzy.json')
            with open(jazzy_cfg_path) as jazzy_file:
                jazzy_cfg = json.load(jazzy_file)

            for idx, namespace in enumerate(api.namespaces.values()):
                ns_name = fmt_public_name(namespace.name)
                ns_dict = {"name": ns_name, "children": [], }
                jazzy_cfg['custom_categories'].insert(idx, ns_dict)

        for namespace in api.namespaces.values():
            self.namespace_to_has_route_auth_list[namespace] = set()
            if namespace.routes:
                for route in namespace.routes:
                    if route.attrs.get('auth') != 'noauth':
                        self.namespace_to_has_route_auth_list[namespace].add(
                            route.attrs.get('auth'))
                    else:
                        self.namespace_to_has_route_auth_list[namespace].add(
                            'user')

        with self.output_to_relative_path('DBSDKImportsGenerated.h'):
            self._generate_all_imports(api)

        for namespace in api.namespaces.values():
            for data_type in namespace.linearize_data_types():
                self.obj_name_to_namespace[data_type.name] = fmt_class_prefix(
                    data_type)

        for namespace in api.namespaces.values():
            ns_name = fmt_public_name(namespace.name)
            self._generate_namespace_types(namespace, jazzy_cfg)

            if namespace.routes:
                if self.args.documentation:
                    for auth_type in self.namespace_to_has_route_auth_list[
                            namespace]:
                        append_to_jazzy_category_dict(
                            jazzy_cfg, 'Routes', fmt_routes_class(ns_name, auth_type))
                    append_to_jazzy_category_dict(
                        jazzy_cfg, 'RouteObjects', fmt_route_obj_class(ns_name))
                self._generate_route_objects_m(api.route_schema, namespace)
                self._generate_route_objects_h(api.route_schema, namespace)

        if self.args.documentation:
            with self.output_to_relative_path('../../../../.jazzy.json'):
                self.emit_raw(json.dumps(jazzy_cfg, indent=2) + '\n')
1334650
def make_modules(self, groups, code_opts):
        """"""
        modules = []
        for raw_module, raw_funcs in groups:
            module = raw_module[0].strip().strip(string.punctuation)
            funcs = [func.strip() for func in raw_funcs]
            args = [self.database.query_args(func, raw=True)
                    for func in funcs]
            if self.generic:
                args = [arg if arg else ('VOID *', [])
                        for arg in args]
            else:
                args = [arg for arg in args if arg]
            if not args:
                logging.info(_('%s not found.'), module)
                continue
            logging.debug(module)
            module = ModuleSource(module, zip(funcs, args),
                                  code_opts)
            modules.append(module.c_source())
        return AttrsGetter(modules)
820598
def _generate_struct_class_m(self, struct):
        """"""
        self.emit()
        self._generate_imports_m(
            self._get_imports_m(
                struct,
                default_imports=['DBStoneSerializers', 'DBStoneValidators']))

        struct_name = fmt_class_prefix(struct)

        self.emit('#pragma mark - API Object')
        self.emit()
        with self.block_m(struct_name):
            self.emit('#pragma mark - Constructors')
            self.emit()
            self._generate_struct_cstor(struct)
            self._generate_struct_cstor_default(struct)
            self.emit('#pragma mark - Serialization methods')
            self.emit()
            self._generate_serializable_funcs(struct_name)
            self.emit('#pragma mark - Description method')
            self.emit()
            self._generate_description_func(struct_name)
            self.emit('#pragma mark - Copyable method')
            self.emit()
            self._generate_copyable_func()
            self.emit('#pragma mark - Hash method')
            self.emit()
            self._generate_hash_func(struct)
            self.emit('#pragma mark - Equality method')
            self.emit()
            self._generate_equality_func(struct)

        self.emit()
        self.emit()

        self.emit('#pragma mark - Serializer Object')
        self.emit()
        with self.block_m(fmt_serial_class(struct_name)):
            self._generate_struct_serializer(struct)
            self._generate_struct_deserializer(struct)
586642
def generate(env):
    """"""
    import SCons.Defaults
    import SCons.Tool

    set_vars(env)

    static_obj, shared_obj = SCons.Tool.createObjBuilders(env)

    for suffix in CSuffixes:
        static_obj.add_action(suffix, SCons.Defaults.CAction)
        shared_obj.add_action(suffix, SCons.Defaults.ShCAction)

    for suffix in CXXSuffixes:
        static_obj.add_action(suffix, SCons.Defaults.CXXAction)
        shared_obj.add_action(suffix, SCons.Defaults.ShCXXAction)

    env['CCCOMFLAGS'] = '$CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -nolink -o $TARGET $SOURCES'

    env['CC']         = 'mwcc'
    env['CCCOM']      = '$CC $CFLAGS $CCFLAGS $CCCOMFLAGS'

    env['CXX']        = 'mwcc'
    env['CXXCOM']     = '$CXX $CXXFLAGS $CCCOMFLAGS'

    env['SHCC']       = '$CC'
    env['SHCCFLAGS']  = '$CCFLAGS'
    env['SHCFLAGS']   = '$CFLAGS'
    env['SHCCCOM']    = '$SHCC $SHCFLAGS $SHCCFLAGS $CCCOMFLAGS'

    env['SHCXX']       = '$CXX'
    env['SHCXXFLAGS']  = '$CXXFLAGS'
    env['SHCXXCOM']    = '$SHCXX $SHCXXFLAGS $CCCOMFLAGS'

    env['CFILESUFFIX'] = '.c'
    env['CXXFILESUFFIX'] = '.cpp'
    env['CPPDEFPREFIX']  = '-D'
    env['CPPDEFSUFFIX']  = ''
    env['INCPREFIX']  = '-I'
    env['INCSUFFIX']  = ''
655396
def _generate_route_method_decl(
            self, namespace, route, arg_data_type, request_binary_body,
            method_name_suffix='', extra_args=None):
        """"""
        args = ['self']
        if extra_args:
            args += extra_args
        if request_binary_body:
            args.append('f')
        if is_struct_type(arg_data_type):
            for field in arg_data_type.all_fields:
                if is_nullable_type(field.data_type):
                    args.append('{}=None'.format(field.name))
                elif field.has_default:
                    # TODO(kelkabany): Decide whether we really want to set the
                    # default in the argument list. This will send the default
                    # over the wire even if it isn't overridden. The benefit is
                    # it locks in a default even if it is changed server-side.
                    if is_user_defined_type(field.data_type):
                        ns = field.data_type.namespace
                    else:
                        ns = None
                    arg = '{}={}'.format(
                        field.name,
                        self._generate_python_value(ns, field.default))
                    args.append(arg)
                else:
                    args.append(field.name)
        elif is_union_type(arg_data_type):
            args.append('arg')
        elif not is_void_type(arg_data_type):
            raise AssertionError('Unhandled request type: %r' %
                                 arg_data_type)

        method_name = fmt_func(route.name + method_name_suffix, version=route.version)
        namespace_name = fmt_underscores(namespace.name)
        self.generate_multiline_list(args, 'def {}_{}'.format(namespace_name, method_name), ':')
180905
function genModuleDeps(scriptPath) {
  var provideMap = new ProvideMap_();
  var requireMap = new RequireMap_();
  scanFiles([scriptPath], provideMap, requireMap);
  var dumpValues = function(map) {
    var results = [];
    map.forEach(function(value, key) {
      results = results.concat(value);
    });
    return results;
  };

  var relativePath = pathMod.join('../..', scriptPath);
  if (osMod.platform().indexOf('win') != -1) {
    relativePath = relativePath.replace(/\\/g, '\\\\');
  }

  var provide = provideMap.getAllProvides();
  var require = requireMap.getAllRequires();
  return 'goog.addDependency("' + relativePath + '", ' +
      JSON.stringify(dumpValues(provide)) + ', ' +
      JSON.stringify(dumpValues(require)) + ', true);';
}
111278
def gen_modules(self, initial_load=False):
        '''
        
        '''
        self.opts['pillar'] = salt.pillar.get_pillar(
            self.opts,
            self.opts['grains'],
            self.opts['id'],
            self.opts['saltenv'],
            pillarenv=self.opts.get('pillarenv'),
        ).compile_pillar()

        self.utils = salt.loader.utils(self.opts)
        self.functions = salt.loader.minion_mods(self.opts, utils=self.utils)
        self.serializers = salt.loader.serializers(self.opts)
        self.returners = salt.loader.returners(self.opts, self.functions)
        self.proxy = salt.loader.proxy(self.opts, self.functions, self.returners, None)
        # TODO: remove
        self.function_errors = {}  # Keep the funcs clean
        self.states = salt.loader.states(self.opts,
                self.functions,
                self.utils,
                self.serializers)
        self.rend = salt.loader.render(self.opts, self.functions)
#        self.matcher = Matcher(self.opts, self.functions)
        self.matchers = salt.loader.matchers(self.opts)
        self.functions['sys.reload_modules'] = self.gen_modules
        self.executors = salt.loader.executors(self.opts)
277531
def generate(self, vars=None, env=None):
        """"""
        def defined(v, default=None):
            _v = default
            if v in vars:
                _v = vars[v]
            elif v in env:
                _v = env[v]
            return _v

        namespace = {
            # __name__ and __loader__ allow the traceback mechanism to find
            # the generated source code.
            "defined": defined,
            #fix RuntimeWarning: Parent module 'a/b/c' not found while handling absolute import warning
            "__name__": self.name.replace('.', '_'),
            # "__name__": self.name,
            "__loader__": ObjectDict(get_source=lambda name: self.code),
        }
        namespace.update(default_namespace)
        namespace.update(env or {})
        namespace.update(self.namespace)
        namespace.update(vars or {})
        namespace['_vars'] = vars
        exec_in(self.compiled, namespace)
        execute = namespace["_tt_execute"]
        # Clear the traceback module's cache of source data now that
        # we've generated a new template (mainly for this module's
        # unittests, where different tests reuse the same name).
        linecache.clearcache()
        return execute()
522113
def generate_cxx(module_name, code, specs=None, optimizations=None,
                 module_dir=None):
    '''

    '''

    pm, ir, renamings, docstrings = front_middle_end(module_name, code,
                                                     optimizations, module_dir)

    # back-end
    content = pm.dump(Cxx, ir)

    # instantiate the meta program
    if specs is None:

        class Generable(object):
            def __init__(self, content):
                self.content = content

            def __str__(self):
                return str(self.content)

            generate = __str__

        mod = Generable(content)

        def error_checker():
            tog.typecheck(ir)

    else:

        # uniform typing
        if isinstance(specs, dict):
            specs = Spec(specs, {})

        def error_checker():
            types = tog.typecheck(ir)
            check_specs(specs, renamings, types)

        specs.to_docstrings(docstrings)
        check_exports(ir, specs, renamings)

        if isinstance(code, bytes):
            code_bytes = code
        else:
            code_bytes = code.encode('ascii', 'ignore')
        metainfo = {'hash': hashlib.sha256(code_bytes).hexdigest(),
                    'version': __version__,
                    'date': datetime.now()}

        mod = PythonModule(module_name, docstrings, metainfo)
        mod.add_to_includes(
            Include("pythonic/core.hpp"),
            Include("pythonic/python/core.hpp"),
            # FIXME: only include these when needed
            Include("pythonic/types/bool.hpp"),
            Include("pythonic/types/int.hpp"),
            Line("#ifdef _OPENMP\n#include <omp.h>\n#endif")
        )
        mod.add_to_includes(*[Include(inc) for inc in
                              _extract_specs_dependencies(specs)])
        mod.add_to_includes(*content.body)
        mod.add_to_includes(
            Include("pythonic/python/exception_handler.hpp"),
        )

        def warded(module_name, internal_name):
            return pythran_ward + '{0}::{1}'.format(module_name, internal_name)

        for function_name, signatures in specs.functions.items():
            internal_func_name = renamings.get(function_name,
                                               function_name)
            # global variables are functions with no signatures :-)
            if not signatures:
                mod.add_global_var(function_name,
                                   "{}()()".format(warded(module_name,
                                                          internal_func_name)))

            for sigid, signature in enumerate(signatures):
                numbered_function_name = "{0}{1}".format(internal_func_name,
                                                         sigid)
                arguments_types = [pytype_to_ctype(t) for t in signature]
                arguments_names = HasArgument(internal_func_name).visit(ir)
                arguments = [n for n, _ in
                             zip(arguments_names, arguments_types)]
                name_fmt = pythran_ward + "{0}::{1}::type{2}"
                args_list = ", ".join(arguments_types)
                specialized_fname = name_fmt.format(module_name,
                                                    internal_func_name,
                                                    "<{0}>".format(args_list)
                                                    if arguments_names else "")
                result_type = "typename %s::result_type" % specialized_fname
                mod.add_pyfunction(
                    FunctionBody(
                        FunctionDeclaration(
                            Value(
                                result_type,
                                numbered_function_name),
                            [Value(t + '&&', a)
                             for t, a in zip(arguments_types, arguments)]),
                        Block([Statement("""
                            PyThreadState *_save = PyEval_SaveThread();
                            try {{
                                auto res = {0}()({1});
                                PyEval_RestoreThread(_save);
                                return res;
                            }}
                            catch(...) {{
                                PyEval_RestoreThread(_save);
                                throw;
                            }}
                            """.format(warded(module_name,
                                              internal_func_name),
                                       ', '.join(arguments)))])
                    ),
                    function_name,
                    arguments_types,
                    signature
                )

        for function_name, signature in specs.capsules.items():
            internal_func_name = renamings.get(function_name,
                                               function_name)

            arguments_types = [pytype_to_ctype(t) for t in signature]
            arguments_names = HasArgument(internal_func_name).visit(ir)
            arguments = [n for n, _ in
                         zip(arguments_names, arguments_types)]
            name_fmt = pythran_ward + "{0}::{1}::type{2}"
            args_list = ", ".join(arguments_types)
            specialized_fname = name_fmt.format(module_name,
                                                internal_func_name,
                                                "<{0}>".format(args_list)
                                                if arguments_names else "")
            result_type = "typename %s::result_type" % specialized_fname
            docstring = spec_to_string(function_name, signature)
            mod.add_capsule(
                FunctionBody(
                    FunctionDeclaration(
                        Value(result_type, function_name),
                        [Value(t, a)
                         for t, a in zip(arguments_types, arguments)]),
                    Block([ReturnStatement("{0}()({1})".format(
                        warded(module_name, internal_func_name),
                        ', '.join(arguments)))])
                ),
                function_name,
                docstring
            )

    return mod, error_checker
49474
def get_module_plugins(module, classobj):
    
    try:
        names = module.__all__
    except AttributeError:
        names = [x for x in vars(module) if not x.startswith('_')]
    for name in names:
        try:
            obj = getattr(module, name)
        except AttributeError:
            continue
        try:
            if issubclass(obj, classobj):
                yield obj
        except TypeError:
            continue
988872
def _generate_client_m(self, api):
        """"""
        self.emit_raw(base_file_comment)

        import_classes = [self.args.module_name]
        import_classes += [
            fmt_routes_class(ns.name, self.args.auth_type)
            for ns in api.namespaces.values()
            if ns.routes and self.namespace_to_has_routes[ns]
        ]
        import_classes.append(
            '{}Protocol'.format(self.args.transport_client_name))
        self._generate_imports_m(import_classes)

        with self.block_m(self.args.class_name):
            client_args = fmt_func_args_declaration(
                [('client',
                  'id<{}>'.format(self.args.transport_client_name))])
            with self.block_func(
                    func='initWithTransportClient',
                    args=client_args,
                    return_type='instancetype'):
                self.emit('self = [super init];')

                with self.block_init():
                    self.emit('_transportClient = client;')
                    for namespace in api.namespaces.values():
                        if namespace.routes and self.namespace_to_has_routes[namespace]:
                            base_string = '_{}Routes = [[{} alloc] init:client];'
                            self.emit(
                                base_string.format(
                                    fmt_var(namespace.name),
                                    fmt_routes_class(namespace.name,
                                                     self.args.auth_type)))
223712
def _generate_routes_m(self, namespace):
        """"""
        with self.block_m(
                fmt_routes_class(namespace.name, self.args.auth_type)):
            init_args = fmt_func_args_declaration([(
                'client', 'id<{}>'.format(self.args.transport_client_name))])

            with self.block_func(
                    func='init', args=init_args, return_type='instancetype'):
                self.emit('self = [super init];')
                with self.block_init():
                    self.emit('_client = client;')
            self.emit()
            style_to_request = json.loads(self.args.z__style_to_request)

            for route in namespace.routes:
                if (route.attrs.get('auth') != self.args.auth_type
                        and route.attrs.get('auth') != 'noauth'):
                    continue

                route_type = route.attrs.get('style')
                client_args = json.loads(self.args.client_args)

                if route_type in client_args.keys():
                    for args_data in client_args[route_type]:
                        task_type_key, type_data_dict = tuple(args_data)
                        task_type_name = style_to_request[task_type_key]

                        func_suffix = type_data_dict[0]
                        extra_args = [
                            tuple(type_data[:-1])
                            for type_data in type_data_dict[1]
                        ]

                        if (is_struct_type(route.arg_data_type) and
                                self._struct_has_defaults(route.arg_data_type)):
                            route_args, _ = self._get_default_route_args(
                                namespace, route)
                            self._generate_route_m(route, namespace,
                                                   route_args, extra_args,
                                                   task_type_name, func_suffix)

                        route_args, _ = self._get_route_args(namespace, route)
                        self._generate_route_m(route, namespace, route_args,
                                               extra_args, task_type_name,
                                               func_suffix)
                else:
                    task_type_name = style_to_request[route_type]
                    if (is_struct_type(route.arg_data_type) and
                            self._struct_has_defaults(route.arg_data_type)):
                        route_args, _ = self._get_default_route_args(
                            namespace, route)
                        self._generate_route_m(route, namespace, route_args,
                                               [], task_type_name, '')

                    route_args, _ = self._get_route_args(namespace, route)
                    self._generate_route_m(route, namespace, route_args, [],
                                           task_type_name, '')
333276
function GENERATE_CLASS(name, description, namespace, parent) {
  return GENERATE_DOC(description + '\n' 
    + '@class ' + name + '\n'
    + (namespace ? ('@module ' + namespace + '\n') : '')
    /*
    TODO: leave out until figure out what swig does with inheritance
    + (parent ? ('@extends ' + parent + '\n') : '')
    */
  );
}
3011
def create_service_module(service_name, apis):
   
   service_module = imp.new_module(service_name.lower())

   for api in apis:
      setattr(service_module, api.__class__.__name__, api)

   ClientClass = create_rest_client_class(service_name, apis)

   setattr(service_module, 'resources', tuple(apis))
   setattr(service_module, 'Client', ClientClass)

   sys.modules[service_name.lower()] = service_module
   return service_module
900465
def _build_module_db(self):
        
        tdict = collections.defaultdict(lambda: [])
        for callable_name, callable_dict in self._exh_obj.callables_db.items():
            fname, line_no = callable_dict["code_id"]
            cname = (
                "{cls_name}.__init__".format(cls_name=callable_name)
                if callable_dict["type"] == "class"
                else callable_name
            )
            tdict[fname].append({"name": cname, "line": line_no})
        for fname in tdict.keys():
            self._module_obj_db[fname] = sorted(
                tdict[fname], key=lambda idict: idict["line"]
            )
148804
def include_sqlalchemy_models(nc, Base):
    

    from sqlalchemy.ext.declarative.clsregistry import _ModuleMarker

    # Include all SQLAlchemy models in the local namespace
    for name, klass in Base._decl_class_registry.items():
        print(name, klass)
        if isinstance(klass, _ModuleMarker):
            continue

        add_script(nc, get_import_statement(klass))
        add_greeting(nc, "* **{}** - {}".format(klass.__name__, get_dotted_path(klass)))
138166
def generate(env):
    ""
    
    client  = Builder(action=rpcgen_client,  suffix='_clnt.c', src_suffix='.x')
    header  = Builder(action=rpcgen_header,  suffix='.h',      src_suffix='.x')
    service = Builder(action=rpcgen_service, suffix='_svc.c',  src_suffix='.x')
    xdr     = Builder(action=rpcgen_xdr,     suffix='_xdr.c',  src_suffix='.x')
    env.Append(BUILDERS={'RPCGenClient'  : client,
                         'RPCGenHeader'  : header,
                         'RPCGenService' : service,
                         'RPCGenXDR'     : xdr})
    env['RPCGEN'] = 'rpcgen'
    env['RPCGENFLAGS'] = SCons.Util.CLVar('')
    env['RPCGENCLIENTFLAGS'] = SCons.Util.CLVar('')
    env['RPCGENHEADERFLAGS'] = SCons.Util.CLVar('')
    env['RPCGENSERVICEFLAGS'] = SCons.Util.CLVar('')
    env['RPCGENXDRFLAGS'] = SCons.Util.CLVar('')