Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

## page was renamed from enhancements/AutoGenParser/CythonVisitorTest ## page was renamed from enhancements/AutoGenParser Autogenerated parser/CythonVisitorTest

#!python
import unittest
from cython.pyparser.pythonutil import get_grammar
from cython.pyparser.cyparser import CythonAstBuilder, build_parser as cython_parser
from cython.Compiler.ast import ASTVisitor

from cython.Compiler.Nodes import StatListNode, DefNode, PassStatNode, CFuncDeclaratorNode, CNameDeclaratorNode, CFuncDefNode, CSimpleBaseTypeNode, CDeclaratorNode
from cython.Compiler.ModuleNode import ModuleNode

from cython.Compiler.Symtab import BuiltinScope, ModuleScope
from cython.Compiler.Main import Context, CompilationResult, CompilationOptions

from cython.test.tools import CythonTestCase

class TestMark:
    pass
class CythonVisitor(ASTVisitor):

    def visitCFunction (self, node):
        pos = (__file__, 0, node.lineno)
        basenode = CSimpleBaseTypeNode(pos,
                                             name = 'int',
                                             module_path = [],
                                             is_basic_c_type = True,
                                             signed = 1,
                                             longness = 0,
                                             is_self_arg = False)

        base = CNameDeclaratorNode(pos, name = node.name, cname = node.name)

        declarator = CFuncDeclaratorNode (pos,
                                    base = base,
                                    args = [],
                                    has_varargs = False,
                                    exception_value = None,
                                    exception_check = 0,
                                    nogil = True,
                                    with_gil = False)



        suite = node.code.accept(self)
        return CFuncDefNode(pos,
            visibility = 'private',
            base_type = basenode,
            declarator = declarator,
            body = suite,
            doc = node.doc,
            modifiers = [],
            api = False,
            overridable = False)

    def visitPass (self,node):
        return PassStatNode((__file__, 0, node.lineno))

    def visitStmt (self, node):
        return StatListNode ((__file__, 0, node.lineno), stats = [n.accept(self) for n in node ] )

    def visitFunction(self,node):
        return DefNode((__file__, 0, node.lineno),
                       name = node.name,
                       args = [],
                       star_arg = [],
                       starstar_arg = [],
                       doc = node.doc,
                       body = node.code.accept(self))

    def visitModule(self, node):
        body = node.node.accept(self)
        return ModuleNode((__file__, 0, node.lineno), doc = node.doc, body = body, full_module_name = "CythonMODHACK")

CYTHON_GRAMMAR_EXTENSION = """
compound_stmt: cfuncdef | if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef

cfuncdef: 'cdef' NAME parameters ':' suite

"""
def build_parser (version):
    grammar = get_grammar (version)

    return cython_parser( CYTHON_GRAMMAR_EXTENSION + grammar )

class PyParsingTestCase (CythonTestCase):

    def test_simple_python_function(self):
        funame = 'test_simple_pass'
        source = """
def %s():
     pass
"""
        P23 = build_parser ('2.3')
        P24 = build_parser ('2.4')
        P25 = build_parser ('2.5a')
        # P3K = build_parser ('3.0') Incoming !
        self.assertProduces(P24, source % funame, None, funame)

    def test_simple_Cython_function(self):
        funame = 'ctest_simple_pass'
        source = """
cdef %s():
     pass
"""
        P24 = build_parser ('2.4')
        self.assertProduces(P24, source % funame, None, funame)

    def assertProduces (self, parser, source, result, funame, *args):
        # Parse
        modname = 'mod_%s'%funame
        b = parser.parse_source ( source, 'single', CythonAstBuilder(parser))
        ast = b.rule_stack[-1]

        # Analyse to generate a Scope
        v = CythonVisitor()
        tree = ast.accept (v)
        ctx = Context([])
        scope = ModuleScope(modname, None, context = ctx)
        tree.analyse_declarations (scope)

        #Generate C Module
        result = CompilationResult()
        result.c_file = modname+'.c'
        result.h_file = modname+'.h'
        result.i_file = ''

        options = CompilationOptions()
        tree.process_implementation(scope, options, result)

        # Validate
        self.validateCCode ( result.c_file)

        # Compile
        new_parser_test = self.compileModuleAndImport ( result.c_file)

        # Test
        try:
            self.assertEquals (getattr(new_parser_test,funame)(*args), None)
        except Exception, tg:
            self.fail(tg)
Something went wrong with that request. Please try again.