Example #1
0
def load(file):
    conf = {}
    with open(file, "r") as input:
        conf = yaml.load(input)
        pass
    systemenv = dict(os.environ)
    env = {}
    env.update(systemenv)
    env.update(conf)
    env["system"] = systemenv
    conf["system"] = systemenv
    expression.evaluate(env, conf)
    return conf
Example #2
0
def evalExpression(value, obj):
    # check if the expression is correct
    try:
        evaluate(value, obj.getMockGlobals(), obj.getMockLocals())
    except BaseException as e:
        raise ValueError(str(e))
    # evaluate without labels
    try:
        return evaluate(value), None
    except NameError as e:
        return 0, value
    except BaseException as e:
        raise ValueError("Error evaluating {}: {}".format(value, e))
Example #3
0
 def makeMinterms(self, expr):  #getting expression in RPN
     Minterms = []
     vars = expression.getVariables(expr)
     for x in range(0, 2**len(vars)):
         perm = bin(x)
         perm = perm[2:]
         perm = perm.rjust(len(vars), '0')
         if expression.evaluate(expression.insertValues(expr, vars,
                                                        perm)) == "1":
             Minterms.append(Minterm(perm, [x], len(Minterms)))
     return Minterms
Example #4
0
def link(objects, layout, fit, sectionsFilter, api):
    ip = 0
    exportedSymbolValues = dict()
    segments = {}
    # place sections into segments
    for segment in layout.layout:
        if segment["begin"] is not None:
            if ip > segment["begin"]:
                raise LinkerError(
                    "segment overflow: IP is beyond segment `{}' begin".format(
                        segment["name"]))
            ip = segment["begin"]
        if segment["min-begin"] is not None:
            ip = max(ip, segment["min-begin"])
        segBegin = ip
        sectionList = []
        for o in objects:
            for s in sectionsFilter.filter(o.sections):
                if s.segment == segment["name"]:
                    sectionList.append(s)
        ip = fit(ip, sectionList)
        if segment["end"] is not None:
            end = segment["end"]
            if end < ip:
                raise LinkerError(
                    "Segment overflow: IP is beyond segment `{}' end".format(
                        segment["name"]), o, s)
            ip = segment["end"]
        segments[segment["name"]] = segBegin, ip
    # update origin segments sizes
    ip = 0
    for segment in layout.layout:
        segName = segment["name"]
        target = segment["target"]
        begin, end = segments[segName]
        if target is not None:
            if begin != end:
                raise LinkerError("Non-empty origin segment `{}'".format(
                    segment["name"]))
            begin = ip
        if begin < ip:
            raise LinkerError("Segment `{}' is overlapped".format(segName))
        if target is not None:
            targetBegin, targetEnd = segments[target]
            targetSize = targetEnd - targetBegin
            end = begin + targetSize
            segments[segName] = begin, end
        ip = end
    # report segment sizes
    for name in segments:
        begin, end = segments[name]
        if begin != end:
            print("Segment {}: {} bytes (0x{:04X}-0x{:04X})".format(
                name, end - begin, begin, end))
        exportedSymbolValues["__seg_{}_begin".format(name)] = begin
        exportedSymbolValues["__seg_{}_end".format(name)] = end
    # assign global symbol values
    for o in objects:
        for label in o.exportSymbols:
            found = False
            for s in o.sections:
                if label in s.labels:
                    if label in api:
                        if sectionsFilter.isReachable(s):
                            raise LinkerError(
                                f"conflicting definitions of global symbol `{label}' in api and in object",
                                o, s)
                        exportedSymbolValues[label] = api[label]
                    elif label in exportedSymbolValues:
                        raise LinkerError(
                            "global symbol `{}' redifinition".format(label), o,
                            s)
                    elif sectionsFilter.isReachable(s):
                        exportedSymbolValues[
                            label] = s.offset + s.labels[label]
                    found = True
            if label in o.consts:
                if label in api:
                    exportedSymbolValues[label] = api[label]
                elif label in exportedSymbolValues:
                    raise LinkerError(
                        "global symbol `{}' redifinition".format(label), o)
                else:
                    exportedSymbolValues[label] = o.consts[label]
                found = True
            if not found:
                raise LinkerError(
                    "symbol `{}' is exported, but not defined".format(label),
                    o)
    # assign local symbol values and evaluate references
    symbolMap = SymbolMap(exportedSymbolValues)
    apiOut = dict()
    for o in objects:
        localSymbolValues = {}
        for s in sectionsFilter.filter(o.sections):
            for label in s.labels:
                value = s.offset + s.labels[label]
                localSymbolValues[label] = value
                if label not in o.exportSymbols:
                    symbolMap.addLabel(o.name, label, value)
                else:
                    apiOut[label] = value
            symbolMap.addLineInfo(s.offset, s.lineInfo)
        localSymbolValues.update(o.consts)
        for label in o.consts:
            if label in o.exportSymbols:
                apiOut[label] = o.consts[label]
        exportedSymbolValues.update(api)
        for s in sectionsFilter.filter(o.sections):
            for offs, expr in s.refs:
                try:
                    value = evaluate(expr, exportedSymbolValues,
                                     localSymbolValues)
                    s.text[offs] = value & 255
                except BaseException as e:
                    raise LinkerError("error evaluating {}: {}".format(
                        expr, e))
    return symbolMap, apiOut, segments
