Esempio n. 1
0
def definition(
    name: str,
    default_operation: DefaultOperation,
    qualified_name: typing.Optional[str] = None,
    templates: typing.Optional[typing.List[str]] = None,
) -> None:
    output = ""
    output += "// NOLINTBEGIN\n"
    output += "// clang-format off\n"

    _name = qualified_name if qualified_name is not None else name

    for template in templates:
        output += f"{template}\n"

    if default_operation == DefaultOperation.CONSTRUCTOR:
        output += f"{_name}::{name}()\n"
    if default_operation == DefaultOperation.COPY_CONSTRUCTOR:
        output += f"{_name}::{name}(const {name} & _other)\n"
    if default_operation == DefaultOperation.COPY_ASSIGNMENT:
        output += f"auto {_name}::operator=(const {name} & _other) -> {_name} &\n"
    if default_operation == DefaultOperation.MOVE_CONSTRUCTOR:
        output += f"{_name}::{name}({name} && _other) noexcept\n"
    if default_operation == DefaultOperation.MOVE_ASSIGNMENT:
        output += f"auto {_name}::operator=({name} && _other) noexcept -> {_name} &\n"
    if default_operation == DefaultOperation.DESTRUCTOR:
        output += f"{_name}::~{name}()\n"

    output += "// clang-format on\n"
    output += "// NOLINTEND"

    cog.outl(output)
Esempio n. 2
0
File: ast.py Progetto: mbeckem/tiro
def implement(*node_types):
    templ = ENV.get_template("ast.jinja2")
    for index, node_type in enumerate(node_types):
        if index > 0:
            cog.outl()

        cog.outl(templ.module.node_impl(node_type))
Esempio n. 3
0
def declarations(
    name: str,
    constructor: bool = True,
    copy_constructor: bool = True,
    copy_assignment: bool = True,
    move_constructor: bool = True,
    move_assignment: bool = True,
    destructor: bool = True,
) -> None:
    output = ""
    output += "    // NOLINTBEGIN\n"
    output += "    // clang-format off\n"

    if constructor:
        output += f"    {name}();\n"
    if copy_constructor:
        output += f"    {name}(const {name} & _other);\n"
    if copy_assignment:
        output += f"    auto operator=(const {name} & _other) -> {name} &;\n"
    if move_constructor:
        output += f"    {name}({name} && _other) noexcept;\n"
    if move_assignment:
        output += f"    auto operator=({name} && _other) noexcept -> {name} &;\n"
    if destructor:
        output += f"    virtual ~{name}();\n"

    output += "    // clang-format on\n"
    output += "    // NOLINTEND"

    cog.outl(output)
def category_h_guard(category_file):
    category = category_for_file(category_file, models)

    guard = category.struct_name.lower(
    ) + "_h"  # TODO Could just use the file name
    cog.outl('#ifndef {0}'.format(guard))
    cog.outl('#define {0}'.format(guard))
Esempio n. 5
0
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 write_options(optionsList):
    cog.outl('// generated, using cog:')
    for option in optionsList:
        optionTcase = option[0].upper() + option[1:]
        gOption = 'g' + optionTcase
        cog.outl('options += " -D' + gOption + '=" + toString( ' + option +
                 ' );')
 def emit(self):
     cog.outl('\t\t\tcase %d: {' % self.arity)
     if len(self.methods) == 1 and not is_builtin(self.name):
         cog.out('\t\t\t\t')
         self.emit_method(self.methods[0])
     else:
         for i in range(self.arity):
             cog.outl('\t\t\t\tfinal PyType t%d = args[%d].getType();' % (i, i))
         self.methods.sort(key=lambda p: [m.getSimpleName()
                                          for m in p.getParameterTypes()],
                            reverse=True)
         for i in range(len(self.methods)):
             m = self.methods[i]
             if i > 0:
                 cog.out(' else ')
             else:
                 cog.out('\t\t\t\t')
             if self.arity > 0:
                 cog.out('if (')
                 for j in range(self.arity):
                     if j > 0:
                         cog.out(' && ')
                     emit_typecheck_expression(m.getParameterTypes()[j], 
                                               't%d' % j)
                 cog.out(') {\n\t\t\t\t\t')
             self.emit_method(m)
             if self.arity > 0:
                 cog.out('\t\t\t\t}') 
         if is_builtin(self.name):
             cog.outl(' else { return %s_builtin.__call__(args, kws); }' % self.name)
         elif self.arity > 0:
             cog.outl(' else { throw new UnexpectedInvocationError'
                      '("%s", args, kws); }' % self.name)  
     cog.outl('\t\t\t}')
