Example #1
0
def do_rule(rule, sexps, nsi):
    """
    Applies a Pure rule to tuple of elements. The codomain tuple
    is always mapped to the same size of the domain tuple.

    For example a rule to commute addition maps 1-tuples to
    1-tuples.

    `(Addition x y) →  (Addition y x)`

    A rule to add an element to both sides of an equation maps
    2-tuples to 2-tuples but one element of the image is null.

    `( (Equation lhs rhs) , x ) →  ( (Equation lhs+x rhs+x) , pass )`

    In this case the 'pass' element tells the worksheet to do
    not expect a new element in the image of the rule and leave
    that element inplace.
    """

    # Build the Pure expression from the given sexps
    args  = map(translate.parse_sexp, sexps)
    pargs = map(translate.python_to_pure, args)

    # Build the rule and apply it to the Pure expression
    ref        = rules[rule]()
    _pure_expr = ref.reduce_with(*pargs)

    # Convert to prefix form for conversion back to Python
    result = i2p(_pure_expr)

    # Create the uid generator and walk the new expression to
    # return the JSON
    uid       = uidgen(int(nsi))
    expr_tree = translate.parse_pure_exp(result)

    # Walk the tree with the UID generator
    expr_tree.uid_walk(uid, overwrite=True)

    _html = html(expr_tree)
    _json = json_flat(expr_tree)
    _nsi  =  uid.next()[3:]

    return json.dumps({
        'new_html'        : [_html],
        'new_json'        : [_json],
        'namespace_index' : _nsi
    })
Example #2
0
def do_eval(code, sexps, nsi):
    # Block the execution of any code which could alter the
    # interpreter, this is marginally improves security
    if any([s in code for s in blacklist]):
        # Raise a warning since this could be a hacking attempt
        # TODO: at some point tie this into django-axes and cut
        # the user off if they try too much of this stuff
        logging.warning('Attempt to use Pure keyword: ' + code)
        return json.dumps({'error': 'Invalid keyword'})

    try:
        pure_expr = PureInterface().eval(code)
        result = i2p(pure_expr)
    except Exception as e:
        error = str(e.value)
        return json.dumps({'error':error})


    # Create the uid generator and walk the new expression to
    # return the JSON
    uid       = uidgen(int(nsi))

    try:
        expr_tree = translate.parse_pure_exp(result)
    except exception.NoWrapper as e:
        unknown = e.value
        return json.dumps({'error': 'Unknown symbol: %s' % unknown})

    expr_tree.uid_walk(uid, overwrite=True)

    _html = html(expr_tree)
    _json = json_flat(expr_tree)
    _nsi  =  uid.next()[3:]

    return json.dumps({
        'new_html'        : [_html],
        'new_json'        : [_json],
        'namespace_index' : _nsi
    })