Example #5
0
def launch(expression, code, use_calculations, use_workfunctions, sleep,
           timeout, modulo, dry_run, daemon):
    """
    Evaluate the expression in Reverse Polish Notation in both a normal way and by procedurally generating
    a workchain that encodes the sequence of operators and gets the stack of operands as an input. Multiplications
    are modelled by a 'while_' construct and addition will be done performed by an addition or a subtraction,
    depending on the sign, branched by the 'if_' construct. Powers will be simulated by nested workchains.

    The script will generate a file containing the workchains with the procedurally generated outlines. Unless the
    dry run option is specified, the workchain will also be run and its output compared with the normal evaluation
    of the expression. If the two values match the script will be exited with a zero exit status, otherwise a non-zero
    exit status will be returned, indicating failure.

    In addition to normal rules of Reverse Polish Notation, the following restrictions to the expression apply:

     \b
     * Only integers are supported
     * Only the addition, multiplication and power operators (+, * and ^, respectively) are supported
     * Every intermediate result should be an integer, so no raising a number to a negative power
     * Operands for power operator are limited to the range [1, 3]
     * Expression has only a single sequence of numbers followed by single continuous sequence of operators

    If no expression is specified, a random one will be generated that adheres to these rules
    """
    import importlib
    import sys
    import time
    import uuid
    from aiida.orm import Code
    from aiida.orm.data.int import Int
    from aiida.orm.data.str import Str
    from aiida.work.launch import run_get_node, submit
    from expression import generate, validate, evaluate
    from workchain import generate_outlines, format_outlines, write_workchain

    if use_calculations and not isinstance(code, Code):
        raise click.BadParameter(
            'if you specify the -C flag, you have to specify a code as well')

    if expression is None:
        expression = generate()

    valid, error = validate(expression)

    if not valid:
        click.echo("the expression '{}' is invalid: {}".format(
            expression, error))
        sys.exit(1)

    filename = 'polish_{}.py'.format(str(uuid.uuid4().hex))
    evaluated = evaluate(expression, modulo)
    outlines, stack = generate_outlines(expression)
    outlines_string = format_outlines(outlines, use_calculations,
                                      use_workfunctions)
    workchain_filename = write_workchain(outlines_string, filename=filename)

    click.echo('Expression: {}'.format(expression))

    if not dry_run:
        try:
            workchain_module = 'polish_workchains.{}'.format(
                filename.replace('.py', ''))
            workchains = importlib.import_module(workchain_module)
        except ImportError:
            click.echo(
                'could not import the {} module'.format(workchain_module))
            sys.exit(1)

        inputs = {'modulo': Int(modulo), 'operands': Str(' '.join(stack))}

        if code:
            inputs['code'] = code

        if daemon:
            workchain = submit(workchains.Polish00WorkChain, **inputs)
            start_time = time.time()
            timed_out = True

            while time.time() - start_time < timeout:
                time.sleep(sleep)

                if workchain.is_terminated:
                    timed_out = False
                    break

            if timed_out:
                click.secho('Failed: ', fg='red', bold=True, nl=False)
                click.secho(
                    'the workchain<{}> did not finish in time and the operation timed out'
                    .format(workchain.pk),
                    bold=True)
                sys.exit(1)

            try:
                result = workchain.out.result
            except AttributeError:
                click.secho('Failed: ', fg='red', bold=True, nl=False)
                click.secho(
                    'the workchain<{}> did not return a result output node'.
                    format(workchain.pk),
                    bold=True)
                sys.exit(1)

        else:
            results, workchain = run_get_node(workchains.Polish00WorkChain,
                                              **inputs)
            result = results['result']

    click.echo('Evaluated : {}'.format(evaluated))

    if not dry_run:
        click.echo('Workchain : {} <{}>'.format(result, workchain.pk))

        if result != evaluated:
            click.secho('Failed: ', fg='red', bold=True, nl=False)
            click.secho(
                'the workchain result did not match the evaluated value',
                bold=True)
            sys.exit(1)
        else:
            click.secho('Success: ', fg='green', bold=True, nl=False)
            click.secho(
                'the workchain accurately reproduced the evaluated value',
                bold=True)
            sys.exit(0)