Esempio n. 8
0
def include(filename, start=None, end=None):
    """Include the text of an external file verbatim."""
    import cog
    with open(filename, 'r') as f:
        text = f.read()
    text = _subset_lines(text, start, end)
    cog.outl(text)
Esempio n. 9
0
def write_file2(filepath):
    f = open(filepath, 'r')
    line = f.readline()
    while(line != ''):
        line = process_includes(line)
        cog.outl('"' + line.rstrip().replace('\\','\\\\').replace('"', '\\"') + '\\n"')
        line = f.readline()
    f.close()
Esempio n. 10
0
def write_file2(filepath):
    f = open(filepath, "r")
    line = f.readline()
    while line != "":
        line = process_includes(line)
        cog.outl('"' + line.rstrip().replace("\\", "\\\\").replace('"', '\\"') + '\\n" ')
        line = f.readline()
    f.close()
Esempio n. 11
0
def _implement_inlines(T):
    if T.kind == "tag":
        pass
    elif T.kind == "union":
        templ = ENV.get_template("unions.jinja2")
        cog.outl(templ.module.union_inline_impl(T))
    else:
        raise RuntimeError("Invalid type.")
Esempio n. 12
0
def output_cconf2():
    for cstruct in cstructs2:
        assert len(cstruct) > 0
        cstruct[0].output_cconf_start()
        for elt in cstruct:
            elt.output_cconf_entry()
        cstruct[0].output_cconf_end()
        cog.outl("")
Esempio n. 13
0
def _prompt_session(ver, in1, in2=None):
    if in2:
        prefix, input = in1, in2
    else:
        prefix, input = None, in1
    output = cagedprompt.prompt_session(input, prefix)
    cog.outl("<div class='version-marker'>%s</div>" % ver)
    pre_lines(output.strip().split("\n"), "language-python language-python-%d" % ver)
Esempio n. 14
0
def write_file2( filepath ):
    f = open( filepath, 'r')
    line = f.readline()
    while( line != '' ):
        line = process_includes( line )
        cog.outl( '"' + line.rstrip().replace('\\','\\\\').replace('"', '\\"') + '\\n" ' )
        line = f.readline()
    f.close()
Esempio n. 15
0
def _define(T):
    if T.kind == "tag":
        templ = ENV.get_template("union_tag.jinja2")
        cog.outl(templ.module.tag_def(T))
    elif T.kind == "union":
        templ = ENV.get_template("unions.jinja2")
        cog.outl(templ.module.union_def(T))
    else:
        raise RuntimeError("Invalid type.")
Esempio n. 16
0
def process_includes( line ):
    if line.strip().find('#include') != 0:
        return line
    line = line.replace('<','"').replace('>','"') # standardize quotes a bit...
    targetpath = line.split('"')[1]
    line = ''
    cog.outl('// including ' + targetpath + ':')
    write_file2( '../' + targetpath )
    return line
Esempio n. 17
0
def tutor_a_tag(code):
    """
    Produce an <a> tag to pythontutor.com.
    """
    tutor_url_fmt = 'http://pythontutor.com/visualize.html#code={code}&mode=display&cumulative=false&heapPrimitives=false&drawParentPointers=false&textReferences=false&showOnlyOutputs=false&py=2'
    url_code = urllib.quote(textwrap.dedent(code))
    url = tutor_url_fmt.replace('&', '&amp;').format(code=url_code)
    html = "<a href='{url}' target='_blank'>".format(url=url)
    cog.outl(html)
Esempio n. 18
0
def process_includes(line):
    if line.strip().find('#include') != 0:
        return line
    line = line.replace('<','"').replace('>','"') # standardize quotes a bit...
    targetpath = line.split('"')[1]
    line = ''
    cog.outl('"// including ' + targetpath + ':\\n"')
    write_file2(targetpath)
    return line
