예제 #1
0
def test_tag_macro_error():
    """Check if we get correct error with wrong dispatch character"""
    try:
        macroexpand(tokenize("(dispatch_tag_macro '- '())")[0],
                    HyASTCompiler(__name__))
    except HyTypeError as e:
        assert "with the character `-`" in str(e)
예제 #2
0
def test_tag_macro_error():
    """Check if we get correct error with wrong dispatch character"""
    try:
        macroexpand(
            tokenize("(dispatch_tag_macro '- '())")[0], __name__,
            HyASTCompiler(__name__))
    except HyTypeError as e:
        assert "with the character `-`" in str(e)
예제 #3
0
def test_preprocessor_exceptions():
    """ Test that macro expansion raises appropriate exceptions"""
    try:
        macroexpand(tokenize('(defn)')[0], __name__)
        assert False
    except HyMacroExpansionError as e:
        assert "_hy_anon_fn_" not in str(e)
        assert "TypeError" not in str(e)
예제 #4
0
def test_preprocessor_exceptions():
    """ Test that macro expansion raises appropriate exceptions"""
    try:
        macroexpand(tokenize('(defn)')[0], __name__)
        assert False
    except HyMacroExpansionError as e:
        assert "_hy_anon_fn_" not in str(e)
        assert "TypeError" not in str(e)
예제 #5
0
def test_preprocessor_expression():
    """ Test that macro expansion doesn't recurse"""
    obj = macroexpand(tokenize('(test (test "one" "two"))')[0], HyASTCompiler(__name__))

    assert type(obj) == HyList
    assert type(obj[0]) == HyExpression

    assert obj[0] == HyExpression([HySymbol("test"), HyString("one"), HyString("two")])

    obj = HyList([HyString("one"), HyString("two")])
    obj = tokenize('(shill ["one" "two"])')[0][1]
    assert obj == macroexpand(obj, HyASTCompiler(""))
예제 #6
0
def test_preprocessor_expression():
    """ Test that macro expansion doesn't recurse"""
    obj = macroexpand(tokenize('(test (test "one" "two"))')[0], __name__)

    assert type(obj) == HyList
    assert type(obj[0]) == HyExpression

    assert obj[0] == HyExpression([HySymbol("test"),
                                   HyString("one"),
                                   HyString("two")])

    obj = HyList([HyString("one"), HyString("two")])
    obj = tokenize('(shill ["one" "two"])')[0][1]
    assert obj == macroexpand(obj, '')
예제 #7
0
def test_macroexpand_nan():
    # https://github.com/hylang/hy/issues/1574
    import math
    NaN = float('nan')
    x = macroexpand(HyFloat(NaN), __name__, HyASTCompiler(__name__))
    assert type(x) is HyFloat
    assert math.isnan(x)
예제 #8
0
def test_macroexpand_nan():
   # https://github.com/hylang/hy/issues/1574
   import math
   NaN = float('nan')
   x = macroexpand(HyFloat(NaN), __name__, HyASTCompiler(__name__))
   assert type(x) is HyFloat
   assert math.isnan(x)
예제 #9
0
def test_preprocessor_simple():
    """ Test basic macro expansion """
    obj = macroexpand(tokenize('(test "one" "two")')[0],
                      __name__,
                      HyASTCompiler(__name__))
    assert obj == HyList(["one", "two"])
    assert type(obj) == HyList
예제 #10
0
def test_preprocessor_simple():
    """ Test basic macro expansion """
    obj = macroexpand(tokenize('(test "one" "two")')[0],
                      __name__,
                      HyASTCompiler(__name__))
    assert obj == List(["one", "two"])
    assert type(obj) == List
예제 #11
0
def test_macroexpand_source_data():
    # https://github.com/hylang/hy/issues/1944
    ast = Expression([Symbol('#@'), String('a')])
    ast.start_line = 3
    ast.start_column = 5
    bad = macroexpand(ast, "hy.core.macros")
    assert bad.start_line == 3
    assert bad.start_column == 5
예제 #12
0
def test_preprocessor_exceptions():
    """Test that macro expansion raises appropriate exceptions"""
    with pytest.raises(HyMacroExpansionError) as excinfo:
        macroexpand(tokenize("(when)")[0], __name__, HyASTCompiler(__name__))
    assert "_hy_anon_" not in excinfo.value.msg
예제 #13
0
    def compile_expression(self, expr, *, allow_annotation_expression=False):
        # Perform macro expansions
        expr = macroexpand(expr, self.module, self)
        if isinstance(expr, (Result, ast.AST)):
            # Use this as-is.
            return expr
        elif not isinstance(expr, Expression):
            # Go through compile again if we have a different type of model.
            return self.compile(expr)

        if not expr:
            raise self._syntax_error(
                expr, "empty expressions are not allowed at top level"
            )

        args = list(expr)
        root = args.pop(0)
        func = None

        if isinstance(root, Symbol) and root.startswith("."):
            # (.split "test test") -> "test test".split()
            # (.a.b.c x v1 v2) -> (.c (. x a b) v1 v2) ->  x.a.b.c(v1, v2)

            # Get the method name (the last named attribute
            # in the chain of attributes)
            attrs = [
                Symbol(a).replace(root) if a else None for a in root.split(".")[1:]
            ]
            if not all(attrs):
                raise self._syntax_error(expr, "cannot access empty attribute")
            root = attrs.pop()

            # Get the object we're calling the method on
            # (extracted with the attribute access DSL)
            # Skip past keywords and their arguments.
            try:
                kws, obj, rest = (
                    many(KEYWORD + FORM | unpack("mapping")) + FORM + many(FORM)
                ).parse(args)
            except NoParseError:
                raise self._syntax_error(expr, "attribute access requires object")
            # Reconstruct `args` to exclude `obj`.
            args = [x for p in kws for x in p] + list(rest)
            if is_unpack("iterable", obj):
                raise self._syntax_error(
                    obj, "can't call a method on an unpacking form"
                )
            func = self.compile(Expression([Symbol(".").replace(root), obj] + attrs))

            # And get the method
            func += asty.Attribute(
                root, value=func.force_expr, attr=mangle(root), ctx=ast.Load()
            )

        if is_annotate_expression(root):
            # Flatten and compile the annotation expression.
            ann_expr = Expression(root + args).replace(root)
            return self.compile_expression(ann_expr, allow_annotation_expression=True)

        if not func:
            func = self.compile(root)

        args, ret, keywords = self._compile_collect(args, with_kwargs=True)

        return (
            func + ret + asty.Call(expr, func=func.expr, args=args, keywords=keywords)
        )
예제 #14
0
def test_preprocessor_exceptions():
    """ Test that macro expansion raises appropriate exceptions"""
    with pytest.raises(HyMacroExpansionError) as excinfo:
        macroexpand(tokenize('(defn)')[0], __name__, HyASTCompiler(__name__))
    assert "_hy_anon_" not in excinfo.value.msg