def emit(self): has_methods = len(self.methods.values()) > 0 n = self.name if is_builtin(n): cog.outl( 'final PyObject %s_builtin = builtins.__getitem__("%s");' % (n, n)) cog.out('builtins.__setitem__("%s",' % n) if self.field: emit_python_prefix(self.field.getType()) cog.out('%s)' % n) else: cog.out('new PyObject()') if has_methods: cog.outl('{') if has_methods: cog.outl( '\tpublic PyObject __call__(final PyObject[] args, final String[] kws) {' ) cog.outl('\t\tswitch(args.length) {') cog.outl('\t\t\tdefault: ') cog.out('\t\t\t\t') if is_builtin(n): cog.outl('return %s_builtin.__call__(args, kws);' % n) else: cog.outl( 'throw new RuntimeException("Can\'t call \\"%s\\" with "' ' + args.length + " parameters."); ' % n) for k in sorted(self.methods.keys()): self.methods[k].emit() cog.outl('\t\t}\n\t}') if has_methods: cog.out('}') cog.outl(');')
def __generate_class_start(self, config): class_name = config['class'] cog.outl("#ifndef %s_H" % class_name.upper()) cog.outl("#define %s_H" % class_name.upper()) cog.out("\n\n\n") cog.outl("class %s\n{" % class_name) return
def inject_usage(module_name): """ Use cog_ to inject a usage message into a reStructuredText_ file. :param module_name: The name of the module whose ``__doc__`` attribute is the source of the usage message (a string). This simple wrapper around :func:`render_usage()` makes it very easy to inject a reformatted usage message into your documentation using cog_. To use it you add a fragment like the following to your ``*.rst`` file:: .. [[[cog .. from humanfriendly.usage import inject_usage .. inject_usage('humanfriendly.cli') .. ]]] .. [[[end]]] The lines in the fragment above are single line reStructuredText_ comments that are not copied to the output. Their purpose is to instruct cog_ where to inject the reformatted usage message. Once you've added these lines to your ``*.rst`` file, updating the rendered usage message becomes really simple thanks to cog_: .. code-block:: sh $ cog.py -r README.rst This will inject or replace the rendered usage message in your ``README.rst`` file with an up to date copy. .. _cog: http://nedbatchelder.com/code/cog/ """ import cog usage_text = import_module(module_name).__doc__ cog.out("\n" + render_usage(usage_text) + "\n\n")
def emit(self): has_methods = len(self.methods.values()) > 0 n = self.name if is_builtin(n): cog.outl('final PyObject %s_builtin = builtins.__getitem__("%s");' % (n, n)) cog.out('builtins.__setitem__("%s",' % n) if self.field: emit_python_prefix(self.field.getType()) cog.out('%s)' % n) else: cog.out('new PyObject()') if has_methods: cog.outl('{') if has_methods: cog.outl('\tpublic PyObject __call__(final PyObject[] args, final String[] kws) {') cog.outl('\t\tswitch(args.length) {') cog.outl('\t\t\tdefault: '); cog.out('\t\t\t\t') if is_builtin(n): cog.outl('return %s_builtin.__call__(args, kws);' % n) else: cog.outl('throw new RuntimeException("Can\'t call \\"%s\\" with "' ' + args.length + " parameters."); ' % n) for k in sorted(self.methods.keys()): self.methods[k].emit() cog.outl('\t\t}\n\t}') if has_methods: cog.out('}') cog.outl(');')
def include(filename, first=None, after=None, numlines=None, numblanks=None, dedent=True): """ Include text from a file. """ global LAST_LINES, LAST_FILENAME if filename != LAST_FILENAME: with open(filename) as f: lines = LAST_LINES = f.readlines() LAST_FILENAME = filename else: lines = LAST_LINES including = "".join( selected_lines(lines, first, after, numlines, numblanks)) if dedent: including = textwrap.dedent(including) cog.outl("```") cog.out(including) cog.outl("```")
def enhanced_enum(name, rows: Dict[str, dict], type_info=None): if type_info is None: type_info = { key: elm_type_by_python_type(type(value)) for key, value in list(rows.values())[0].items() } cog.out(_enhanced_enum(name=name, type_info=type_info, rows=rows))
def initVars(self,varnames): cog.outl("#define %s %d \n" %(varnames[0],len(self.lebedev_theata))) # allocate Lebedev quadrature points cog.outl("static const double %s [] = { %s };"%(varnames[1] , ",".join(['{:.20f}'.format(x) for x in self.lebedev_theata]))) cog.outl("static const double %s [] = { %s };"%(varnames[2] , ",".join(['{:.20f}'.format(x) for x in self.lebedev_phi]))) cog.outl("static const double %s [] = { %s };"%(varnames[3] , ",".join(['{:.20f}'.format(x) for x in self.lebedev_w]))) for l in self.lmodes: for m in range(-l,l+1): lm_value=[] for q in range(0,len(self.lebedev_theata)): lm_value.append(self.swsh(2,l,m,self.lebedev_theata[q],self.lebedev_phi[q])) if(m<0): cog.outl("static const DendroComplex %s_sp_%d_l_%d_m_minus_%d [] = { %s };"%(varnames[4],2,l,abs(m), ",".join(['DendroComplex({:.20f},{:.20f})'.format(x.real,x.imag) for x in lm_value]))) else: cog.outl("static const DendroComplex %s_sp_%d_l_%d_m_plus_%d [] = { %s };"%(varnames[4],2,l,abs(m), ",".join(['DendroComplex({:.20f},{:.20f})'.format(x.real,x.imag) for x in lm_value]))) ptr_str=[] for i in range(0,len(self.lmodes)): for m in range(-self.lmodes[i],self.lmodes[i]+1): if(m<0): ptr_str.append("%s_sp_%d_l_%d_m_minus_%d" %(varnames[4],2,self.lmodes[i],abs(m))) else: ptr_str.append("%s_sp_%d_l_%d_m_plus_%d" %(varnames[4],2,self.lmodes[i],abs(m))) cog.out("static const DendroComplex* %s[]={%s};" %(varnames[4],",".join(ptr_str)))
def generate_common_common(): global __generated_common_common if __generated_common_common: return __generated_common_common = True cog.out(__common_big_string)
def export_cr(class_name, function, return_type='void', args=[]): template = """// [[Rcpp::export]] ${return_type} ${class_name}__${function}(${definition}) { ${return_statement}forest::${function}(${call}); } """ d = build_dict(class_name, function, return_type, args, False) cog.out(tp(template, d))
def export_cr_method(class_name, function, return_type, args=[]): template = """// [[Rcpp::export]] ${return_type} ${class_name}__${function}(${definition}) { ${return_statement}tr.${function}(${call}); } """ d = build_dict(class_name, function, return_type, args, False, True) cog.out(tp(template, d))
def genehelp(subcommand=''): cmd = 'python -m neorg.commands %s -h' % subcommand po = Popen(cmd.split(), cwd='../..', stdout=PIPE, stderr=PIPE) (stdoutdata, stderrdata) = po.communicate() stdoutdata = stdoutdata.replace('commands.py', 'neorg', 1) cog.out('\n::\n\n') lines = (l if l == '' else ' ' + l for l in stdoutdata.splitlines()) cog.outl('\n'.join(lines)) cog.out('\n')
def emit_typecheck_expression(klass, name): try: cog.out(CONVERSIONS[klass].typecheck_format % {'name': name}) except (TypeError, KeyError): if klass.isPrimitive(): raise Exception("You need a converter for %s" % klass.getName()) cog.out('%s.getProxyType() != null ' '&& %s.getProxyType() == %s.class' % (name, name, Class.getSimpleName(klass)))
def generate_enum_common(): global __generated_enum_common if __generated_enum_common: return generate_common_common() __generated_enum_common = True cog.out(__enum_big_string)
def export_ptr_method(class_name, function, return_type='void', args=[]): template = """// [[Rcpp::export]] ${return_type} ${class_name}__${function}(${definition}) { Rcpp::XPtr<forest::${class_name}> ptr = forest::exporters::ptr_${tree_type}_from_R<forest::forest_node>(x); ${return_statement}ptr->${function}(${call}); } """ d = build_dict(class_name, function, return_type, args, True, True) cog.out(tp(template, d))
def genehelp(subcommand=''): cmd = 'python -m neorg.commands %s -h' % subcommand po = Popen(cmd.split(), cwd='../..', stdout=PIPE, stderr=PIPE) (stdoutdata, stderrdata) = po.communicate() stdoutdata = stdoutdata.replace('commands.py', 'neorg', 1) cog.out('\n::\n\n') lines = (l if l=='' else' ' + l for l in stdoutdata.splitlines()) cog.outl('\n'.join(lines)) cog.out('\n')
def wrap(*a, **kw): sys.stderr.write('\n{}({}, {})\n'.format(f.__name__, a, kw)) buf = io.StringIO() sys.stdout = buf f(*a, **kw) sys.stdout = sys.__stdout__ results = buf.getvalue() sys.stderr.write(results) sys.stderr.write('\n') cog.out(results) return results
def output_cconf_entry(self): cog.out("\tVSHADER(\"" + self.filename + "\", ") if self.unif_funname != "": cog.out("&sp_unif_" + self.unif_funname + ",\n\t") else: cog.out("NULL,\n\t") for loc in self.locations[0:-1]: cog.out("LOC(sp_" + loc[0] + "_loc, " + str(loc[1]) + "), ") loc = self.locations[-1] cog.out("LOC(sp_" + loc[0] + "_loc, " + str(loc[1]) + ")") cog.outl("),")
def interact(mod, snippet): exec ('from %s import *' % mod) in snippet_namespace, snippet_namespace skipping = True script = extract_session(snippet_namespace, 'snippet%d' % snippet) # Capture stdout, stderr old_stdin, old_stdout, old_stderr = sys.stdin, sys.stdout, sys.stderr sys.stdout = sys.stderr = stdout = StringIO() sys.stdin = EchoingStringIO(stdout, script) console = code.InteractiveConsole(snippet_namespace) console.interact('') sys.stdin, sys.stdout, sys.stderr = old_stdin, old_stdout, old_stderr # cog.out('.. ' + script.replace('\n', '\n.. ')) output = stdout.getvalue()[:-5] cog.out(output) cog.outl()
def interact(mod, snippet): exec('from %s import *' % mod) in snippet_namespace, snippet_namespace skipping = True script = extract_session(snippet_namespace, 'snippet%d' % snippet) # Capture stdout, stderr old_stdin, old_stdout, old_stderr = sys.stdin, sys.stdout, sys.stderr sys.stdout = sys.stderr = stdout = StringIO() sys.stdin = EchoingStringIO(stdout, script) console = code.InteractiveConsole(snippet_namespace) console.interact('') sys.stdin, sys.stdout, sys.stderr = old_stdin, old_stdout, old_stderr # cog.out('.. ' + script.replace('\n', '\n.. ')) output = stdout.getvalue()[:-5] cog.out(output) cog.outl()
def inject_documentation(**options): """ Generate configuration documentation in reStructuredText_ syntax. :param options: Any keyword arguments are passed on to the :class:`ConfigLoader` initializer. This methods injects the generated documentation into the output generated by cog_. .. _cog: https://pypi.python.org/pypi/cogapp """ import cog loader = ConfigLoader(**options) cog.out("\n" + loader.documentation + "\n\n")
def list_of(name, items, start_char='[', end_char=']', item_separator_char=',', single_line=False): cog.out( _list_of( name=name, items=items, start_char=start_char, end_char=end_char, item_separator_char=item_separator_char, single_line=single_line, ))
def list_of(name, items, *, start_char='[', end_char=']', item_separator_char=',', single_line=False): cog.outl(f'{name} =') f = _list_single_line if single_line else _list cog.out( indent( f( items=items, start_char=start_char, end_char=end_char, item_separator_char=item_separator_char, )))
def integrate_algorithms(return_type, category, algorithms, storage): method = """ ${return_type} run_${category}() { switch(s.algorithm_id()) {${switch} default: util::stop("Unimplemented algorithm"); // TODO: give details return ${return_type}(); // never get here } }""" switch = """ case stepper::${ALGORITHM}: return run<stepper_${category}_${algorithm}_${storage}>();""" d = {'return_type': return_type, 'switch': '', 'category': category, 'storage': storage} for t in algorithms[category]: d['switch'] += tp(switch, dappend(d, 'algorithm', t)) cog.out(tp(method, d))
def include_with_syntax(filename, start=None, end=None, lexer=None): """Includes the text of an external file, highlighting with pygments.""" import pygments import pygments.lexers import cog with open(filename, 'r') as f: text = f.read() if lexer is None: lexer = pygments.lexers.guess_lexer_for_filename(filename, text) elif isinstance(lexer, basestring): lexer = pygments.lexers.get_lexer_by_name(lexer) formatter = get_syntax_formatter() text = _subset_lines(text, start, end) cog.out(pygments.highlight(text, lexer, formatter))
def output_row(bytes, encoding, labels): cog.out("<tr class='chars'>") if labels: cog.out("<td class='label'>{0}</td>".format(encoding)) for b, c in zip(*show_decode(bytes, encoding)): if len(b) > 1: span = " colspan='{0}'".format(len(b)) else: span = "" cog.out("<td{0}>&#x{1:x};</td>".format(span, ord(c))) cog.out("</tr>\n")
def include(filename, first=None, after=None, numlines=None, numblanks=None, dedent=True): """ Include text from a file. """ global LAST_LINES, LAST_FILENAME if filename != LAST_FILENAME: with open(filename) as f: lines = LAST_LINES = f.readlines() LAST_FILENAME = filename else: lines = LAST_LINES including = "".join(selected_lines(lines, first, after, numlines, numblanks)) if dedent: including = textwrap.dedent(including) cog.outl("```") cog.out(including) cog.outl("```")
def integrate(return_type, algorithms, storage): method = """ ${return_type} run() { switch(s.category_id()) {${switch} default: util::stop("Unimplemented category"); // TODO: give details return ${return_type}(); // never get here } }""" switch = """ case stepper::${CATEGORY}: return run_${category}();""" cog.outl(header) d = {'return_type': return_type, 'switch': ''} for c in categories: d['switch'] += tp(switch, dappend(d, 'category', c)) cog.out(tp(method, d)) for c in categories: integrate_algorithms(return_type, c, algorithms, storage)
def generate_context(platform): registers = contexts[platform] cog.outl("typedef struct {") for reg in registers: if reg.generic_name: cog.out(" union {") if reg.comment: cog.outl(" // {}".format(reg.comment)) else: cog.outl("") cog.outl(" size_t {};".format(reg.platform_name)) cog.outl(" size_t {};".format(reg.generic_name)) cog.outl(" };") else: cog.out(" size_t {};".format(reg.platform_name)) if reg.comment: cog.outl(" // {}".format(reg.comment)) else: cog.outl("") cog.outl("} __attribute__((packed)) RegisterContext;")
def pxd_write_proxy_class( proxy_name, defs ): """writes the pxd declaration of the same class that was created using 'cpp_write_proxy_class' for C++ above. This should be used inside 'cdef extern from "somefile.h":' section""" cog.outl('# generated using cog (as far as the [[end]] bit:') for thisdef in defs: ( name, returnType, parameters ) = thisdef cog.out('ctypedef ' + returnType + '(*' + proxy_name + '_' + name + 'Def)(') for parameter in parameters: (ptype,pname) = parameter cog.out( ptype + ' ' + pname + ',') cog.outl( ' void *pyObject)') cog.outl( 'cdef cppclass ' + proxy_name + ':') cog.outl( ' ' + proxy_name + '(void *pyObject)') cog.outl( '' ) for thisdef in defs: ( name, returnType, parameters ) = thisdef cog.outl( ' void set' + upperFirst( name ) + ' ( ' + proxy_name + '_' + name + 'Def c' + upperFirst( name ) + ' )')
def emit_python_prefix(klass): try: cog.out(CONVERSIONS[klass].to_python_prefix) except (KeyError, AttributeError): if klass.isPrimitive(): raise Exception("You need a converter for %s" % klass.getName()) cog.out('Py.java2py') cog.out('(')
def emit_method(self, m): if m.getReturnType() is not Void.TYPE: cog.out('return ') emit_python_prefix(m.getReturnType()) cog.out('%s(' % self.name) for i in range(self.arity): if i > 0: cog.out(', ') emit_java_expression(m.getParameterTypes()[i], 'args[%d]' % i) cog.out(')') if m.getReturnType() is Void.TYPE: cog.outl(';') cog.outl('\t\t\t\treturn Py.None;') else: cog.outl(');')
def __generate_data(self, config): cog.outl("class %s::%s\n{" % (self.class_name, self.data_name)) cog.outl("\t\tpublic:") for item in config['private_data']: name = item['name'] returns = tryRead(item, 'returns') cog.outl("\t\t%s\t%s;" % (returns, name)) cog.outl('\t\t%s():' % self.data_name) first = True for item in config['private_data']: name = item['name'] default = tryRead(item, 'default') if first: cog.out("\t\t\t%s(%s)" % (name, default)) first = False else: cog.out("\n\t\t\t, %s(%s)" % (name, default)) cog.outl('{\n\t\t}') cog.outl("};\n") return
def emit_java_expression(klass, name): try: cog.out(CONVERSIONS[klass].to_java_format % name) except KeyError: if klass.isPrimitive(): raise Exception("You need a converter for %s" % klass.getName()) simpleName = Class.getName(klass) if klass.isArray(): simpleName = Class.getSimpleName(klass) if simpleName != 'java.lang.Object': cog.out('(%s)' % simpleName) cog.out('%s.__tojava__(%s.class)' % (name, simpleName))
def firRic1(self): file_name = "firRic1.s" cog.outl("; Automatically Generated Code") line_item_count = 10 for row in self.taps_hword: if line_item_count >= 9: cog.out("\n.hword ") line_item_count = 0 else: cog.out(",") cog.out(" 0x" + row['hex']) line_item_count += 1
def whitespace(): global _has_started_whitespace if not _has_started_whitespace: should_surround = True _has_started_whitespace = True else: should_surround = False cog.out('\n\n') yield if should_surround: cog.out('\n\n\n\n') else: cog.out('\n') if should_surround: _has_started_whitespace = False
def generate(self): generate_cppclass_common() cog.out("namespace %s {\n" "\n" % self.name) cog.out("class data\n" "{\n" "public:") cog.out(_body % { "name": self.name, "forAllMembersBody": self.__gen_for_all_members() }) cog.out("private:\n") for f in self.fields: if f.type: cog.out(" %s %s_;\n" % (sanitizeTypename(f.type), f.name.lower())) cog.out("}; // class data\n\n") for f in self.fields: if f.type: cog.out( "template<>\n" "inline %(name)s_INFO::type& data::get_member<%(name)s_INFO>()\n" "{\n" " return %(lower_name)s_;\n" "}\n\n" % { "name": f.name, "lower_name": f.name.lower() }) for f in self.fields: if f.type: cog.out( "template<>\n" "inline %(name)s_INFO::type const& data::get_member<%(name)s_INFO>() const\n" "{\n" " return %(lower_name)s_;\n" "}\n\n" % { "name": f.name, "lower_name": f.name.lower() }) cog.out("} // namespace %s\n" % self.name)
def generate(self): generate_cppclass_common() cog.out("namespace %s {\n" "\n" % self.name) cog.out("class data\n" "{\n" "public:") cog.out(_body % {"name": self.name, "forAllMembersBody": self.__gen_for_all_members()}) cog.out("private:\n") for f in self.fields: if f.type: cog.out(" %s %s_;\n" % (sanitizeTypename(f.type), f.name.lower())) cog.out("}; // class data\n\n") for f in self.fields: if f.type: cog.out( "template<>\n" "inline %(name)s_INFO::type& data::get_member<%(name)s_INFO>()\n" "{\n" " return %(lower_name)s_;\n" "}\n\n" % {"name": f.name, "lower_name": f.name.lower()} ) for f in self.fields: if f.type: cog.out( "template<>\n" "inline %(name)s_INFO::type const& data::get_member<%(name)s_INFO>() const\n" "{\n" " return %(lower_name)s_;\n" "}\n\n" % {"name": f.name, "lower_name": f.name.lower()} ) cog.out("} // namespace %s\n" % self.name)
def enhanced_enum(name, rows, type_info=None): cog.out(_enhanced_enum(name=name, type_info=type_info, rows=rows))
def record(name, definition): cog.out(_named_record(name=name, definition=definition))
def type_alias_with_json(name, type_info, decoder=True, encoder=True): cog.out( _type_alias_with_json(name=name, type_info=type_info, decoder=decoder, encoder=encoder))
def encoder_for_type_alias(name, type_info): cog.out(_encoder(name=name, type_info=type_info))
def type_alias(name, type_info): cog.out(_type_alias(name=name, type_info=type_info)) return dict(name=name, type_info=type_info)
def enum(name, definition): cog.out(_enum(name=name, definition=definition))
def union(name, definition): cog.out(_union(name=name, definition=definition))
""" IMPLEMENTS_STR = """ <TABHERE><TABHERE>adapter = ic.createObjectAdapter('<NORMAL>') <TABHERE><TABHERE>adapter.add(<NORMAL>I(worker), ic.stringToIdentity('<LOWER>')) <TABHERE><TABHERE>adapter.activate() """ ]]] [[[end]]] # # Copyright (C) [[[cog A() import datetime cog.out(' '+str(datetime.date.today().year)) Z() ]]] [[[end]]] by YOUR NAME HERE # # This file is part of RoboComp # # RoboComp is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # RoboComp is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
def inject_literal_block(desc, lines): cog.out("\n{0}::\n\n".format(desc)) cog.outl("\n".join(indent_lines(lines))) cog.outl()
def Z(): cog.out('>@@>')
def A(): cog.out('<@@<')
def TAB(): cog.out('<TABHERE>')
from parseIDSL import * pool = IDSLPool(theIDSLs) def replaceTypeCPP2Python(t): t = t.replace('::','.') t = t.replace('string', 'str') return t ]]] [[[end]]] # # Copyright (C) [[[cog A() import datetime cog.out(' '+str(datetime.date.today().year)) Z() ]]] [[[end]]] by YOUR NAME HERE # # This file is part of RoboComp # # RoboComp is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # RoboComp is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the