Esempio n. 19
0
def output_enums():
    for cstruct in cstructs:
        if len(cstruct) == 0:
            continue
        cstruct[0].output_enum_start()
        for elt in cstruct:
            elt.output_enum_line()
        cstruct[0].output_enum_end()
        cog.outl("")
Esempio n. 20
0
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')
Esempio n. 21
0
def tutor_a_tag(code):
    """
    Produce an <a> tag to pythontutor.com.
    """
    tutor_url_fmt = 'http://pythontutor.com/visualize.html#code={code}&mode=display&cumulative=false&heapPrimitives=false&drawParentPointers=false&textReferences=false&showOnlyOutputs=false&py=2'
    url_code = urllib.quote(textwrap.dedent(code))
    url = tutor_url_fmt.replace('&', '&amp;').format(code=url_code)
    html = "<a href='{url}' target='_blank'>".format(url=url)
    cog.outl(html)
Esempio n. 22
0
def screenshot(cmd, fname):
    logging.info('%s %s',cmd, fname)
    fpath = 'docs/_img/%s' % fname
    if os.path.exists(fpath):
        os.remove(fpath)
    with SmartDisplay(visible=0, bgcolor='black') as disp:
        with EasyProcess(cmd):
            img = disp.waitgrab()
            img.save(fpath)
            cog.outl('.. image:: _img/%s' % fname)
Esempio n. 23
0
	def output_cconf_entry(self):
		self.col = 3
		self.maxcol = 78
		self.printstr("\tOB(sp_" + self.model + "_model")
		for k, v in self.kwargs:
			if k == sca:
				s = str(float(v)) + 'f'
				self.printstr(', ob_sca, OTOV3(' + s+', '+s+', '+s + ')')
			# printstr("ob_" + str(k) + ', ')
		cog.outl(');')
Esempio n. 24
0
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')
Esempio n. 25
0
def screenshot(cmd, fname):
    logging.info("%s %s", cmd, fname)
    fpath = "docs/_img/%s" % fname
    if os.path.exists(fpath):
        os.remove(fpath)
    with SmartDisplay(visible=0, bgcolor="black") as disp:
        with EasyProcess(cmd):
            img = disp.waitgrab()
            img.save(fpath)
            cog.outl(".. image:: _img/%s" % fname)
Esempio n. 26
0
    def __generate_class_body(self, config):
        cog.outl(code_separator)
        data_str = ''
        if 'private_data' in config.keys():
            data_str = " : d_data(new %s())" % self.data_name
        cog.outl("%s::%s() %s" % (self.class_name, self.class_name, data_str))
        cog.outl(braces)
        cog.outl("%s::~%s()" % (self.class_name, self.class_name))
        cog.outl(braces)

        return
Esempio n. 27
0
 def __generate_methods(self, config):
     cog.outl("\t\t// Methods")
     vis_list = ['public', 'private', 'protected']
     for visibility in vis_list:
         self.vis.set(visibility)
         for item in dictlistSelect(config['methods'], 'visibility', visibility):
             name = item['name']
             returns = tryRead(item, 'returns')
             arguments = tryRead(item, 'arguments')
             modifier = tryRead(item, 'modifier')
             cog.outl("\t\t%s\t%s(%s) %s;" % (returns, name, arguments, modifier))
     return
Esempio n. 28
0
def genProto(protoName, vecSize=1, inArgs=1, outArgs=1):
    _checkVecSize(vecSize)
    llvmType = _getLLVMType(vecSize)
    if inArgs == 1 and outArgs == 1:
        cog.outl("declare {0} @{1}({0} %ins) nounwind readnone".format(
            llvmType, protoName))
    elif inArgs == 2 and outArgs == 1:
        cog.outl(
            "declare {0} @{1}({0} %ins, {0} %ins2) nounwind readnone".format(
                llvmType, protoName))
    else:
        raise ValueError("Invalid in or out-args size")
Esempio n. 29
0
	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("),")
Esempio n. 30
0
def write_kernel3(kernelVarName, kernel_filename, kernelName, options):
    # cog.outl('string kernelFilename = "'  + kernel_filename + '";')
    cog.outl('// generated using cog:')
    f = open(kernel_filename, 'r')
    line = f.readline()
    cog.outl('const char * ' + kernelVarName + 'Source =  R"DELIM(\n')
    while(line != ''):
        cog.outl('' + line.rstrip())
        line = f.readline()
    cog.outl(')DELIM";')
    f.close()
    cog.outl(kernelVarName + ' = cl->buildKernelFromString(' + kernelVarName + 'Source, "' + kernelName + '", ' + options + ', "' + kernel_filename + '");')
