Example #1
0
    def parse(tokens):
        if tokens.peek() is not token.BEGIN_BLOCK:
            return None

        attributes = []
        decls = []

        tokens.expect(token.BEGIN_BLOCK)
        while tokens.peek() is not token.END_BLOCK:
            decl = None

            attr = Attribute.parse(tokens)
            if attr is not None:
                attributes.append(attr)
            else:
                decl = (
                    FunctionDecl.parse(tokens) or
                    VarDecl.parse(tokens) or
                    PassStatement.parse(tokens)
                )

                if decl is None:
                    raise error.SyntaxError(tokens.peek().position, 'Expected end block, variable or class declaration, or pass statement.  Got %r' % tokens.peek())

                if not isinstance(decl, PassStatement):
                    decls.append(decl)

            while tokens.peek() is token.END_OF_STATEMENT:
                tokens.getNext()

        tokens.expect(token.END_BLOCK)

        return ClassBody(decls, attributes)
    def testGoodParse(self):
        program = util.source('''
            def foo():
                pass
        ''')

        result = FunctionDecl.parse(lex(program))
        assert isinstance(result, FunctionDecl), result
    def testBadParse(self):
        program = util.source('''
            def foo():
        ''')

        self.failUnlessRaises(
            error.SyntaxError,
            lambda: FunctionDecl.parse(lex(program))
        )
    def testParseArgs(self):
        tokens = lex(util.source('''
            def foo(x as string, y as int, z as boolean):
                print x
                print y
                print z
        '''))

        result = FunctionDecl.parse(tokens)
        assert isinstance(result, FunctionDecl), tokens.peek()
    def testGoodSemantic(self):
        program = util.source('''
            def foo():
                var x = 2
                var y = 9
                print x + y
        ''')

        tokens = lex(program)
        decl = FunctionDecl.parse(tokens)

        assert isinstance(decl, FunctionDecl), tokens

        scope = Scope(parent=None)
        result = decl.semantic(scope)

        assert result is not None