Esempio n. 31
0
def write_kernel3( kernelVarName, kernel_filename, kernelName, options ):
    # cog.outl( 'string kernelFilename = "'  + kernel_filename + '";' )
    cog.outl( '// generated using cog:' )
    f = open( '../' + kernel_filename, 'r')
    line = f.readline()
    cog.outl( 'const char * ' + kernelVarName + 'Source =  R"DELIM(\n' )
    while( line != '' ):
        cog.outl( '' + line.rstrip() )
        line = f.readline()
    cog.outl( ')DELIM";')
    f.close()
    cog.outl( kernelVarName + ' = cl->buildKernelFromString( ' + kernelVarName + 'Source, "' + kernelName + '", ' + options + ', "' + kernel_filename + '" );' )
Esempio n. 32
0
 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
Esempio n. 33
0
    def img(self, alt=""):
        assert os.path.isdir(self.DOT_DIR), "%r must be an existing directory" % self.DOT_DIR

        dot_file = 'd{0:03d}.png'.format(next(self.diagram_id))
        dot_path = os.path.join(self.DOT_DIR, dot_file)

        ok, output = self.make_png(dot_path)
        if not ok:
            raise Exception("dot couldn't process at line {0}:\n{1}".format(cog.firstLineNum, output))

        full_path = "/".join([self.HERE, self.DOT_DIR, dot_file])
        alt = alt or self.default_alt
        cog.outl('<img src="{0}" alt="{1}" align="top" scale="0.5"/>'.format(full_path, cgi.escape(alt, quote=True)))
Esempio n. 34
0
    def img(self, alt=""):
        assert os.path.isdir(self.DOT_DIR), "%r must be an existing directory" % self.DOT_DIR

        dot_file = 'd{0:03d}.png'.format(next(self.diagram_id))
        dot_path = os.path.join(self.DOT_DIR, dot_file)

        ok, output = self.make_png(dot_path)
        if not ok:
            raise Exception("dot couldn't process at line {0}:\n{1}".format(cog.firstLineNum, output))

        full_path = "/".join([self.HERE, self.DOT_DIR, dot_file])
        alt = alt or self.default_alt
        cog.outl('<img src="{0}" alt="{1}" align="top" scale="0.5"/>'.format(full_path, cgi.escape(alt, quote=True)))
Esempio n. 35
0
def write_kernel2(kernelVarName, kernel_filename, kernelName, options):
    # cog.outl('string kernelFilename = "'  + kernel_filename + '";')
    cog.outl('// generated using cog, from ' + kernel_filename + ':')
    cog.outl('const char * ' + kernelVarName + 'Source =  ')
    write_file2(kernel_filename)
    cog.outl('"";')
    cog.outl(kernelVarName + ' = cl->buildKernelFromString(' + kernelVarName + 'Source, "' + kernelName + '", ' + options + ', "' + kernel_filename + '");')
Esempio n. 36
0
def write_kernel2( kernelVarName, kernel_filename, kernelName, options ):
    # cog.outl( 'string kernelFilename = "'  + kernel_filename + '";' )
    cog.outl( '// generated using cog:' )
    cog.outl( 'const char * ' + kernelVarName + 'Source =  ' )
    write_file2( '../' + kernel_filename )
    cog.outl( '"";')
    cog.outl( kernelVarName + ' = cl->buildKernelFromString( ' + kernelVarName + 'Source, "' + kernelName + '", ' + options + ', "' + kernel_filename + '" );' )
Esempio n. 37
0
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()
Esempio n. 38
0
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()
Esempio n. 39
0
	def output_cconf_entry(self):
		self.col = 3
		self.maxcol = 80
		self.printstr("\tMESH(")
		self.printstr(self.usage) #usage
		self.printstr(", " + "sp_" + self.program + "_program") #prog
		self.printstr(", " + "sp_" + self.objfile_enum + "_objfile")
		self.printstr(", " + "&sp_meshfill_" + self.name) #primary_fill
		self.printstr(", " + self.recenter)
		self.printstr(", " + "sp_" + self.grp_enum + "_ebogrouping")
		self.printstr(", " + self.vert_before)
		self.printstr(", " + "sp_" + self.tex_enum + "_texwrapping")
		self.maxcol = 78
		self.printstr(", " + "{" + str(self.texscale[0]) + "f, "
					  + str(self.texscale[1]) + "f}")
		cog.outl('),')
Esempio n. 40
0
	def output_cconf_entry(self):
		self.col = 3
		self.maxcol = 80
		self.printstr("\tPROG(sp_" + self.vsname + "_vshader")
		self.printstr(", sp_" + self.fsname + "_fshader")
		self.printstr(", sp_" + self.gsname + "_gshader")
		self.printstr(", sp_" + self.tcsname + "_tcshader")
		self.printstr(", sp_" + self.tesname + "_teshader")
		self.printstr(", sp_" + self.sboxprog + "_program")
		self.printstr(", TEXI(")
		self.printstr(str(self.img1))
		self.printstr(", " + str(self.img2))
		self.printstr(", " + str(self.img3))
		self.maxcol = 78
		self.printstr(", " + str(self.sbox) + ")")
		cog.outl("),");
Esempio n. 41
0
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,
            )))
Esempio n. 42
0
def write_kernel( var_name, kernel_filename ):
    cog.outl( 'string kernelFilename = "'  + kernel_filename + '";' )
    f = open( kernel_filename, 'r')
    line = f.readline()
    cog.outl( 'const char * '  + var_name + ' =  ' )
    while( line != '' ):
        cog.outl( '"' + line.strip().replace('\\','\\\\') + '\\n" ' )
        line = f.readline()
    cog.outl( '"";')
    f.close()
Esempio n. 43
0
def write_kernel(var_name, kernel_filename):
    cog.outl('string kernelFilename = "' + kernel_filename + '";')
    f = open(kernel_filename, 'r')
    line = f.readline()
    cog.outl('const char * ' + var_name + ' =  ')
    while (line != ''):
        cog.outl('"' + line.strip().replace('\\', '\\\\') + '\\n" ')
        line = f.readline()
    cog.outl('"";')
    f.close()
Esempio n. 44
0
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)
Esempio n. 45
0
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("```")
Esempio n. 46
0
    def __generate_methods(self, config):
        vis_list = ['public', 'private', 'protected']

        for visibility in vis_list:
            cog.outl('// %s METHODS' % visibility.upper())
            for item in dictlistSelect(config['methods'], 'visibility', visibility):
                name = item['name']
                returns = tryRead(item, 'returns')
                arguments = tryRead(item, 'arguments')
                modifier = tryRead(item, 'modifier')
                cog.outl(code_separator)
                cog.outl("%s\t%s::%s(%s) %s" % (returns, self.class_name, name, arguments, modifier))
                cog.outl(braces)
        return
Esempio n. 47
0
 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
Esempio n. 48
0
 def __generate_class_end(self, config):
     class_name = config['class']
     self.vis.set('public')
     cog.outl("\t\t%s();" % class_name)
     cog.outl("\t\tvirtual ~%s();" % class_name )
     cog.outl("};\n\n#endif //%s_H" % class_name.upper())
     return
Esempio n. 49
0
def write_kernel3(kernelVarName, kernel_filename, kernelName, options):
    # cog.outl( 'string kernelFilename = "'  + kernel_filename + '";' )
    cog.outl("// generated using cog:")
    f = open(kernel_filename, "r")
    line = f.readline()
    cog.outl("const char * " + kernelVarName + 'Source =  R"DELIM(\n')
    while line != "":
        cog.outl("" + line.rstrip())
        line = f.readline()
    cog.outl(')DELIM";')
    f.close()
    cog.outl(
        kernelVarName
        + " = cl->buildKernelFromString( "
        + kernelVarName
        + 'Source, "'
        + kernelName
        + '", '
        + options
        + ', "'
        + kernel_filename
        + '" );'
    )
Esempio n. 50
0
 def __generate_properties(self, config):
     self.vis.set('public')
     cog.outl("\t\t// Property get / set")
     for item in config['properties']:
         name = item['name']
         returns = tryRead(item, 'returns')
         cog.outl("\t\tvoid set%s(const %s value);" % (firstUppper(name), returns))
         cog.outl("\t\t%s\t%s() const;\n" % (returns, name))
     return
Esempio n. 51
0
 def emit(self):
     cog.outl('\t\t\tcase %d: {' % self.arity)
     if len(self.methods) == 1 and not is_builtin(self.name):
         cog.out('\t\t\t\t')
         self.emit_method(self.methods[0])
     else:
         for i in range(self.arity):
             cog.outl('\t\t\t\tfinal PyType t%d = args[%d].getType();' %
                      (i, i))
         self.methods.sort(
             key=lambda p:
             [m.getSimpleName() for m in p.getParameterTypes()],
             reverse=True)
         for i in range(len(self.methods)):
             m = self.methods[i]
             if i > 0:
                 cog.out(' else ')
             else:
                 cog.out('\t\t\t\t')
             if self.arity > 0:
                 cog.out('if (')
                 for j in range(self.arity):
                     if j > 0:
                         cog.out(' && ')
                     emit_typecheck_expression(m.getParameterTypes()[j],
                                               't%d' % j)
                 cog.out(') {\n\t\t\t\t\t')
             self.emit_method(m)
             if self.arity > 0:
                 cog.out('\t\t\t\t}')
         if is_builtin(self.name):
             cog.outl(' else { return %s_builtin.__call__(args, kws); }' %
                      self.name)
         elif self.arity > 0:
             cog.outl(' else { throw new UnexpectedInvocationError'
                      '("%s", args, kws); }' % self.name)
     cog.outl('\t\t\t}')
Esempio n. 52
0
def deallocDerivMemory():

    for deriv in FUNC_D_I:
        cog.outl("\t free(%s);" % (deriv))

    for deriv in FUNC_D_IJ:
        cog.outl("\t free(%s);" % (deriv))

    for deriv in FUNC_AD_I:
        cog.outl("\t free(%s);" % (deriv))
Esempio n. 53
0
def write_kernel2(kernelVarName, kernel_filename, kernelName, options):
    # cog.outl( 'string kernelFilename = "'  + kernel_filename + '";' )
    cog.outl("// generated using cog, from " + kernel_filename + ":")
    cog.outl("const char * " + kernelVarName + "Source =  ")
    write_file2(kernel_filename)
    cog.outl('"";')
    cog.outl(
        kernelVarName
        + " = cl->buildKernelFromString( "
        + kernelVarName
        + 'Source, "'
        + kernelName
        + '", '
        + options
        + ', "'
        + kernel_filename
        + '" );'
    )
Esempio n. 54
0
def allocDerivMemory():

    for deriv in FUNC_D_I:
        cog.outl("\t double* " + deriv +
                 " = (double*)malloc(sizeof(double)*n);")

    for deriv in FUNC_D_IJ:
        cog.outl("\t double* " + deriv +
                 " = (double*)malloc(sizeof(double)*n);")

    for deriv in FUNC_AD_I:
        cog.outl("\t double* " + deriv +
                 " = (double*)malloc(sizeof(double)*n);")
Esempio n. 55
0
 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(');')
Esempio n. 56
0
def add(classname=''):
    #    debug = open('debug.txt', 'a' )
    #    debug.write( 'foo\n')
    #    debug.write( 'infile [' + cog.inFile + ']\n' )

    infile = cog.inFile
    splitinfile = infile.replace('\\', '/').split('/')
    infilename = splitinfile[len(splitinfile) - 1]
    if classname == '':
        classname = infilename.replace('.h', '')
    cppfile = infile.replace('.h', '.cpp')
    # cog.outl( '// classname: ' + classname )
    # cog.outl( '// cppfile: ' + infilename.replace('.h','.cpp' ) )
    f = open(cppfile, 'r')
    in_multiline_comment = False
    in_header = False
    line = f.readline()
    cog.outl('// generated, using cog:')
    while (line != ''):
        # cog.outl(line)
        if (line.strip().find("/*") >= 0):
            in_multiline_comment = True
        if (line.strip().find("*/") >= 0):
            in_multiline_comment = False
        if not in_multiline_comment:
            if (in_header or (line.find(' ' + classname + '::') >= 0
                              or line.find('\r' + classname + '::') >= 0
                              or line.find('\n' + classname + '::') >= 0
                              or line.find(classname + '::') == 0
                              or line.find('*' + classname + '::') >= 0
                              or line.find('&' + classname + '::') >= 0)
                    and line.find("(") >= 0
                    and line.strip().find("//") != 0) and line.find(";") < 0:
                in_header = True
                fnheader = line.replace(classname + '::', '')
                fnheader = fnheader.replace('{', '')
                fnheader = fnheader.replace(') :', ')')
                if fnheader.find(")") >= 0:
                    in_header = False
                fnheader = fnheader.strip().replace(')', ');')
                fnheader = fnheader.strip().replace(';const', 'const;')
                fnheader = fnheader.strip().replace('; const', ' const;')
                cog.outl(fnheader)
        line = f.readline()
    f.close()
    cog.outl('')
Esempio n. 57
0
def definitions():
    members = get_vars('../hist.def')
    for i,fn in enumerate(members):
        #cog.outl("int i{}; //! ignored by root".format(fn))
        cog.outl("double {0}(const int& i) {{ return (data.count({1}) > 0) ? data[{1}][i] : BAD_NUM; }}".format(fn,i))
        #cog.outl("double {0}() {{ return (data.count({1}) > 0) ? data[{1}][0] : BAD_NUM; }}".format(fn,i))
        cog.outl("vector<double>* {0}() {{ return (data.count({1}) > 0) ? &data[{1}] : nullptr; }}".format(fn,i))
    # assume that Make is run from the analyzer directory and hist.def is one level up
    fullpath = readcmd('readlink -f ../hist.def')[:-1]
    astr = """
static void HistDefCheckSum(int pid=0) {{\n\n  string record = "{0}";""".format(check_dst_vars(fullpath).replace("\"","\\\"")) + """
  string line, dstvars = "DST_VAR";\n"""+"""
  ifstream histdef ("{0}");""".format(fullpath) + """
  if (histdef.is_open())
  {
    while ( getline (histdef,line) )
    {
      if (line.find(dstvars) != string::npos) {
        break;
      }
    }
    histdef.close();
  }
  line.erase(line.begin(), std::find_if(line.begin(), line.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
  line.erase(std::find_if(line.rbegin(), line.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), line.end());
  fprintf(stderr,"%s\\n",line.c_str());
  if (line == record) {
    return;
  } else {
    fprintf(stderr,"%s vs %s\\n",record.c_str(),line.c_str());
    const char* msg =
      "\\n###################### RUNTIME ERROR ######################\\n"
      "DST_VAR line in hist.def has changed since compilation.\\n"
      "Please recompile the analyzer before attempting to run.\\n"
      "###########################################################\\n";
    fprintf(stderr,"%s",msg);
    kill(pid,SIGINT);
    throw runtime_error(msg);
  }
}"""
    cog.outl(astr)
Esempio n. 58
0
except:
	print '$ROBOCOMP environment variable not set, using the default value /opt/robocomp'
	ROBOCOMP = '/opt/robocomp'
if len(ROBOCOMP)<1:
	print 'ROBOCOMP environment variable not set! Exiting.'
	sys.exit()


preStr = "-I"+ROBOCOMP+"/interfaces/ -I/opt/robocomp/interfaces/ --all "+ROBOCOMP+"/interfaces/"
Ice.loadSlice(preStr+"CommonBehavior.ice")
import RoboCompCommonBehavior
[[[cog
for imp in component['imports']:
	module = IDSLParsing.gimmeIDSL(imp.split('/')[-1])
	incl = imp.split('/')[-1].split('.')[0]
	cog.outl('Ice.loadSlice(preStr+"'+incl+'.ice")')
	cog.outl('import '+module['name']+'')
]]]
[[[end]]]


class CommonBehaviorI(RoboCompCommonBehavior.CommonBehavior):
	def __init__(self, _handler, _communicator):
		self.handler = _handler
		self.communicator = _communicator
	def getFreq(self, current = None):
		self.handler.getFreq()
	def setFreq(self, freq, current = None):
		self.handler.setFreq()
	def timeAwake(self, current = None):
		try:
Esempio n. 59
0
 def outl(self, s, **kwargs):
     cog.outl(s.format(**dict(vars(self), **kwargs)))