id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
146,048
LionelAuroux/cnorm
LionelAuroux_cnorm/cnorm/nodes.py
cnorm.nodes.PointerType
class PointerType(DeclType): """For pointer in declaration"""
class PointerType(DeclType): '''For pointer in declaration''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
3
2
0
1
1
0
1
1
1
0
0
2
0
0
146,049
LionelAuroux/cnorm
LionelAuroux_cnorm/cnorm/nodes.py
cnorm.nodes.ParenType
class ParenType(DeclType): """For parenthesis in declaration""" def __init__(self, params=None): DeclType.__init__(self) if params is None: params = [] self._params = params @property def params(self): return self._params
class ParenType(DeclType): '''For parenthesis in declaration''' def __init__(self, params=None): pass @property def params(self): pass
4
1
4
0
4
0
2
0.11
1
0
0
0
2
1
2
5
12
2
9
5
5
1
8
4
5
2
2
1
3
146,050
LionelAuroux/cnorm
LionelAuroux_cnorm/cnorm/nodes.py
cnorm.nodes.Paren
class Paren(Unary): """For () expression"""
class Paren(Unary): '''For () expression''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
1
2
0
1
1
0
1
1
1
0
0
4
0
0
146,051
LionelAuroux/cnorm
LionelAuroux_cnorm/cnorm/nodes.py
cnorm.nodes.LoopControl
class LoopControl(Label): """loop control statement"""
class LoopControl(Label): '''loop control statement''' pass
1
1
0
0
0
0
0
1
1
0
0
2
0
0
0
1
2
0
1
1
0
1
1
1
0
0
3
0
0
146,052
LionelAuroux/cnorm
LionelAuroux_cnorm/cnorm/nodes.py
cnorm.nodes.Literal
class Literal(Terminal): """Terminal Literal"""
class Literal(Terminal): '''Terminal Literal''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
1
2
0
1
1
0
1
1
1
0
0
3
0
0
146,053
LionelAuroux/cnorm
LionelAuroux_cnorm/cnorm/nodes.py
cnorm.nodes.Label
class Label(Stmt): """Label statement""" def __init__(self, value: str): Stmt.__init__(self) self.value = value
class Label(Stmt): '''Label statement''' def __init__(self, value: str): pass
2
1
3
0
3
0
1
0.25
1
1
0
2
1
1
1
1
6
1
4
3
2
1
4
3
2
1
2
0
1
146,054
LionelAuroux/cnorm
LionelAuroux_cnorm/cnorm/nodes.py
cnorm.nodes.Return
class Return(Branch): """Return statement""" def __init__(self, expr: Expr): Branch.__init__(self, "return", expr)
class Return(Branch): '''Return statement''' def __init__(self, expr: Expr): pass
2
1
2
0
2
0
1
0.33
1
1
1
0
1
0
1
3
5
1
3
2
1
1
3
2
1
1
4
0
1
146,055
LionelAuroux/cnorm
LionelAuroux_cnorm/cnorm/nodes.py
cnorm.nodes.RootBlockStmt
class RootBlockStmt(BlockStmt): """Root Block statement""" def __init__(self, body: [ExprStmt]): BlockStmt.__init__(self, body) from collections import ChainMap self.types = ChainMap()
class RootBlockStmt(BlockStmt): '''Root Block statement''' def __init__(self, body: [ExprStmt]): pass
2
1
4
0
4
0
1
0.2
1
2
1
0
1
1
1
11
7
1
5
4
2
1
5
4
2
1
3
0
1
146,056
LionelAuroux/cnorm
LionelAuroux_cnorm/cnorm/nodes.py
cnorm.nodes.If
class If(Conditional): """If statement""" def __init__(self, condition: Expr, thencond: Stmt, elsecond: Stmt=None): Conditional.__init__(self, condition) self.thencond = thencond self.elsecond = elsecond
class If(Conditional): '''If statement''' def __init__(self, condition: Expr, thencond: Stmt, elsecond: Stmt=None): pass
2
1
4
0
4
0
1
0.2
1
1
1
0
1
2
1
2
7
1
5
4
3
1
5
4
3
1
3
0
1
146,057
LionelAuroux/cnorm
LionelAuroux_cnorm/cnorm/nodes.py
cnorm.nodes.Sizeof
class Sizeof(Unary): """For sizeof expr/type expression"""
class Sizeof(Unary): '''For sizeof expr/type expression''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
1
2
0
1
1
0
1
1
1
0
0
4
0
0
146,058
LionelAuroux/cnorm
LionelAuroux_cnorm/cnorm/nodes.py
cnorm.nodes.ExprStmt
class ExprStmt(Stmt): """Expression statement""" def __init__(self, expr: Expr): parsing.Node.__init__(self) self.expr = expr
class ExprStmt(Stmt): '''Expression statement''' def __init__(self, expr: Expr): pass
2
1
3
0
3
0
1
0.25
1
1
1
0
1
1
1
1
6
1
4
3
2
1
4
3
2
1
2
0
1
146,059
LionelAuroux/cnorm
LionelAuroux_cnorm/cnorm/nodes.py
cnorm.nodes.Expr
class Expr(parsing.Node): """All expression"""
class Expr(parsing.Node): '''All expression''' pass
1
1
0
0
0
0
0
1
1
0
0
5
0
0
0
0
2
0
1
1
0
1
1
1
0
0
1
0
0
146,060
LionelAuroux/cnorm
LionelAuroux_cnorm/cnorm/nodes.py
cnorm.nodes.Post
class Post(Unary): """For post{inc,dec} expression"""
class Post(Unary): '''For post{inc,dec} expression''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
1
2
0
1
1
0
1
1
1
0
0
4
0
0
146,061
LionelAuroux/cnorm
LionelAuroux_cnorm/cnorm/nodes.py
cnorm.nodes.CType
class CType(parsing.Node): """Base for primary/func""" def __init__(self): parsing.Node.__init__(self) self._decltype = None # only one storage by declaration # i.e: auto, register, typedef, static, extern, ... self._storage = Storages.AUTO # only one specifier by declaration # i.e: auto, short, long, struct, union, enum, ... self._specifier = Specifiers.AUTO def copy(self): import copy theclone = copy.copy(self) theclone._decltype = None return theclone def link(self, t: DeclType=None): if t is not None: if not isinstance(t, DeclType): raise Exception("add only C type declarator") self._decltype = t return self._decltype def push(self, t: DeclType=None): if t is not None: if not isinstance(t, DeclType): raise Exception("add only C type declarator") old = self._decltype self._decltype = t self._decltype.link(old) return self._decltype
class CType(parsing.Node): '''Base for primary/func''' def __init__(self): pass def copy(self): pass def link(self, t: DeclType=None): pass def push(self, t: DeclType=None): pass
5
1
7
0
6
1
2
0.2
1
2
1
2
4
3
4
4
34
4
25
11
19
5
25
11
19
3
1
2
8
146,062
LionelAuroux/cnorm
LionelAuroux_cnorm/cnorm/nodes.py
cnorm.nodes.Id
class Id(Terminal): """Terminal Id"""
class Id(Terminal): '''Terminal Id''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
1
2
0
1
1
0
1
1
1
0
0
3
0
0
146,063
LionelAuroux/cnorm
LionelAuroux_cnorm/tests/cnorm_visit.py
tests.cnorm_visit.CnormVisit_Test
class CnormVisit_Test(unittest.TestCase): def test_01_basic(self): """Basic visit function test""" decl = Declaration() res = decl.parse(""" int a; int b = 3; enum A pouet; enum A {R,S,T}; union U pif; union U { int k; double b; }; struct J nia; int f1(); int g(int) {} struct J { int k; double b; }; double (*f2(char**)); typedef int size_t; size_t pim; int main(int ac, char **av) { return 42; } """) scollect = set() for d in res.declfuncs(): scollect |= {d._name} self.assertEqual(scollect, {'f1', 'f2'}, "Fail iter correctly") scollect = set() for d in res.implfuncs(): scollect |= {d._name} self.assertEqual(scollect, {'g', 'main'}, "Fail iter correctly") scollect = set() for d in res.defvars(): scollect |= {d._name} self.assertEqual(scollect, {'pouet', 'pif', 'a', 'b', 'nia', 'pim'}, "Fail iter correctly") scollect = set() for d in res.deftypes(): if d._name != '': scollect |= {d._name} else: scollect |= {d._ctype.identifier} self.assertEqual(scollect, {'size_t', 'U', 'A', 'J'}, "Fail iter correctly")
class CnormVisit_Test(unittest.TestCase): def test_01_basic(self): '''Basic visit function test''' pass
2
1
47
0
46
1
6
0.02
1
2
1
0
1
0
1
73
49
1
47
6
45
1
22
6
20
6
2
2
6
146,064
LionelAuroux/cnorm
LionelAuroux_cnorm/tests/internal_cnorm.py
tests.internal_cnorm.InternalCnorm_Test
class InternalCnorm_Test(unittest.TestCase): def test_01_basicdecl(self): """Test cnorm nodes construction""" d = nodes.Decl('a') self.assertEqual( str(d.to_c()), "int a;\n", "Failed to convert to C") vars(d)["_name"] = 'b' qual = d.ctype qual = qual.link(nodes.PointerType()) qual = qual.link(nodes.QualType(nodes.Qualifiers.VOLATILE)) self.assertEqual( str(d.to_c()), "volatile int *b;\n", "Failed to convert to C") vars(d)["_name"] = 'c' qual = d.ctype qual = qual.link(nodes.QualType(nodes.Qualifiers.CONST)) qual = qual.link(nodes.PointerType()) qual = qual.link(nodes.QualType(nodes.Qualifiers.VOLATILE)) self.assertEqual(str(d.to_c()), "volatile int *const c;\n", "Failed to convert to C") vars(d)["_name"] = 'd' qual = d.ctype qual = qual.link(nodes.PointerType()) qual = qual.link(nodes.ParenType()) qual = qual.link(nodes.QualType(nodes.Qualifiers.CONST)) qual = qual.link(nodes.PointerType()) qual = qual.link(nodes.QualType(nodes.Qualifiers.VOLATILE)) self.assertEqual(str(d.to_c()), "volatile int *const (*d);\n", "Failed to convert to C") vars(d)["_name"] = 'e' qual = d.ctype qual = qual.link(nodes.ArrayType()) qual = qual.link(nodes.ArrayType()) qual = qual.link(nodes.PointerType()) qual = qual.link(nodes.ParenType()) qual = qual.link(nodes.QualType(nodes.Qualifiers.CONST)) qual = qual.link(nodes.PointerType()) qual = qual.link(nodes.QualType(nodes.Qualifiers.VOLATILE)) self.assertEqual(str(d.to_c()), "volatile int *const (*e[][]);\n", "Failed to convert to C") d = nodes.Decl('tf', nodes.PrimaryType('double')) qual = d.ctype qual = qual.link(nodes.ArrayType()) qual = qual.link(nodes.QualType(nodes.Qualifiers.CONST)) self.assertEqual(str(d.to_c()), "const double tf[];\n", "Failed to convert to C") ft = nodes.FuncType( 'double', [nodes.Decl('a', nodes.PrimaryType('size_t')), nodes.Decl('b', nodes.PrimaryType('int'))] ) f = nodes.Decl('f', ft) self.assertEqual(str(f.to_c()), "double f(size_t a, int b);\n", "Failed to convert to C") f = nodes.Decl('f', nodes.PrimaryType('double')) qual = f.ctype qual = qual.link(nodes.PointerType()) qual = qual.link( nodes.ParenType([ nodes.Decl( 'a', nodes.PrimaryType('size_t') ), nodes.Decl('b', nodes.PrimaryType('int')) ]) ) self.assertEqual(str(f.to_c()), "double (*f)(size_t a, int b);\n", "Failed to convert to C") ft2 = nodes.FuncType( 'double', [nodes.Decl('p', nodes.PrimaryType('ext_func'))] ) f2 = nodes.Decl('f2', ft2) qual = f2.ctype qual = qual.link(nodes.PointerType()) qual = qual.link( nodes.ParenType([ nodes.Decl('a', nodes.PrimaryType('size_t')), nodes.Decl('b', nodes.PrimaryType('int')) ]) ) self.assertEqual( str(f2.to_c()), "double (*f2(ext_func p))(size_t a, int b);\n", "Failed to convert to C") ## test CTYPE construction ctype = nodes.makeCType('int') d = nodes.Decl('ghh', ctype) self.assertEqual(str(d.to_c()), "int ghh;\n", "Failed to convert to C") ctype = nodes.makeCType('const') ctype = nodes.makeCType('double', ctype) d = nodes.Decl('ghh', ctype) self.assertEqual(str(d.to_c()), "const double ghh;\n", "Failed to convert to C") ctype = nodes.makeCType('__int8', ctype) ctype = nodes.makeCType('__unsigned__', ctype) ctype = nodes.makeCType('extern', ctype) d = nodes.Decl('ghh', ctype) self.assertEqual(str(d.to_c()), "extern const unsigned __int8 ghh;\n", "Failed to convert to C") d = nodes.Decl('GG', nodes.PrimaryType('XXX')) qual = d.ctype qual = qual.link(nodes.QualType(nodes.Qualifiers.CONST)) qual = qual.link(nodes.PointerType()) qual = qual.link(nodes.ParenType()) qual = qual.link(nodes.ArrayType(nodes.Literal("12"))) qual = qual.link(nodes.ParenType()) qual = qual.link(nodes.ArrayType(nodes.Literal("66"))) self.assertEqual(str(d.to_c()), "XXX ((*const GG)[12])[66];\n", "Failed to convert to C") ft = nodes.FuncType( 'HHHHH', [ nodes.Decl('a', nodes.PrimaryType('size_t')), nodes.Decl('b', nodes.PrimaryType('int')) ] ) d = nodes.Decl('func', ft) self.assertEqual(str(d.to_c()), "HHHHH func(size_t a, int b);\n", "Failed to convert to C") def test_02_basicexpr(self): """Test cnorm expression nodes""" e = nodes.Id('cool') self.assertEqual(str(e.to_c()), "cool", "Failed to convert to C") e = nodes.Literal('42') self.assertEqual(str(e.to_c()), "42", "Failed to convert to C") e = nodes.Binary(nodes.Raw('+'), [nodes.Id('a'), nodes.Literal('12')]) p = e self.assertEqual(str(e.to_c()), "a + 12", "Failed to convert to C") e = nodes.Func(nodes.Id('f'), [nodes.Id('a'), nodes.Literal('12')]) self.assertEqual(str(e.to_c()), "f(a, 12)", "Failed to convert to C") e = nodes.Ternary( '', [ nodes.Id('a'), nodes.Literal('1'), nodes.Literal('2') ] ) self.assertEqual(str(e.to_c()), "a ? 1 : 2", "Failed to convert to C") e = nodes.Unary(nodes.Raw('++'), [nodes.Id('a')]) self.assertEqual(str(e.to_c()), "++a", "Failed to convert to C") e = nodes.Paren('', [p]) self.assertEqual(str(e.to_c()), "(a + 12)", "Failed to convert to C") e = nodes.Post(nodes.Raw('++'), [nodes.Id('a')]) self.assertEqual(str(e.to_c()), "a++", "Failed to convert to C") e = nodes.Array(nodes.Id('tab'), [p]) self.assertEqual(str(e.to_c()), "tab[a + 12]", "Failed to convert to C") e = nodes.Dot(nodes.Id('s'), [nodes.Id('a')]) self.assertEqual(str(e.to_c()), "s.a", "Failed to convert to C") e = nodes.Arrow(nodes.Id('s'), [nodes.Id('a')]) self.assertEqual(str(e.to_c()), "s->a", "Failed to convert to C") def test_03_basicstmt(self): """Test cnorm statement nodes""" c = nodes.Binary(nodes.Raw('<'), [nodes.Id('a'), nodes.Literal('12')]) thencond = nodes.ExprStmt( nodes.Binary( nodes.Raw('='), [nodes.Id('b'), nodes.Literal('1')] )) elsecond = nodes.ExprStmt( nodes.Binary( nodes.Raw('='), [nodes.Id('c'), nodes.Literal('2')] )) s = nodes.If(c, thencond, elsecond) self.assertEqual( str(s.to_c()), "if (a < 12)\n{tab}b = 1;\nelse\n{tab}c = 2;\n" .format(tab=" " * 4), "Failed to convert to C") s = nodes.RootBlockStmt( [ thencond, nodes.BlockStmt([thencond, elsecond]), elsecond ] ) self.assertEqual( str(s.to_c()), "b = 1;\n{{\n{tab}b = 1;\n{tab}c = 2;\n}}\nc = 2;\n" .format(tab=" " * 4), "Failed to convert to C") s = nodes.While(c, thencond) self.assertEqual( str(s.to_c()), "while (a < 12)\n{tab}b = 1;\n" .format(tab=" " * 4), "Failed to convert to C") s = nodes.Do(c, thencond) self.assertEqual( str(s.to_c()), "do\n{tab}b = 1;\nwhile (a < 12);\n" .format(tab=" " * 4), "Failed to convert to C") s = nodes.Return(c) self.assertEqual(str(s.to_c()), "return a < 12;\n", "Failed to convert to C") s = nodes.Goto(c) self.assertEqual(str(s.to_c()), "goto a < 12;\n", "Failed to convert to C") s = nodes.Case(c) self.assertEqual(str(s.to_c()), "case a < 12:\n", "Failed to convert to C") s = nodes.Label("Cool") self.assertEqual(str(s.to_c()), "Cool:\n", "Failed to convert to C") s = nodes.Switch(c, thencond) self.assertEqual( str(s.to_c()), "switch (a < 12)\n{tab}b = 1;\n" .format(tab=" " * 4), "Failed to convert to C") init = nodes.ExprStmt( nodes.Binary( nodes.Raw('='), [nodes.Id('b'), nodes.Literal('0')] )) cond = nodes.ExprStmt(c) inc = nodes.Binary( nodes.Raw('+='), [nodes.Id('b'), nodes.Literal('1')] ) s = nodes.For(init, cond, inc, thencond) self.assertEqual( str(s.to_c()), "for (b = 0; a < 12; b += 1)\n{tab}b = 1;\n" .format(tab=" " * 4), "Failed to convert to C")
class InternalCnorm_Test(unittest.TestCase): def test_01_basicdecl(self): '''Test cnorm nodes construction''' pass def test_02_basicexpr(self): '''Test cnorm expression nodes''' pass def test_03_basicstmt(self): '''Test cnorm statement nodes''' pass
4
3
78
0
76
1
1
0.02
1
32
31
0
3
0
3
75
237
3
230
20
226
4
127
20
123
1
2
0
3
146,065
LionelAuroux/cnorm
LionelAuroux_cnorm/cnorm/nodes.py
cnorm.nodes.While
class While(Conditional): """While statement""" def __init__(self, condition: Expr, body: Stmt): Conditional.__init__(self, condition) self.body = body
class While(Conditional): '''While statement''' def __init__(self, condition: Expr, body: Stmt): pass
2
1
3
0
3
0
1
0.25
1
1
1
0
1
1
1
2
6
1
4
3
2
1
4
3
2
1
3
0
1
146,066
LionelAuroux/cnorm
LionelAuroux_cnorm/cnorm/parsing/declaration.py
cnorm.parsing.declaration.Declaration
class Declaration(Grammar, Statement): """ interaction with other CNORM PART: """ #: entry point for C programming language entry = "translation_unit" #: complete C declaration grammar grammar = """ translation_unit = [ @ignore("C/C++") [ __scope__:current_block #new_root(_, current_block) [ declaration ]* ] Base.eof ] declaration = [ ';' // garbage single comma | c_decl | preproc_decl | asm_decl ] preproc_decl = [ ['#' preproc_directive ]:decl #raw_decl(decl) #end_decl(current_block, decl) ] asm_decl = [ [ Base.id:i #check_asm(i) [ Base.id:i #check_quali(i) ]? attr_asm_decl_follow ';'? ]:decl #raw_decl(decl) #end_decl(current_block, decl) ] attr_asm_decl = [ [ Base.id:i #check_asmattr(i) attr_asm_decl_follow ] ] attr_asm_decl_follow = [ '(' dummy_with_paren* ')' | '{' dummy_with_brace* '}' | '__extension__' ] c_decl = [ __scope__:local_specifier #create_ctype(local_specifier) declaration_specifier*:dsp init_declarator:decl #not_empty(current_block, dsp, decl) #end_decl(current_block, decl) [ ',' #copy_ctype(local_specifier, decl) init_declarator:decl #end_decl(current_block, decl) ]* [ ';' | Statement.compound_statement:b #add_body(decl, b) ] ] declaration_specifier = [ Base.id:i #new_decl_spec(local_specifier, i, current_block) [ #is_composed(local_specifier) composed_type_specifier | #is_enum(local_specifier) enum_specifier | #is_typeof(i) typeof_expr ]? | attr_asm_decl:attr #add_attr_specifier(local_specifier, attr) ] type_qualifier = [ Base.id:i #add_qual(local_specifier, i) | attr_asm_decl:attr #add_attr_specifier(local_specifier, attr) ] name_of_composed_type = [ Base.id ] composed_type_specifier = [ [ attr_asm_decl:attr #add_attr_composed(local_specifier, attr) ]? name_of_composed_type?:n composed_fields?:body #add_composed(local_specifier, n, body) ] composed_fields = [ '{' __scope__:current_block #new_composed(_, current_block) declaration* '}' ] enum_name = [ Base.id ] enum_specifier = [ enum_name?:n enumerator_list?:body #add_enum(local_specifier, n, body) ] enumerator_list = [ '{' enumerator:e #add_enumerator(_, e) [ ',' enumerator:e #add_enumerator(_, e) ]* ','? // trailing comma '}' ] enumerator = [ identifier:i __scope__:c ['=' constant_expression:>c]? #new_enumerator(_, i, c) ] typeof_expr = [ // TODO: split inside typeof ['(' [ type_name !!')' | expression ] ')']:tof #add_typeof(local_specifier, tof) ] init_declarator = [ declarator:>_ [ ':' constant_expression:cexpr #colon_expr(_, cexpr) ]? [ attr_asm_decl:attr #add_attr_decl(_, attr) ]* [ '=' initializer:aexpr #assign_expr(_, aexpr) ]? !![','|';'|'{'] ] declarator = [ [ "*" #first_pointer(local_specifier) declarator_recurs:>_ | absolute_declarator:>_ ] #commit_declarator(_, local_specifier) ] declarator_recurs = [ pointer absolute_declarator:>_ ] pointer = [ [ "*" #add_pointer(local_specifier) | type_qualifier ]* ] f_or_v_id = [ identifier ] absolute_declarator = [ [ '(' #add_paren(local_specifier) type_qualifier? declarator_recurs:>_ #close_paren(local_specifier) ')' | f_or_v_id?:name #name_absdecl(local_specifier, name) ] direct_absolute_declarator? ] direct_absolute_declarator = [ [ '[' // TODO: handle c99 qual for trees "static"? ["const"|"volatile"]? "static"? __scope__:expr [ assignement_expression:>expr | '*':star #new_raw(expr, star) ]? #add_ary(local_specifier, expr) ']' ]+ | '(' #open_params(local_specifier) [ //kr_parameter_type_list //| parameter_type_list ]? ')' /* [ // K&R STYLE !![';'|','|'{'|'('|')'] | declaration* ] */ ] kr_parameter_type_list = [ identifier [',' identifier]* !!')' ] parameter_type_list = [ [type_name ';']* [ parameter_list ]? ','? ["..." #add_ellipsis(local_specifier)]? ] parameter_list = [ parameter_declaration:p #add_param(local_specifier, p) [',' parameter_declaration:p #add_param(local_specifier, p) ]* ] parameter_declaration = [ type_name:>_ ] initializer = [ [ initializer_block | assignement_expression ]:>_ ] initializer_block = [ '{' __scope__:init_list #new_blockinit(init_list) [initializer_list]? ','? // trailing comma #bind('_', init_list) '}' ] initializer_list = [ designation?:dsign initializer:init #add_init(init_list, init, dsign) [ ',' designation?:dsign initializer:init #add_init(init_list, init, dsign) ]* ] designation = [ designation_list+ '='? | identifier ':' ] designation_list = [ '[' range_expression ']' | dot identifier ] type_name = [ __scope__:local_specifier #create_ctype(local_specifier) declaration_specifier+ declarator:>_ ] ///////// OVERLOAD OF STATEMENT // add declaration in block line_of_code = [ declaration | single_statement:line #end_loc(current_block, line) ] for_statement = [ '(' __scope__:init [ expression_statement:>init | __scope__:current_block #for_decl_begin(current_block) declaration #for_decl_end(init, current_block) ] expression_statement:cond expression?:inc ')' single_statement:body #new_for(_, init, cond, inc, body) ] ///////// OVERLOAD OF EXPRESSION // add cast / sizeof unary_expression = [ // CAST '(' type_name:t ')' [ // simple cast unary_expression | // compound literal initializer_block ]:>_ #to_cast(_, t) | // SIZEOF Base.id:i #sizeof(i) __scope__:n [ '(' type_name:>n ')' | Expression.unary_expression:>n ] #new_sizeof(_, i, n) | Expression.unary_expression:>_ ] // ({}) and __builtin_offsetof primary_expression = [ "({" __scope__:current_block #new_blockexpr(_, current_block) [ line_of_code ]* "})" | // TODO: create special node for that "__builtin_offsetof" '(' [type_name ',' postfix_expression]:bof ')' #new_builtoffset(_, bof) | Expression.primary_expression:>_ ] """
class Declaration(Grammar, Statement): ''' interaction with other CNORM PART: ''' pass
1
1
0
0
0
0
0
0.21
2
0
0
0
0
0
0
0
395
38
298
3
297
64
3
3
2
0
4
0
0
146,067
LionelAuroux/cnorm
LionelAuroux_cnorm/cnorm/parsing/expression.py
cnorm.parsing.expression.Expression
class Expression(Grammar, Literal): """ interaction with other CNORM PART: """ entry = "expression" grammar = """ /* Comment works as in C/C++ */ dummy_with_brace = [ @ignore('null') [ '{' dummy_with_brace* '}' | Base.string | Base.char | Base.read_char:c #check_not_brace(c) ] ] dummy_with_paren = [ @ignore('null') [ '(' dummy_with_paren* ')' | Base.string | Base.char | Base.read_char:c #check_not_paren(c) ] ] expression = [ assignement_expression:>_ [ ',':op #new_raw(op, op) assignement_expression:param #new_binary(_, op, param) ]* ] assign_op = [ @ignore('null') [ '=' !'=' | "+=" | "-=" | "*=" | "/=" | "%=" | "<<=" | ">>=" | "&=" | "^=" | "|=" ]:op #new_raw(_, op) ] assignement_expression = [ conditional_expression:>_ [ assign_op:op assignement_expression:param #new_binary(_, op, param) ]* ] constant_expression = [ conditional_expression:>_ ] conditional_expression = [ logical_or_expression:>_ [ '?' expression?:then ':' assignement_expression?:else #new_ternary(_, then, else) ]? ] logical_or_op = [ @ignore('null') ["||"]:op #new_raw(_, op) ] logical_or_expression = [ logical_and_expression:>_ [ logical_or_op:op logical_and_expression:param #new_binary(_, op, param) ]* ] logical_and_op = [ @ignore('null') ["&&"]:op #new_raw(_, op) ] logical_and_expression = [ or_expression:>_ [ logical_and_op:op or_expression:param #new_binary(_, op, param) ]* ] or_op = [ @ignore('null') ["|" !["|"|"="]]:op #new_raw(_, op) ] or_expression = [ xor_expression:>_ [ or_op:op xor_expression:param #new_binary(_, op, param) ]* ] xor_op = [ @ignore('null') ["^" !"="]:op #new_raw(_, op) ] xor_expression = [ and_expression:>_ [ xor_op:op and_expression:param #new_binary(_, op, param) ]* ] and_op = [ @ignore('null') ["&" !["&"|"="]]:op #new_raw(_, op) ] and_expression = [ equality_expression:>_ [ and_op:op equality_expression:param #new_binary(_, op, param) ]* ] eqneq_op = [ @ignore('null') ["==" | "!="]:op #new_raw(_, op) ] equality_expression = [ relational_expression:>_ [ eqneq_op:op relational_expression:param #new_binary(_, op, param) ]* ] cmp_op = [ @ignore('null') [ "<=" | ">=" | '<' !'<' | '>' !'>' ]:op #new_raw(_, op) ] relational_expression = [ shift_expression:>_ [ cmp_op:op shift_expression:param #new_binary(_, op, param) ]* ] shift_op = [ @ignore('null') [ "<<" !"=" | ">>" !"=" ]:op #new_raw(_, op) ] shift_expression = [ additive_expression:>_ [ shift_op:op additive_expression:param #new_binary(_, op, param) ]* ] add_op = [ @ignore('null') [ '+' !['+'|'='] | '-' !['-'|'='|'>'] ]:op #new_raw(_, op) ] additive_expression = [ multiplicative_expression:>_ [ add_op:op multiplicative_expression:param #new_binary(_, op, param) ]* ] mul_op = [ @ignore('null') [['*'|'/'|'%']:op !'='] #new_raw(_, op) ] multiplicative_expression = [ unary_expression:>_ [ mul_op:op unary_expression:param #new_binary(_, op, param) ]* ] unary_op = [ @ignore('null') ["++" |"--" |"&&" | '&' !'=' | '*' !'=' | '~' !'=' | '!' !'=' | '+' !'=' | '-' !['>'|'='] ]:op #new_raw(_, op) ] unary_expression = [ postfix_expression:>_ | __scope__:op [ unary_op:>op | Base.id:i #is_raw(op, i) ] unary_expression:expr #new_unary(_, op, expr) ] postfix_expression = [ primary_expression:>_ [ __scope__:pres [ '[' expression:expr ']' #new_array_call(pres, _, expr) | '(' func_arg_list?:args ')' #new_func_call(pres, _, args) | '.' identifier:i #new_dot(pres, _, i) | "->" identifier:i #new_arrow(pres, _, i) | ["++"|"--"]:op #new_raw(op, op) #new_post(pres, op, _) ] #bind('_', pres) ]* ] func_arg_list = [ assignement_expression:a #new_arg(_, a) [ ',' assignement_expression:a #new_arg(_, a) ]* ] primary_expression = [ '(' expression:expr ')' #new_paren(_, expr) | [ Literal.literal | identifier ]:>_ ] identifier = [ @ignore('null') [ rootidentifier:id #check_is_id(id) #new_id(_, id) ] ] rootidentifier = [ Base.id ] """
class Expression(Grammar, Literal): ''' interaction with other CNORM PART: ''' pass
1
1
0
0
0
0
0
0.2
2
0
0
1
0
0
0
0
264
24
215
3
214
44
3
3
2
0
2
0
0
146,068
LionelAuroux/cnorm
LionelAuroux_cnorm/cnorm/parsing/literal.py
cnorm.parsing.literal.Literal
class Literal(Grammar): """ interaction with other CNORM PART: Expression.primary_expression -> Literal.literal """ grammar = """ dot = [ '.' !'.' ] pow = [ 'p' | 'P' ] exp = [ ['e'|'E'] ['+'|'-']? ['0'..'9']+ ] unsigned_suffix = [ 'u' | 'U' ] long_suffix = [ 'l' | 'L' ] float_suffix = [ 'f' | 'F' ] complex_suffix = [ 'i' | 'I' | 'j' | 'J' ] decimal_const = [ ['0'..'9']+ unsigned_suffix? long_suffix? long_suffix? ] hexadecimal_prefix = [ '0' ['x'|'X'] ] hexadecimal_digit = [ ['0'..'9'|'a'..'f'|'A'..'F'] ] hexadecimal_const_int = [ hexadecimal_prefix [hexadecimal_digit]+ unsigned_suffix? long_suffix? long_suffix? ] octal_digit = [ '0'..'7' ] octal_const = [ '0' octal_digit+ [ dot octal_digit+ [pow ['+'|'-']? decimal_const]? ]? ] double_const = [ [decimal_const dot ['0'..'9']*| dot ['0'..'9']+] exp? long_suffix? float_suffix? complex_suffix? ] encoding_prefix = [ "u8" | 'u' | 'U' | 'L' ] string_const = [ encoding_prefix? Base.string ] char_const = [ encoding_prefix? Base.char ] literal = [ @ignore('null') [ hexadecimal_const_int | octal_const | double_const | decimal_const | char_const ]:val #new_literal(_, val) | __scope__:val [string_const:v #concat_str(val, v)]+ #new_string(_, val) ] """
class Literal(Grammar): ''' interaction with other CNORM PART: Expression.primary_expression -> Literal.literal ''' pass
1
1
0
0
0
0
0
0.12
1
0
0
1
0
0
0
0
82
19
57
2
56
7
2
2
1
0
1
0
0
146,069
LionelAuroux/cnorm
LionelAuroux_cnorm/cnorm/parsing/statement.py
cnorm.parsing.statement.Statement
class Statement(Grammar, Expression): """ interaction with other CNORM PART: Declaration.init_declarator -> compound_statement Expression.primary_expression """ entry = "single_statement" grammar = """ /* Comment works as in C/C++ */ single_statement = [ [compound_statement | labeled_statement | expression_statement ]:>_ ] compound_statement = [ [ '{' __scope__:current_block #new_blockstmt(_, current_block) [ line_of_code ]* '}' ] ] line_of_code = [ single_statement:line #end_loc(current_block, line) ] labeled_statement = [ Expression.rootidentifier:ident [ #check_stmt(ident, "if") if_statement:>_ | #check_stmt(ident, "for") for_statement:>_ | #check_stmt(ident, "while") while_statement:>_ | #check_stmt(ident, "switch") switch_statement:>_ | #check_stmt(ident, "do") do_statement:>_ | #check_stmt(ident, "return") return_statement:>_ | #check_stmt(ident, "goto") goto_statement:>_ | #check_stmt(ident, "case") case_statement:>_ | #check_stmt(ident, "break") ';' #new_break(_) | #check_stmt(ident, "continue") ';' #new_continue(_) | ':' #new_label(_, ident) ] ] if_statement = [ '(' expression:cond ')' single_statement:then __scope__:else [ "else" single_statement:>else ]? #new_if(_, cond, then, else) ] for_statement = [ '(' expression_statement:init expression_statement:cond expression?:inc ')' single_statement:body #new_for(_, init, cond, inc, body) ] while_statement = [ '(' expression:cond ')' single_statement:body #new_while(_, cond, body) ] switch_statement = [ '(' expression:cond ')' single_statement:body #new_switch(_, cond, body) ] do_statement = [ single_statement:body "while" '(' expression:cond ')' ';' #new_do(_, cond, body) ] return_statement = [ expression?:e ';' #new_return(_, e) ] goto_statement = [ expression:e ';' #new_goto(_, e) ] range_expression = [ constant_expression:>_ [ "..." constant_expression:r #new_range(_, r) ]? ] case_statement = [ range_expression:e #new_case(_, e) ':' ] expression_statement = [ [expression:e #new_expr(_, e)]? ';' ] """
class Statement(Grammar, Expression): ''' interaction with other CNORM PART: Declaration.init_declarator -> compound_statement Expression.primary_expression ''' pass
1
1
0
0
0
0
0
0.3
2
0
0
1
0
0
0
0
125
17
93
3
92
28
3
3
2
0
3
0
0
146,070
LionelAuroux/cnorm
LionelAuroux_cnorm/tests/cnorm_pickle.py
tests.cnorm_pickle.CnormPickle_Test
class CnormPickle_Test(unittest.TestCase): def test_01_basic(self): """Basic pickle function test""" decl = Declaration() src = "void *const (*func(int))(char *);" res = decl.parse(src) buf = res.to_pickle() res2 = pickle.from_pickle(buf) self.assertEqual(res, res2, "Fail to save/restore from variable with pickle") src = "double *volatile * (*func(int))(char *);" res = decl.parse(src) buf = res.save_pickle("/tmp/test.pickle") res2 = pickle.from_pickle("/tmp/test.pickle") self.assertEqual(res, res2, "Fail to save/restore from file with pickle")
class CnormPickle_Test(unittest.TestCase): def test_01_basic(self): '''Basic pickle function test''' pass
2
1
13
0
12
1
1
0.08
1
1
1
0
1
0
1
73
15
1
13
7
11
1
13
7
11
1
2
0
1
146,071
LionelAuroux/cnorm
LionelAuroux_cnorm/tests/internal_parsing.py
tests.internal_parsing.InternalParsing_Test
class InternalParsing_Test(unittest.TestCase): def test_00_literal(self): lit = literal.Literal(raise_diagnostic=False) res = lit.parse(".", "dot") self.assertTrue(res, "Failed to parse a single dot") res = lit.parse("..", "dot") self.assertFalse(res, "Failed to detect the error") # HEXA res = lit.parse("0xcafebabe", "literal") self.assertTrue(type(res) is nodes.Literal, "Failed to set the correct type node") self.assertEqual(res.value, "0xcafebabe", "Failed to get the correct node value") # OCTAL res = lit.parse("0700", "literal") self.assertTrue(type(res) is nodes.Literal, "Failed to set the correct type node") self.assertEqual(res.value, "0700", "Failed to get the correct node value") res = lit.parse("033.3p-1", "literal") self.assertTrue(type(res) is nodes.Literal, "Failed to set the correct type node") self.assertEqual(res.value, "033.3p-1", "Failed to get the correct node value") # FLOAT res = lit.parse("6.6", "literal") self.assertTrue(type(res) is nodes.Literal, "Failed to set the correct type node") self.assertEqual(res.value, "6.6", "Failed to get the correct node value") res = lit.parse(".8e+4", "literal") self.assertTrue(type(res) is nodes.Literal, "Failed to set the correct type node") self.assertEqual(res.value, ".8e+4", "Failed to get the correct node value") res = lit.parse("3.E4", "literal") self.assertTrue(type(res) is nodes.Literal, "Failed to set the correct type node") self.assertEqual(res.value, "3.E4", "Failed to get the correct node value") res = lit.parse("3.12L", "literal") self.assertTrue(type(res) is nodes.Literal, "Failed to set the correct type node") self.assertEqual(res.value, "3.12L", "Failed to get the correct node value") res = lit.parse("6.02e23f", "literal") self.assertTrue(type(res) is nodes.Literal, "Failed to set the correct type node") self.assertEqual(res.value, "6.02e23f", "Failed to get the correct node value") # DECIMAL res = lit.parse("42", "literal") self.assertTrue(type(res) is nodes.Literal, "Failed to set the correct type node") self.assertEqual(res.value, "42", "Failed to get the correct node value") res = lit.parse("42u", "literal") self.assertTrue(type(res) is nodes.Literal, "Failed to set the correct type node") self.assertEqual(res.value, "42u", "Failed to get the correct node value") res = lit.parse("42l", "literal") self.assertTrue(type(res) is nodes.Literal, "Failed to set the correct type node") self.assertEqual(res.value, "42l", "Failed to get the correct node value") res = lit.parse("42LL", "literal") self.assertTrue(type(res) is nodes.Literal, "Failed to set the correct type node") self.assertEqual(res.value, "42LL", "Failed to get the correct node value") res = lit.parse("1uLl", "literal") self.assertTrue(type(res) is nodes.Literal, "Failed to set the correct type node") self.assertEqual(res.value, "1uLl", "Failed to get the correct node value") # STRING res = lit.parse('"tutu"', "literal") self.assertTrue(type(res) is nodes.Literal, "Failed to set the correct type node") self.assertEqual(res.value, '"tutu"', "Failed to get the correct node value") res = lit.parse('"tu\\"tu"', "literal") self.assertTrue(type(res) is nodes.Literal, "Failed to set the correct type node") self.assertEqual(res.value, '"tu\\"tu"', "Failed to get the correct node value") res = lit.parse('"to" "ta"', "literal") self.assertEqual(res.value, '"to" "ta"', "Failed to concatenate consecutive string") # CHAR res = lit.parse("'C'", "literal") self.assertTrue(type(res) is nodes.Literal, "Failed to set the correct type node") self.assertEqual(res.value, "'C'", "Failed to get the correct node value") res = lit.parse("'\\''", "literal") self.assertTrue(type(res) is nodes.Literal, "Failed to set the correct type node") self.assertEqual(res.value, "'\\''", "Failed to get the correct node value") def test_01_expr(self): expr = expression.Expression(raise_diagnostic=False) # dummy_with_brace res = expr.parse("{}", "dummy_with_brace") self.assertTrue(res, "Failed to parse an dummy_with_brace") res = expr.parse("{ada{da}da}", "dummy_with_brace") self.assertTrue(res, "Failed to parse an dummy_with_brace") res = expr.parse("{", "dummy_with_brace") self.assertFalse(res, "Failed to detect the error") res = expr.parse("{ewew{d'as}ewe}", "dummy_with_brace") self.assertFalse(res, "Failed to detect the error") # dummy_with_paren res = expr.parse("()", "dummy_with_paren") self.assertTrue(res, "Failed to parse an dummy_with_paren") res = expr.parse("(ada(da)da)", "dummy_with_brace") self.assertTrue(res, "Failed to parse an dummy_with_paren") res = expr.parse("(", "dummy_with_paren") self.assertFalse(res, "Failed to detect the error") res = expr.parse("(ewew(d'as)ewe)", "dummy_with_paren") self.assertFalse(res, "Failed to detect the error") # identifier res = expr.parse("toto", "identifier") self.assertTrue(res, "Failed to parse an identifier") res = expr.parse("struct", "identifier") self.assertFalse(res, "Failed to detect the error") res = expr.parse("toto tata", "identifier") self.assertTrue(res, "Failed to parse an identifier") # primary expression res = expr.parse("toto", "primary_expression") self.assertTrue(res, "Failed to parse an identifier") self.assertTrue(type(res) is nodes.Id, "Failed to set the correct type node") self.assertEqual(res.value, "toto", "Failed to get the correct node value") res = expr.parse("12", "primary_expression") self.assertTrue(res, "Failed to parse a literal") self.assertTrue(type(res) is nodes.Literal, "Failed to set the correct type node") self.assertEqual(res.value, "12", "Failed to get the correct node value") # mul expr res = expr.parse("12 * 4", "multiplicative_expression") self.assertTrue(res, "Failed to parse a multiplicative_expression") self.assertTrue(type(res) is nodes.Binary, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "12 * 4", "Failed to get the correct node value") res = expr.parse("12 * b / c %42 / e", "multiplicative_expression") self.assertTrue(res, "Failed to parse a multiplicative_expression") self.assertTrue(type(res) is nodes.Binary, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "12 * b / c % 42 / e", "Failed to get the correct node value") # add expr res = expr.parse("12 + 4", "additive_expression") self.assertTrue(res, "Failed to parse a additive_expression") self.assertTrue(type(res) is nodes.Binary, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "12 + 4", "Failed to get the correct node value") res = expr.parse("12 * 4 + 4 / 2", "additive_expression") self.assertTrue(res, "Failed to parse a additive_expression") self.assertTrue(type(res) is nodes.Binary, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "12 * 4 + 4 / 2", "Failed to get the correct node value") # shift expr res = expr.parse("12 << 4", "shift_expression") self.assertTrue(res, "Failed to parse a shift_expression") self.assertTrue(type(res) is nodes.Binary, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "12 << 4", "Failed to get the correct node value") res = expr.parse("12 + 4 << 4 + 1", "shift_expression") self.assertTrue(res, "Failed to parse a shift_expression") self.assertTrue(type(res) is nodes.Binary, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "12 + 4 << 4 + 1", "Failed to get the correct node value") # relat expr res = expr.parse("12 < 4", "relational_expression") self.assertTrue(res, "Failed to parse a relational_expression") self.assertTrue(type(res) is nodes.Binary, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "12 < 4", "Failed to get the correct node value") res = expr.parse("13 + 1 > 14 - 2", "relational_expression") self.assertTrue(res, "Failed to parse a relational_expression") self.assertTrue(type(res) is nodes.Binary, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "13 + 1 > 14 - 2", "Failed to get the correct node value") # equality expr res = expr.parse("a == 4", "equality_expression") self.assertTrue(res, "Failed to parse a equality_expression") self.assertTrue(type(res) is nodes.Binary, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "a == 4", "Failed to get the correct node value") res = expr.parse("a == c < 5 != b", "equality_expression") self.assertTrue(res, "Failed to parse a equality_expression") self.assertTrue(type(res) is nodes.Binary, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "a == c < 5 != b", "Failed to get the correct node value") # and expr res = expr.parse("a & 4", "and_expression") self.assertTrue(res, "Failed to parse a and_expression") self.assertTrue(type(res) is nodes.Binary, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "a & 4", "Failed to get the correct node value") res = expr.parse("a == b & 4 != 7", "and_expression") self.assertTrue(res, "Failed to parse a and_expression") self.assertTrue(type(res) is nodes.Binary, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "a == b & 4 != 7", "Failed to get the correct node value") # xor expr res = expr.parse("a ^ 4", "xor_expression") self.assertTrue(res, "Failed to parse a xor_expression") self.assertTrue(type(res) is nodes.Binary, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "a ^ 4", "Failed to get the correct node value") res = expr.parse("a & b ^ 4 != 7", "xor_expression") self.assertTrue(res, "Failed to parse a xor_expression") self.assertTrue(type(res) is nodes.Binary, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "a & b ^ 4 != 7", "Failed to get the correct node value") # or expr res = expr.parse("a | 4", "or_expression") self.assertTrue(res, "Failed to parse a or_expression") self.assertTrue(type(res) is nodes.Binary, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "a | 4", "Failed to get the correct node value") res = expr.parse("a == b | 4 != 7", "or_expression") self.assertTrue(res, "Failed to parse a or_expression") self.assertTrue(type(res) is nodes.Binary, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "a == b | 4 != 7", "Failed to get the correct node value") # && res = expr.parse("a && 4", "logical_and_expression") self.assertTrue(res, "Failed to parse a logical_and_expression") self.assertTrue(type(res) is nodes.Binary, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "a && 4", "Failed to get the correct node value") res = expr.parse("a == b && 4 != 7", "logical_and_expression") self.assertTrue(res, "Failed to parse a logical_and_expression") self.assertTrue(type(res) is nodes.Binary, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "a == b && 4 != 7", "Failed to get the correct node value") # || res = expr.parse("a || 4", "logical_or_expression") self.assertTrue(res, "Failed to parse a logical_or_expression") self.assertTrue(type(res) is nodes.Binary, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "a || 4", "Failed to get the correct node value") res = expr.parse("a == b || 4 != 7", "logical_or_expression") self.assertTrue(res, "Failed to parse a logical_or_expression") self.assertTrue(type(res) is nodes.Binary, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "a == b || 4 != 7", "Failed to get the correct node value") # ? : res = expr.parse("a < 7 ? 4 : 8 + b", "conditional_expression") self.assertTrue(res, "Failed to parse a conditional_expression") self.assertTrue(type(res) is nodes.Ternary, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "a < 7 ? 4 : 8 + b", "Failed to get the correct node value") # assignement res = expr.parse("a = 5 + 4 += b - d <<= 3", "assignement_expression") self.assertTrue(res, "Failed to parse a assignement_expression") self.assertTrue(type(res) is nodes.Binary, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "a = 5 + 4 += b - d <<= 3", "Failed to get the correct node value") # expression res = expr.parse("a = 5, b = c, f >>= 42", "expression") self.assertTrue(res, "Failed to parse a expression") self.assertTrue(type(res) is nodes.Binary, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "a = 5, b = c, f >>= 42", "Failed to get the correct node value") # () res = expr.parse("(a * (1 + b))", "expression") self.assertTrue(res, "Failed to parse an () expression") self.assertTrue(type(res) is nodes.Paren, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "(a * (1 + b))", "Failed to get the correct node value") # unary res = expr.parse("+a * -1 + -b", "expression") self.assertTrue(res, "Failed to parse an expression with unarys") self.assertTrue(type(res) is nodes.Binary, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "+a * -1 + -b", "Failed to get the correct node value") # post res = expr.parse("a++ * --c++ + ++b", "expression") self.assertTrue(res, "Failed to parse an expression with post/pre") self.assertTrue(type(res) is nodes.Binary, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "a++ * --c++ + ++b", "Failed to get the correct node value") # func call res = expr.parse("a()", "expression") self.assertTrue(res, "Failed to parse an expression with func") self.assertTrue(type(res) is nodes.Func, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "a()", "Failed to get the correct node value") res = expr.parse("a(b, 12 + 4, ++z)", "expression") self.assertTrue(res, "Failed to parse an expression with func") self.assertTrue(type(res) is nodes.Func, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "a(b, 12 + 4, ++z)", "Failed to get the correct node value") # array call res = expr.parse("tab[z * i]", "expression") self.assertTrue( res, "Failed to parse an expression with array indexes") self.assertTrue(type(res) is nodes.Array, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "tab[z * i]", "Failed to get the correct node value") # field res = expr.parse("s.i", "expression") self.assertTrue( res, "Failed to parse an expression with array indexes") self.assertTrue(type(res) is nodes.Dot, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "s.i", "Failed to get the correct node value") # field deref res = expr.parse("p->i", "expression") self.assertTrue( res, "Failed to parse an expression with array indexes") self.assertTrue(type(res) is nodes.Arrow, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "p->i", "Failed to get the correct node value") def test_02_stmt(self): stmt = statement.Statement() # expression statement res = stmt.parse("a = 4 * 5 + 12;", "expression_statement") self.assertTrue(res, "Failed to parse a expression_statement") self.assertTrue(type(res) is nodes.ExprStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "a = 4 * 5 + 12;\n", "Failed to get the correct node value") # while statement res = stmt.parse("while (a == 42)\n c = 52;\n", "labeled_statement") self.assertTrue(res, "Failed to parse a labeled_statement") self.assertTrue(type(res) is nodes.While, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "while (a == 42)\n c = 52;\n", "Failed to get the correct node value") # if statement res = stmt.parse("if (a == 42)\n\tc = 52;\n", "labeled_statement") self.assertTrue(res, "Failed to parse a labeled_statement") self.assertTrue(type(res) is nodes.If, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "if (a == 42)\n c = 52;\n", "Failed to get the correct node value") res = stmt.parse("if (a == 51)\n\tg = \"toto\";\nelse\n\td = 666;\n", "labeled_statement") self.assertTrue(res, "Failed to parse a labeled_statement") self.assertTrue(type(res) is nodes.If, "Failed to set the correct type node") self.assertEqual( str(res.to_c()), "if (a == 51)\n g = \"toto\";\nelse\n d = 666;\n", "Failed to get the correct node value") # do statement res = stmt.parse("do\n{\n x += 12;\n " + "g = x * 3;\n}\nwhile (z < 12);\n", "labeled_statement") self.assertTrue(res, "Failed to parse a labeled_statement") self.assertTrue(type(res) is nodes.Do, "Failed to set the correct type node") self.assertEqual( str(res.to_c()), ("do\n%s{\n%sx += 12;\n%s" + "g = x * 3;\n%s}\nwhile (z < 12);\n") % (" " * 4, " " * 8, " " * 8, " " * 4), "Failed to get the correct node value") # return res = stmt.parse("return a == 12;\n", "labeled_statement") self.assertTrue(res, "Failed to parse a labeled_statement") self.assertTrue(type(res) is nodes.Return, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "return a == 12;\n", "Failed to get the correct node value") # goto res = stmt.parse("goto toto;\n", "labeled_statement") self.assertTrue(res, "Failed to parse a labeled_statement") self.assertTrue(type(res) is nodes.Goto, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "goto toto;\n", "Failed to get the correct node value") # label res = stmt.parse("toto:\n", "labeled_statement") self.assertTrue(res, "Failed to parse a labeled_statement") self.assertTrue(type(res) is nodes.Label, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "toto:\n", "Failed to get the correct node value") # case res = stmt.parse("case 12:\n", "labeled_statement") self.assertTrue(res, "Failed to parse a labeled_statement") self.assertTrue(type(res) is nodes.Case, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "case 12:\n", "Failed to get the correct node value") # switch statement res = stmt.parse("switch (a == 42)\n{\n case 12:\n}\n", "labeled_statement") self.assertTrue(res, "Failed to parse a labeled_statement") self.assertTrue(type(res) is nodes.Switch, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "switch (a == 42)\n {\n " + " case 12:\n }\n", "Failed to get the correct node value") # for statement res = stmt.parse("for (b = 0; a < 12; b += 1)\n b = 1;\n", "labeled_statement") self.assertTrue(res, "Failed to parse a labeled_statement") self.assertTrue(type(res) is nodes.For, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "for (b = 0; a < 12; b += 1)\n" + " b = 1;\n", "Failed to get the correct node value") def test_03_decl(self): decl = declaration.Declaration() # basic transaction_unit res = decl.parse("int a;") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "int a;\n", "Failed to pretty print correctly") res = decl.parse("int a= 42;") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "int a = 42;\n", "Failed to pretty print correctly") res = decl.parse("int a= 42 * b - c;") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "int a = 42 * b - c;\n", "Failed to pretty print correctly") # basic decl res = decl.parse("unsigned int a;") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "unsigned int a;\n", "Failed to pretty print correctly") res = decl.parse("const int a;") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "const int a;\n", "Failed to pretty print correctly") res = decl.parse("extern int a;") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "extern int a;\n", "Failed to pretty print correctly") # normalize type res = decl.parse("unsigned long long a;") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "unsigned long long int a;\n", "Failed to pretty print correctly") # pointer type res = decl.parse("char *ptr;") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "char *ptr;\n", "Failed to pretty print correctly") res = decl.parse("char * const ptr2;") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "char *const ptr2;\n", "Failed to pretty print correctly") res = decl.parse("const char * ptr;") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "const char *ptr;\n", "Failed to pretty print correctly") # copy decl and pointer type res = decl.parse("char a, *ptr, (* const b), (*z);") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual( str(res.to_c()), "char a;\nchar *ptr;\nchar " + "(*const b);\nchar (*z);\n", "Failed to pretty print correctly") # array type res = decl.parse("char ptr[20];") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "char ptr[20];\n", "Failed to pretty print correctly") res = decl.parse("char ptr[*];") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "char ptr[*];\n", "Failed to pretty print correctly") # func type res = decl.parse("char ptr(int a, double v);") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "char ptr(int a, double v);\n", "Failed to pretty print correctly") res = decl.parse("char ptr(int z, double const c);") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "char ptr(int z, const double c);\n", "Failed to pretty print correctly") # paren type res = decl.parse("char (t);") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "char (t);\n", "Failed to pretty print correctly") res = decl.parse("char (*t);") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "char (*t);\n", "Failed to pretty print correctly") res = decl.parse("char t[20];") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "char t[20];\n", "Failed to pretty print correctly") res = decl.parse("char t[20][6];") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "char t[20][6];\n", "Failed to pretty print correctly") res = decl.parse("char t[20][6][42];") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "char t[20][6][42];\n", "Failed to pretty print correctly") res = decl.parse("char *t[20];") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "char *t[20];\n", "Failed to pretty print correctly") res = decl.parse("char *(t[20]);") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "char *(t[20]);\n", "Failed to pretty print correctly") res = decl.parse("char (*t)(int a);") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "char (*t)(int a);\n", "Failed to pretty print correctly") res = decl.parse("char (*f(int b, double c))(int a);") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual( str(res.to_c()), "char (*f(int b, double c))(int a);\n", "Failed to pretty print correctly") res = decl.parse("char (*t)[20];") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "char (*t)[20];\n", "Failed to pretty print correctly") res = decl.parse("char (*t)[20][6];") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "char (*t)[20][6];\n", "Failed to pretty print correctly") res = decl.parse("""char *t[] = {"tutu", "toto", "tata", "titi"};""") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual( str(res.to_c()), """char *t[] = { "tutu", "toto", "tata", "titi" };\n""", "Failed to pretty print correctly") res = decl.parse("""enum color {\n RED,\n BLUE,\n WHITE};""") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual( str(res.to_c()), """enum color {\n RED,\n BLUE,\n WHITE};\n""", "Failed to pretty print correctly") res = decl.parse("enum id {\n PJ = 1,\n MOB = 2,\n" + " VOID = 0,\n WALL = 3};") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "enum id {\n PJ = 1,\n" + " MOB = 2,\n VOID = 0,\n WALL = 3};\n", "Failed to pretty print correctly") res = decl.parse("struct pj {\n int level;\n int pv;\n " + "double px;\n double py;\n double pz;\n " + " int ac;\n int tac0;};") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), "struct pj {\n int level;\n " + " int pv;\n double px;\n double py;\n " + " double pz;\n int ac;\n int tac0;\n };\n", "Failed to pretty print correctly") def test_04_integration(self): # declaration|single_statement decl = declaration.Declaration() res = decl.parse("""int main(int ac, char **av) { int b = 42; b = b - 2; } """) self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual( str(res.to_c()), "int main(int ac, char **av)\n{\n " + "int b = 42;\n b = b - 2;\n}\n", "Failed to pretty print correctly") # in global scope, implicit 'int' res = decl.parse("""a = 42;b(int, double);""") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual( str(res.to_c()), """int a = 42;\nint b(int, double);\n""", "Failed to pretty print correctly") # cast decl = declaration.Declaration() res = decl.parse("""int NULL = (void *) 0;\n""") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), """int NULL = (void *) 0;\n""", "Failed to pretty print correctly") # sizeof decl = declaration.Declaration() res = decl.parse("""int NULLSZ = sizeof (void *) * 2;\n""") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual( str(res.to_c()), """int NULLSZ = sizeof (void *) * 2;\n""", "Failed to pretty print correctly") decl = declaration.Declaration() res = decl.parse("""int NULLSZ = sizeof z * 2;\n""") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual( str(res.to_c()), """int NULLSZ = sizeof z * 2;\n""", "Failed to pretty print correctly") # typedef decl = declaration.Declaration() res = decl.parse("""typedef int ZZZ;\nZZZ a;\n""") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), """typedef int ZZZ;\nZZZ a;\n""", "Failed to pretty print correctly") decl = declaration.Declaration() res = decl.parse("""typedef int ZZZ;\ntypedef ZZZ aaa;\naaa b;\n""") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual( str(res.to_c()), "typedef int ZZZ;\ntypedef ZZZ aaa;\naaa b;\n", "Failed to pretty print correctly") # unary real/imag decl = declaration.Declaration() res = decl.parse("""float f = __real__ c;\n""") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), """float f = __real__ c;\n""", "Failed to pretty print correctly") # attributes decl = declaration.Declaration() res = decl.parse("""float f(int a) __attribute__((noreturn));\n""") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual( str(res.to_c()), "float f(int a) __attribute__((noreturn));\n", "Failed to pretty print correctly") decl = declaration.Declaration() res = decl.parse("struct s __attribute__((vector_size (16))) foo;\n") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual( str(res.to_c()), "struct s __attribute__((vector_size (16))) foo;\n", "Failed to pretty print correctly") decl = declaration.Declaration() res = decl.parse("""char *__attribute__((aligned(8))) *f;\n""") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual( str(res.to_c()), "char *__attribute__((aligned(8))) *f;\n", "Failed to pretty print correctly") # compound literal decl = declaration.Declaration() res = decl.parse("""struct x a[] = (struct x*) {1, 2, 3};\n""") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual( str(res.to_c()), "struct x a[] = (struct x *) { 1, 2, 3 };\n", "Failed to pretty print correctly") # compound expression decl = declaration.Declaration() res = decl.parse("struct x a[] = ({\n " + "int z = 42;\n z += 5;\n });\n") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual( str(res.to_c()), "struct x a[] = ({\n int z = 42;\n z += 5;\n});\n", "Failed to pretty print correctly") # typeof decl = declaration.Declaration() res = decl.parse("""typeof(z) g;\n""") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual(str(res.to_c()), """typeof(z) g;\n""", "Failed to pretty print correctly") # __builtin_offsetof decl = declaration.Declaration() res = decl.parse("int a = __builtin_offsetof(struct bla, field1);\n") self.assertTrue(res, "Failed to parse a cdecl") self.assertTrue(type(res) is nodes.RootBlockStmt, "Failed to set the correct type node") self.assertEqual( str(res.to_c()), "int a = __builtin_offsetof(struct bla, field1);\n", "Failed to pretty print correctly")
class InternalParsing_Test(unittest.TestCase): def test_00_literal(self): pass def test_01_expr(self): pass def test_02_stmt(self): pass def test_03_decl(self): pass def test_04_integration(self): pass
6
0
159
0
147
12
1
0.08
1
26
24
0
5
0
5
77
799
5
735
16
729
59
459
16
453
1
2
0
5
146,072
LionelAuroux/cnorm
LionelAuroux_cnorm/tests/samples.py
tests.samples.Samples_Test
class Samples_Test(unittest.TestCase): def test_all(self): sample_path = path.join(path.dirname(__file__), 'samples') print("\nTest samples:") for f in sorted(os.listdir(sample_path)): if f.endswith(".c"): fpath = path.join(sample_path, f) fpout = fpath + "_out" print("- read: %s" % fpath) if path.exists(fpout): print("* skip") continue cparse = declaration.Declaration() res = cparse.parse_file(fpath) if res: self.assertTrue(res, "Failed to parse %s" % fpath) fout = open(fpout, "w") fout.write(str(res.to_c())) fout.close() else: print("* error see logs") fout = open(fpath + ".log", "w") fout.write( res.diagnostic.get_content( with_locinfos=True, with_details=True ) ) fout.close()
class Samples_Test(unittest.TestCase): def test_all(self): pass
2
0
28
0
28
0
5
0
1
2
1
0
1
0
1
73
30
1
29
9
27
0
23
9
21
5
2
3
5
146,073
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.LookAhead
class LookAhead(Functor): """ !!A bnf primitive as a functor. """ def __init__(self, pt: Functor): Functor.__init__(self) self.pt = pt if isinstance(self.pt, Seq): if isinstance(self.pt.ptlist[0], SkipIgnore): self.pt.ptlist.pop(0) if isinstance(self.pt.ptlist[-1], SkipIgnore): self.pt.ptlist.pop() def do_call(self, parser: BasicParser) -> bool: parser._stream.save_context() res = self.pt(parser) parser._stream.restore_context() return res
class LookAhead(Functor): ''' !!A bnf primitive as a functor. ''' def __init__(self, pt: Functor): pass def do_call(self, parser: BasicParser) -> bool: pass
3
1
7
0
7
0
3
0.07
1
4
3
0
2
1
2
4
16
1
14
5
11
1
14
5
11
4
1
2
5
146,074
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.MetaDecoratorWrapper
class MetaDecoratorWrapper(type): """ metaclass of all DecoratorWrapper subclasses. ensure that begin and end exists in subclasses as method """ def __new__(metacls, name, bases, namespace): cls = type.__new__(metacls, name, bases, namespace) if 'begin' not in namespace: raise TypeError( "DirectiveWrapper %s must have a begin method" % name) if not(isinstance(namespace['begin'], types.FunctionType)): raise TypeError( "'begin' not a function class in DirectiveWrapper %s" % name) if 'end' not in namespace: raise TypeError( "DirectiveWrapper %s subclasse must have a end method" % name) if not(isinstance(namespace['end'], types.FunctionType)): raise TypeError( "'end' not a function class in DirectiveWrapper %s" % name) return cls
class MetaDecoratorWrapper(type): ''' metaclass of all DecoratorWrapper subclasses. ensure that begin and end exists in subclasses as method ''' def __new__(metacls, name, bases, namespace): pass
2
1
15
0
15
0
5
0.19
1
1
0
1
1
0
1
14
19
0
16
3
14
3
12
3
10
5
2
1
5
146,075
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.MetaDirectiveWrapper
class MetaDirectiveWrapper(type): """ metaclass of all DirectiveWrapper subclasses. ensure that begin and end exists in subclasses as method """ def __new__(metacls, name, bases, namespace): cls = type.__new__(metacls, name, bases, namespace) if 'begin' not in namespace: raise TypeError( "DirectiveWrapper %s must have a begin method" % name) if not(isinstance(namespace['begin'], types.FunctionType)): raise TypeError( "'begin' not a function class in DirectiveWrapper %s" % name) if 'end' not in namespace: raise TypeError( "DirectiveWrapper %s subclasse must have a end method" % name) if not(isinstance(namespace['end'], types.FunctionType)): raise TypeError( "'end' not a function class in DirectiveWrapper %s" % name) return cls
class MetaDirectiveWrapper(type): ''' metaclass of all DirectiveWrapper subclasses. ensure that begin and end exists in subclasses as method ''' def __new__(metacls, name, bases, namespace): pass
2
1
15
0
15
0
5
0.19
1
1
0
1
1
0
1
14
19
0
16
3
14
3
12
3
10
5
2
1
5
146,076
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/unify.py
tests.unify.T
class T: """T for Type""" def __init__(self, name: str, parametric: Tuple or 'T'=None, attributes=None): self.name = name if parametric is not None and type(parametric) not in {Tuple, T}: raise TypeError("T parametric must be a Tuple") self.parametric = parametric self.attributes = attributes def unify(self, oth_type_def: TypeExprComponent, blhs, brhs) -> TypeExprComponent: """ When we unify a type vs another type def we match each term to term t1 ?? t1 match t1 ?? t2 didn't match TODO: parametric """ print("T TRY TO unify %s ?? %s" % (self, oth_type_def)) return self.name == oth_type_def def __eq__(self, oth) -> bool: """ Use by all __contains__ call when we do some 'in' test """ # TODO: self and oth for comparaison with TypeVar, attributes and parametric return self.name == oth def __str__(self) -> str: r = self.name if self.parametric is not None: r += '<' + str(self.parametric) + '>' return r def __repr__(self) -> str: return str(self)
class T: '''T for Type''' def __init__(self, name: str, parametric: Tuple or 'T'=None, attributes=None): pass def unify(self, oth_type_def: TypeExprComponent, blhs, brhs) -> TypeExprComponent: ''' When we unify a type vs another type def we match each term to term t1 ?? t1 match t1 ?? t2 didn't match TODO: parametric ''' pass def __eq__(self, oth) -> bool: ''' Use by all __contains__ call when we do some 'in' test ''' pass def __str__(self) -> str: pass def __repr__(self) -> str: pass
6
3
6
0
4
2
1
0.58
0
6
2
0
5
3
5
5
35
5
19
10
13
11
19
10
13
2
0
1
7
146,077
LionelAuroux/pyrser
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LionelAuroux_pyrser/tests/internal_parse.py
tests.internal_parse.InternalParse_Test.test_14_MetaGrammar.SubGrammar
class SubGrammar(parsing.Parser, FakeGrammar): pass
class SubGrammar(parsing.Parser, FakeGrammar): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
0
2
0
2
1
1
0
2
1
1
0
2
0
0
146,078
LionelAuroux/pyrser
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LionelAuroux_pyrser/tests/internal_parse.py
tests.internal_parse.InternalParse_Test.test_12_Metabasicparser.FakeBasic
class FakeBasic(metaclass=parsing.MetaBasicParser): _rules = collections.ChainMap() _hooks = collections.ChainMap() pass
class FakeBasic(metaclass=parsing.MetaBasicParser): pass
1
0
0
0
0
0
0
0
1
0
0
2
0
0
0
0
4
0
4
3
3
0
4
3
3
0
1
0
0
146,079
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.Neg
class Neg(Functor): """ !A bnf primitive as a functor. """ def __init__(self, pt: Functor): Functor.__init__(self) self.pt = pt if isinstance(self.pt, Seq): if isinstance(self.pt.ptlist[0], SkipIgnore): self.pt.ptlist.pop(0) if isinstance(self.pt.ptlist[-1], SkipIgnore): self.pt.ptlist.pop() def do_call(self, parser: BasicParser): parser._stream.save_context() if self.pt(parser): res = parser._stream.restore_context() return res return parser._stream.validate_context()
class Neg(Functor): ''' !A bnf primitive as a functor. ''' def __init__(self, pt: Functor): pass def do_call(self, parser: BasicParser): pass
3
1
7
0
7
0
3
0.07
1
3
3
0
2
1
2
4
18
2
15
5
12
1
15
5
12
4
1
2
6
146,080
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.PeekChar
class PeekChar(Functor, Leaf): """ !!'A' bnf primitive functor. """ def __init__(self, c: str): self.char = c def do_call(self, parser: BasicParser) -> bool: return parser.peek_char(self.char)
class PeekChar(Functor, Leaf): ''' !!'A' bnf primitive functor. ''' def __init__(self, c: str): pass def do_call(self, parser: BasicParser) -> bool: pass
3
1
2
0
2
0
1
0.2
2
3
1
0
2
1
2
4
8
2
5
4
2
1
5
4
2
1
1
0
2
146,081
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/ast/state.py
state.EventExpr
class EventExpr: """ Ast Node for predicate Expression. """ def checkEvent(self, sr: StateRegister, collect: dict) -> bool: return False def clean(self, sr: StateRegister, updown: bool): pass
class EventExpr: ''' Ast Node for predicate Expression. ''' def checkEvent(self, sr: StateRegister, collect: dict) -> bool: pass def clean(self, sr: StateRegister, updown: bool): pass
3
1
2
0
2
0
1
0.6
0
3
1
5
2
0
2
2
9
1
5
3
2
3
5
3
2
1
0
0
2
146,082
LionelAuroux/pyrser
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LionelAuroux_pyrser/tests/internal_type.py
tests.internal_type.InternalType_Test.test_symbol_01_symbolpatch.MyFun
class MyFun(MySymbol, Fun): def internal_name(self): return (super().internal_name() + self.name + "." + "_".join(self.tparams) + "." + self.tret )
class MyFun(MySymbol, Fun): def internal_name(self): pass
2
0
7
0
7
0
1
0
2
1
0
0
1
0
1
3
8
0
8
2
6
0
3
2
1
1
2
0
1
146,083
LionelAuroux/pyrser
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LionelAuroux_pyrser/tests/internal_parse.py
tests.internal_parse.InternalParse_Test.test_14_MetaGrammar.FakeGrammar
class FakeGrammar(metaclass=grammar.MetaGrammar): pass
class FakeGrammar(metaclass=grammar.MetaGrammar): pass
1
0
0
0
0
0
0
0
1
0
0
1
0
0
0
0
2
0
2
1
1
0
2
1
1
0
1
0
0
146,084
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/type_system/fun.py
pyrser.type_system.fun.Fun
class Fun(Signature): """ Describe a function signature for the language """ def __init__( self, name: str, tret: str, tparams: list=None, variadic=None ): if tparams is not None and not isinstance(tparams, list): raise TypeError("Fun's parameter list must be a list") super().__init__(name) if not isinstance(tret, TypeName): tret = TypeName(tret) self.tret = tret self.variadic = variadic self.tparams = None if tparams is not None and len(tparams) > 0: self.tparams = [] for p in tparams: if not isinstance(p, TypeName): p = TypeName(p) self.tparams.append(p) @property def arity(self) -> int: return len(self.tparams) @property def return_type(self) -> str: return self.tret @property def this_type(self) -> str: return self.tparams[0] @property def is_polymorphic(self) -> bool: if self.tret.is_polymorphic: return True for p in self.tparams: if p.is_polymorphic: return True @property def is_fun(self) -> bool: return True def internal_name(self): """ Return the unique internal name """ unq = 'f_' + super().internal_name() if self.tparams is not None: unq += "_" + "_".join(self.tparams) if self.tret is not None: unq += "_" + self.tret return unq def __str__(self) -> str: import pyrser.type_system.to_fmt return str(self.to_fmt())
class Fun(Signature): ''' Describe a function signature for the language ''' def __init__( self, name: str, tret: str, tparams: list=None, variadic=None ): pass @property def arity(self) -> int: pass @property def return_type(self) -> str: pass @property def this_type(self) -> str: pass @property def is_polymorphic(self) -> bool: pass @property def is_fun(self) -> bool: pass def internal_name(self): ''' Return the unique internal name ''' pass def __str__(self) -> str: pass
14
2
6
0
6
0
2
0.12
1
7
1
0
8
3
8
20
65
8
51
27
30
6
40
16
30
6
2
3
18
146,085
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/ast/state.py
state.EventNamed
class EventNamed(EventExpr): """ Ast Node for a named predicate expression. """ def __init__(self, name: str): self.name = name def checkEvent(self, sr: StateRegister, collect: dict) -> bool: if self.name in sr.named_events: collect[self.name] = True return True return False def clean(self, sr: StateRegister, updown: bool) -> bool: self.subexpr.clean(sr, updown) def to_fmt(self) -> fmt.indentable: return self.name def __repr__(self) -> str: return str(self.to_fmt())
class EventNamed(EventExpr): ''' Ast Node for a named predicate expression. ''' def __init__(self, name: str): pass def checkEvent(self, sr: StateRegister, collect: dict) -> bool: pass def clean(self, sr: StateRegister, updown: bool) -> bool: pass def to_fmt(self) -> fmt.indentable: pass def __repr__(self) -> str: pass
6
1
3
0
3
0
1
0.21
1
5
2
0
5
1
5
7
21
4
14
7
8
3
14
7
8
2
1
1
6
146,086
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/type_system/evalctx.py
pyrser.type_system.evalctx.EvalCtx
class EvalCtx: """ Store environment for mono/poly call. """ def __str__(self) -> str: import pyrser.type_system.to_fmt return str(self.to_fmt()) def __init__(self, sig: Signature): self._sig = sig self.resolution = dict() self._translate_to = None self._variadic_types = None self.resolve() def get_parent(self): return self._sig.get_parent() def internal_name(self): return self._sig.internal_name() def show_name(self): return self._sig.show_name() @property def name(self): if self._sig is not None: return self._sig.name return None @property def tret(self): if self._sig is not None and hasattr(self._sig, 'tret'): return self._sig.tret return None @property def compute_tret(self): tret = [] for t in self.tret.components: if t in self.resolution and self.resolution[t] is not None: tret.append(self.resolution[t]().show_name()) else: tret.append(t) return " ".join(tret) @property def tparams(self): if self._sig is not None and hasattr(self._sig, 'tparams'): return self._sig.tparams return None @property def variadic(self): if self._sig is not None and hasattr(self._sig, 'variadic'): return self._sig.variadic return None @property def is_polymorphic(self) -> bool: if self._sig is not None and hasattr(self._sig, 'is_polymorphic'): return self._sig.is_polymorphic return False def from_sig(sig: Signature) -> object: if isinstance(sig, EvalCtx): return sig else: return EvalCtx(sig) def set_parent(self, parent) -> object: """ Forward to intern Signature """ return self._sig.set_parent(parent) def __len__(self) -> int: return len(self._sig) def values(self) -> list: """ Make EvalCtx iterable (to update a scope with it) """ return [self._sig] def get_compute_sig(self) -> Signature: """ Compute a signature Using resolution!!! TODO: discuss of relevance of a final generation for a signature """ tret = [] tparams = [] for t in self.tret.components: if t in self.resolution and self.resolution[t] is not None: tret.append(self.resolution[t]().show_name()) else: tret.append(t) if hasattr(self, 'tparams'): for p in self.tparams: tp = [] for t in p.components: if t in self.resolution and self.resolution[t] is not None: tp.append(self.resolution[t]().show_name()) else: tp.append(t) tparams.append(" ".join(tp)) if self.variadic: if self._variadic_types is None: raise ValueError("Can't compute the sig " + "with unresolved variadic argument" ) for p in self._variadic_types: tp = [] for t in p.components: if (t in self.resolution and self.resolution[t] is not None ): tp.append(self.resolution[t]().show_name()) else: tp.append(t) tparams.append(" ".join(tp)) ret = Fun(self.name, " ".join(tret), tparams) # transform as-is into our internal Signature (Val, Var, whatever) ret.__class__ = self._sig.__class__ return ret def set_parent(self, parent) -> object: """ When we add a parent (from Symbol), don't forget to resolve. """ ret = self if parent is not None: ret = self._sig.set_parent(parent) self.resolve() elif not hasattr(self, 'parent'): # only if parent didn't exist yet self.parent = None return ret def use_translator(self, translator): """ Attach a translator to an EvalCtx to convert output of the function into another type """ self._translate_to = translator self.resolve() def use_variadic_types(self, list_type: [TypeName]): """ Attach a list of types for extra variadic argument of a call """ self._variadic_types = list_type self.resolve() def resolve(self): """ Process the signature and find definition for type. """ # collect types for resolution t2resolv = [] if hasattr(self._sig, 'tret'): t2resolv.append(self._sig.tret) if hasattr(self._sig, 'tparams') and self._sig.tparams is not None: for p in self._sig.tparams: t2resolv.append(p) if self._translate_to is not None: t2resolv.append(self._translate_to.target) if self._variadic_types is not None: for t in self._variadic_types: t2resolv.append(t) for t in t2resolv: for c in t.components: if c not in self.resolution or self.resolution[c] is None: # try to find what is c parent = self.get_parent() if parent is not None: sc = parent.get_by_symbol_name(c) if len(sc) == 1: sc = list(sc.values())[0] # unwrap EvalCtx around Type if isinstance(sc, EvalCtx): sc = sc._sig rtyp = weakref.ref(sc) self.resolution[c] = rtyp continue # unresolved self.resolution[c] = None def get_resolved_names(self, type_name: TypeName) -> list: """ Use self.resolution to subsitute type_name. Allow to instanciate polymorphic type ?1, ?toto """ if not isinstance(type_name, TypeName): raise Exception("Take a TypeName as parameter not a %s" % type(type_name)) rnames = [] for name in type_name.components: if name not in self.resolution: raise Exception("Unknown type %s in a EvalCtx" % name) rname = self.resolution[name] if rname is not None: rname = rname().show_name() else: rname = name rnames.append(rname) return rnames def set_resolved_name(self, ref: dict, type_name2solve: TypeName, type_name_ref: TypeName): """ Warning!!! Need to rethink it when global poly type """ if self.resolution[type_name2solve.value] is None: self.resolution[type_name2solve.value] = ref[type_name_ref.value]
class EvalCtx: ''' Store environment for mono/poly call. ''' def __str__(self) -> str: pass def __init__(self, sig: Signature): pass def get_parent(self): pass def internal_name(self): pass def show_name(self): pass @property def name(self): pass @property def tret(self): pass @property def compute_tret(self): pass @property def tparams(self): pass @property def variadic(self): pass @property def is_polymorphic(self) -> bool: pass def from_sig(sig: Signature) -> object: pass def set_parent(self, parent) -> object: ''' Forward to intern Signature ''' pass def __len__(self) -> int: pass def values(self) -> list: ''' Make EvalCtx iterable (to update a scope with it) ''' pass def get_compute_sig(self) -> Signature: ''' Compute a signature Using resolution!!! TODO: discuss of relevance of a final generation for a signature ''' pass def set_parent(self, parent) -> object: ''' When we add a parent (from Symbol), don't forget to resolve. ''' pass def use_translator(self, translator): ''' Attach a translator to an EvalCtx to convert output of the function into another type ''' pass def use_variadic_types(self, list_type: [TypeName]): ''' Attach a list of types for extra variadic argument of a call ''' pass def resolve(self): ''' Process the signature and find definition for type. ''' pass def get_resolved_names(self, type_name: TypeName) -> list: ''' Use self.resolution to subsitute type_name. Allow to instanciate polymorphic type ?1, ?toto ''' pass def set_resolved_name(self, ref: dict, type_name2solve: TypeName, type_name_ref: TypeName): ''' Warning!!! Need to rethink it when global poly type ''' pass
29
10
8
0
7
2
3
0.25
0
12
3
0
22
5
22
22
217
23
155
55
124
39
136
48
112
13
0
6
60
146,087
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/stream.py
pyrser.parsing.stream.Tag
class Tag: """Provide capture facilities""" def __init__(self, stream: str, begin: int, end=0): self._stream = stream self._begin = begin if end == 0: self._end = begin else: self._end = end def set_begin(self, begin: int): self._begin = begin def set_end(self, end: int): self._end = end def __str__(self) -> str: if self._begin == self._end: return "" return self._stream[self._begin:self._end] def __repr__(self) -> str: return "strid:%d %s:%s" % (id(self._stream), self._begin, self._end)
class Tag: '''Provide capture facilities''' def __init__(self, stream: str, begin: int, end=0): pass def set_begin(self, begin: int): pass def set_end(self, end: int): pass def __str__(self) -> str: pass def __repr__(self) -> str: pass
6
1
3
0
3
0
1
0.06
0
2
0
0
5
3
5
5
23
4
18
9
12
1
17
9
11
2
0
1
7
146,088
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/stream.py
pyrser.parsing.stream.Stream
class Stream: """Helps keep track of stream processing progress.""" def __init__(self, content: str=None, name: str=None): self._content = content self._len = len(content) self._name = name self._contexts = [] self._cursor = Cursor() # use to store begin:end => value self.value_cache = dict() def __len__(self) -> int: return self._len def __getitem__(self, key: int or slice) -> str: return self._content.__getitem__(key) @property def name(self) -> int: """Name of the stream.""" return self._name @property def eos_index(self) -> int: """End Of Stream index.""" return self._len @property def index(self) -> int: """The current position index.""" return self._cursor.position.index @property def lineno(self) -> int: """The current position line number.""" return self._cursor.lineno @property def col_offset(self) -> int: """The current position column offset.""" return self._cursor.col_offset @property def peek_char(self) -> str: """The current position character value.""" return self._content[self._cursor.index] @property def last_readed_line(self) -> str: """Usefull string to compute error message.""" mpos = self._cursor.max_readed_position mindex = mpos.index # search last \n prevline = mindex - 1 if mindex == self.eos_index else mindex while prevline >= 0 and self._content[prevline] != '\n': prevline -= 1 # search next \n nextline = mindex while nextline < self.eos_index and self._content[nextline] != '\n': nextline += 1 last_line = self._content[prevline + 1:nextline] return last_line def incpos(self, length: int=1) -> int: """Increment the cursor to the next character.""" if length < 0: raise ValueError("length must be positive") i = 0 while (i < length): if self._cursor.index < self._len: if self.peek_char == '\n': self._cursor.step_next_line() self._cursor.step_next_char() i += 1 return self._cursor.index def decpos(self, length: int=1) -> int: if length < 0: raise ValueError("length must be positive") if (self._cursor.index - length) < 0: raise ValueError("can't go before first byte") i = 0 while (i < length): if self.peek_char == '\n': self._cursor.step_prev_line() i += 1 else: self._cursor.step_prev_char() i += 1 return self._cursor.index def save_context(self) -> bool: """Save current position.""" self._contexts.append(self._cursor.position) return True def restore_context(self) -> bool: """Rollback to previous saved position.""" self._cursor.position = self._contexts.pop() return False def validate_context(self) -> bool: """Discard previous saved position.""" del self._contexts[-1] return True
class Stream: '''Helps keep track of stream processing progress.''' def __init__(self, content: str=None, name: str=None): pass def __len__(self) -> int: pass def __getitem__(self, key: int or slice) -> str: pass @property def name(self) -> int: '''Name of the stream.''' pass @property def eos_index(self) -> int: '''End Of Stream index.''' pass @property def index(self) -> int: '''The current position index.''' pass @property def lineno(self) -> int: '''The current position line number.''' pass @property def col_offset(self) -> int: '''The current position column offset.''' pass @property def peek_char(self) -> str: '''The current position character value.''' pass @property def last_readed_line(self) -> str: '''Usefull string to compute error message.''' pass def incpos(self, length: int=1) -> int: '''Increment the cursor to the next character.''' pass def decpos(self, length: int=1) -> int: pass def save_context(self) -> bool: '''Save current position.''' pass def restore_context(self) -> bool: '''Rollback to previous saved position.''' pass def validate_context(self) -> bool: '''Discard previous saved position.''' pass
23
12
5
0
5
1
2
0.2
0
7
1
0
15
6
15
15
105
14
76
36
53
15
68
29
52
5
0
3
26
146,089
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/stream.py
pyrser.parsing.stream.Cursor
class Cursor: """A mutable position in a Stream. It can be initialized or set from an immutable Position. """ def __init__(self, position: Position=Position(0, 1, 1)): self._maxindex = self._index = position.index self._maxcol = self._col_offset = position.col_offset self._maxline = self._lineno = position.lineno self._eol = [] @property def index(self) -> int: """The current index of the cursor.""" return self._index @property def lineno(self) -> int: """The current line number of the cursor.""" return self._lineno @property def col_offset(self) -> int: """The current column offset of the cursor.""" return self._col_offset @property def position(self) -> Position: """The current position of the cursor.""" return Position(self._index, self._lineno, self._col_offset) @position.setter def position(self, position: Position): self._index = position.index self._lineno = position.lineno self._col_offset = position.col_offset @property def max_readed_position(self) -> Position: """The index of the deepest character readed.""" return Position(self._maxindex, self._maxline, self._maxcol) def step_next_char(self): """Puts the cursor on the next character.""" self._index += 1 self._col_offset += 1 if self._index > self._maxindex: self._maxindex = self._index self._maxcol = self._col_offset self._maxline = self._lineno def step_prev_char(self): """Puts the cursor on the previous character.""" self._col_offset -= 1 self._index -= 1 def step_next_line(self): """Sets cursor as beginning of next line.""" self._eol.append(self.position) self._lineno += 1 self._col_offset = 0 def step_prev_line(self): """Sets cursor as end of previous line.""" #TODO(bps): raise explicit error for unregistered eol #assert self._eol[-1].index == self._index if len(self._eol) > 0: self.position = self._eol.pop()
class Cursor: '''A mutable position in a Stream. It can be initialized or set from an immutable Position. ''' def __init__(self, position: Position=Position(0, 1, 1)): pass @property def index(self) -> int: '''The current index of the cursor.''' pass @property def lineno(self) -> int: '''The current line number of the cursor.''' pass @property def col_offset(self) -> int: '''The current column offset of the cursor.''' pass @property def position(self) -> Position: '''The current position of the cursor.''' pass @position.setter def position(self) -> Position: pass @property def max_readed_position(self) -> Position: '''The index of the deepest character readed.''' pass def step_next_char(self): '''Puts the cursor on the next character.''' pass def step_prev_char(self): '''Puts the cursor on the previous character.''' pass def step_next_line(self): '''Sets cursor as beginning of next line.''' pass def step_prev_line(self): '''Sets cursor as end of previous line.''' pass
18
10
4
0
3
1
1
0.33
0
1
0
0
11
7
11
11
68
11
43
22
25
14
37
16
25
2
0
1
13
146,090
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/node.py
pyrser.parsing.node.TupleNode
class TupleNode(list): pass
class TupleNode(list): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
33
2
0
2
1
1
0
2
1
1
0
2
0
0
146,091
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/node.py
pyrser.parsing.node.Node
class Node(dict): """Base class for node manipulation.""" def __bool__(self): return True def __repr__(self): #TODO: use to_yml items = [] if len(self) > 0: items.append(repr(self.items())) for k, v in vars(self).items(): items.append("{} = {}".format(k, repr(v))) return "{}({})".format(self.__class__.__name__, ', '.join(items)) def check(self, ndict: dict, info="") -> bool: """ Debug method, help detect cycle and/or other incoherence in a tree of Node """ def iscycle(thing, ndict: dict, info: str) -> bool: # check if not already here idthing = id(thing) ndict[info] = idthing if idthing not in ndict: # add myself ndict[idthing] = "%s:%s no cycle" % (type(thing), info) return False else: ndict[idthing] += "\n%s:%s cycle" % (type(thing), info) return True def recurs(thing, ndict: dict, info: str) -> bool: if not iscycle(thing, ndict, info): res = False if isinstance(thing, list): idx = 0 for i in thing: res |= recurs(i, ndict, "%s[%d]" % (info, idx)) idx += 1 elif isinstance(thing, Node): res |= thing.check(ndict, info) elif isinstance(thing, dict): for k, v in thing.items(): res |= recurs(v, ndict, "%s[%s]" % (info, k)) return res return True # add ME FIRST if len(ndict) == 0: ndict['self'] = id(self) info = 'self' if not iscycle(self, ndict, info): res = False if len(self) > 0: if hasattr(self, 'keys'): keys = list(self.keys()) for k in keys: ndict["[" + repr(k) + "]"] = id(self[k]) res |= recurs(self[k], ndict, "%s[%s]" % (info, k)) keys = list(vars(self).keys()) for k in keys: ndict["." + k] = id(getattr(self, k)) res |= recurs(getattr(self, k), ndict, "%s.%s" % (info, k)) return res return True def clean(self): if len(self) > 0: keys = list(self.keys()) for k in keys: del self[k] keys = list(vars(self).keys()) for k in keys: delattr(self, k) def set(self, othernode): """allow to completly mutate the node into any subclasses of Node""" self.__class__ = othernode.__class__ self.clean() if len(othernode) > 0: for k, v in othernode.items(): self[k] = v for k, v in vars(othernode).items(): setattr(self, k, v)
class Node(dict): '''Base class for node manipulation.''' def __bool__(self): pass def __repr__(self): pass def check(self, ndict: dict, info="") -> bool: ''' Debug method, help detect cycle and/or other incoherence in a tree of Node ''' pass def iscycle(thing, ndict: dict, info: str) -> bool: pass def recurs(thing, ndict: dict, info: str) -> bool: pass def clean(self): pass def set(self, othernode): '''allow to completly mutate the node into any subclasses of Node''' pass
8
3
15
0
13
2
4
0.15
1
4
0
2
5
1
5
32
84
6
68
22
60
10
65
22
57
7
2
4
28
146,092
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/node.py
pyrser.parsing.node.ListNodeItemIterator
class ListNodeItemIterator: pass
class ListNodeItemIterator: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
1
1
0
2
1
1
0
0
0
0
146,093
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/node.py
pyrser.parsing.node.ListNodeItemIterator
class ListNodeItemIterator: pass
class ListNodeItemIterator: pass
1
0
4
0
4
0
2
0
0
2
1
0
3
2
3
3
16
2
14
7
10
0
14
7
10
2
0
1
5
146,094
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/node.py
pyrser.parsing.node.ListNodeItem
class ListNodeItem: pass
class ListNodeItem: pass
1
0
8
0
7
1
3
0.1
0
8
2
0
17
4
17
17
152
16
124
40
106
12
124
40
106
6
0
2
44
146,095
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/ast/match.py
match.MatchHook
class MatchHook(MatchExpr): """ Ast Node for a Resulting Hook. """ def __init__(self, call: callable, v: MatchValue): if not callable(call): raise ValueError("argument 'call' must be callable") self.call = call self.n = call.__name__ self.v = v def __eq__(self, other) -> bool: return id(self.call) == id(other.call) def attach( self, s1: state.State, s2: state.State, sr: state.StateRegister ): s1.matchHook(self.call, s2) def build_state_tree(self, tree: list): # go deeper self.v.build_state_tree(tree) # add ourself tree.append(self) def to_fmt(self) -> fmt.indentable: res = fmt.sep(' -> ', [self.v.to_fmt(), '#' + self.n + ';']) return res def __repr__(self) -> str: return str(self.to_fmt())
class MatchHook(MatchExpr): ''' Ast Node for a Resulting Hook. ''' def __init__(self, call: callable, v: MatchValue): pass def __eq__(self, other) -> bool: pass def attach( self, s1: state.State, s2: state.State, sr: state.StateRegister ): pass def build_state_tree(self, tree: list): pass def to_fmt(self) -> fmt.indentable: pass def __repr__(self) -> str: pass
7
1
4
0
4
1
1
0.25
1
9
5
0
6
3
6
6
34
5
24
16
12
6
19
11
12
2
1
1
7
146,096
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/ast/match.py
match.MatchExpr
class MatchExpr: """ Ast Node for all match expression. """ pass
class MatchExpr: ''' Ast Node for all match expression. ''' pass
1
1
0
0
0
0
0
1.5
0
0
0
9
0
0
0
0
5
0
2
1
1
3
2
1
1
0
0
0
0
146,097
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/ast/state.py
state.EventAlt
class EventAlt(EventExpr): """ Ast Node for a alternative predicate expression. """ def __init__(self, alt: list): self.alt = alt def checkEvent(self, sr: StateRegister, collect: dict) -> bool: res = False for a in self.alt: b = a.checkEvent(sr, collect) res |= b return res def clean(self, sr: StateRegister, updown: bool) -> bool: for a in self.alt: a.clean(sr, updown) def to_fmt(self) -> fmt.indentable: res = fmt.sep(' | ', []) for a in self.alt: res.lsdata.append(a.to_fmt()) return res def __repr__(self) -> str: return str(self.to_fmt())
class EventAlt(EventExpr): ''' Ast Node for a alternative predicate expression. ''' def __init__(self, alt: list): pass def checkEvent(self, sr: StateRegister, collect: dict) -> bool: pass def clean(self, sr: StateRegister, updown: bool) -> bool: pass def to_fmt(self) -> fmt.indentable: pass def __repr__(self) -> str: pass
6
1
4
0
4
0
2
0.16
1
7
3
0
5
1
5
7
26
4
19
13
13
3
19
13
13
2
1
1
8
146,098
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/ast/match.py
match.MatchEvent
class MatchEvent(MatchExpr): """ Ast Node for a Resulting Event. """ def __init__(self, n: str, v: MatchValue): self.n = n self.v = v def __eq__(self, other) -> bool: return self.n == other.n def attach( self, s1: state.State, s2: state.State, sr: state.StateRegister ): # TODO:!!! the event must be store in the LivingState s1.matchEvent(self.n, s2) def build_state_tree(self, tree: list): # go deeper self.v.build_state_tree(tree) # add ourself tree.append(self) def to_fmt(self) -> fmt.indentable: res = fmt.sep(' -> ', [self.v.to_fmt(), self.n + ';']) return res def __repr__(self) -> str: return str(self.to_fmt())
class MatchEvent(MatchExpr): ''' Ast Node for a Resulting Event. ''' def __init__(self, n: str, v: MatchValue): pass def __eq__(self, other) -> bool: pass def attach( self, s1: state.State, s2: state.State, sr: state.StateRegister ): pass def build_state_tree(self, tree: list): pass def to_fmt(self) -> fmt.indentable: pass def __repr__(self) -> str: pass
7
1
4
0
3
1
1
0.29
1
8
5
0
6
2
6
6
32
5
21
15
9
6
16
10
9
1
1
0
6
146,099
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.Leaf
class Leaf: pass
class Leaf: pass
1
0
0
0
0
0
0
0
0
0
0
8
0
0
0
0
2
0
2
1
1
0
2
1
1
0
0
0
0
146,100
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/ast/state.py
state.EventNot
class EventNot(EventExpr): """ Ast Node for a not predicate expression. """ def __init__(self, subexpr: EventExpr): self.subexpr = subexpr def checkEvent(self, sr: StateRegister, collect: dict) -> bool: c2 = {} r = not self.subexpr.checkEvent(sr, c2) return r def clean(self, sr: StateRegister, updown: bool) -> bool: self.subexpr.clean(sr, not updown) def to_fmt(self) -> fmt.indentable: res = fmt.block('!', '', [self.subexpr.to_fmt()]) return res def __repr__(self) -> str: return str(self.to_fmt())
class EventNot(EventExpr): ''' Ast Node for a not predicate expression. ''' def __init__(self, subexpr: EventExpr): pass def checkEvent(self, sr: StateRegister, collect: dict) -> bool: pass def clean(self, sr: StateRegister, updown: bool) -> bool: pass def to_fmt(self) -> fmt.indentable: pass def __repr__(self) -> str: pass
6
1
3
0
3
0
1
0.21
1
6
3
0
5
1
5
7
21
4
14
10
8
3
14
10
8
1
1
0
5
146,101
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/ast/state.py
state.EventParen
class EventParen(EventExpr): """ Ast Node for a parenthesis predicate expression. """ def __init__(self, subexpr: EventExpr): self.subexpr = subexpr def checkEvent(self, sr: StateRegister, collect: dict) -> bool: return self.subexpr.checkEvent(sr, collect) def clean(self, sr: StateRegister, updown: bool) -> bool: self.subexpr.clean(sr, updown) def to_fmt(self) -> fmt.indentable: res = fmt.block('(', ')', [self.subexpr.to_fmt()]) return res def __repr__(self) -> str: return str(self.to_fmt())
class EventParen(EventExpr): ''' Ast Node for a parenthesis predicate expression. ''' def __init__(self, subexpr: EventExpr): pass def checkEvent(self, sr: StateRegister, collect: dict) -> bool: pass def clean(self, sr: StateRegister, updown: bool) -> bool: pass def to_fmt(self) -> fmt.indentable: pass def __repr__(self) -> str: pass
6
1
2
0
2
0
1
0.25
1
6
3
0
5
1
5
7
19
4
12
8
6
3
12
8
6
1
1
0
5
146,102
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/ast/state.py
state.EventSeq
class EventSeq(EventExpr): """ Ast Node for a sequence predicate expression. """ def __init__(self, seq: list): self.seq = seq def checkEvent(self, sr: StateRegister, collect: dict) -> bool: res = True for s in self.seq: b = s.checkEvent(sr, collect) res &= b return res def clean(self, sr: StateRegister, updown: bool) -> bool: for s in self.seq: s.clean(sr, updown) def to_fmt(self) -> fmt.indentable: res = fmt.sep(' & ', []) for s in self.seq: res.lsdata.append(s.to_fmt()) return res def __repr__(self) -> str: return str(self.to_fmt())
class EventSeq(EventExpr): ''' Ast Node for a sequence predicate expression. ''' def __init__(self, seq: list): pass def checkEvent(self, sr: StateRegister, collect: dict) -> bool: pass def clean(self, sr: StateRegister, updown: bool) -> bool: pass def to_fmt(self) -> fmt.indentable: pass def __repr__(self) -> str: pass
6
1
4
0
4
0
2
0.16
1
7
3
0
5
1
5
7
26
4
19
13
13
3
19
13
13
2
1
1
8
146,103
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.Rule
class Rule(Functor, Leaf): """ Call a rule by its name. """ def __init__(self, name: str): Functor.__init__(self) self.name = name def do_call(self, parser: BasicParser) -> Node: parser.push_rule_nodes() res = parser.eval_rule(self.name) parser.pop_rule_nodes() return res
class Rule(Functor, Leaf): ''' Call a rule by its name. ''' def __init__(self, name: str): pass def do_call(self, parser: BasicParser) -> Node: pass
3
1
4
0
4
0
1
0.11
2
3
2
0
2
1
2
4
12
2
9
5
6
1
9
5
6
1
1
0
2
146,104
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.Scope
class Scope(Functor): """ functor to wrap SCOPE/rule directive or just []. """ def __init__(self, begin: Seq, end: Seq, pt: Seq): Functor.__init__(self) self.begin = begin self.end = end self.pt = pt def do_call(self, parser: BasicParser) -> Node: if not self.begin(parser): return False res = self.pt(parser) if not self.end(parser): return False return res
class Scope(Functor): ''' functor to wrap SCOPE/rule directive or just []. ''' def __init__(self, begin: Seq, end: Seq, pt: Seq): pass def do_call(self, parser: BasicParser) -> Node: pass
3
1
6
0
6
0
2
0.08
1
3
3
0
2
3
2
4
16
2
13
7
10
1
13
7
10
3
1
1
4
146,105
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.Seq
class Seq(Functor): """ A B C bnf primitive as a functor. """ def __init__(self, *ptlist: Functor): Functor.__init__(self) if len(ptlist) == 0: raise TypeError("Expected Functor") self.ptlist = [] for it in ptlist: if not isinstance(it, SkipIgnore): self.ptlist.append(it) self.ptlist.append(SkipIgnore()) if not isinstance(self.ptlist[0], SkipIgnore): self.ptlist.insert(0, SkipIgnore()) def __getitem__(self, idx) -> Functor: """ Hide SkipIgnore object from outside """ if idx >= 0: idx = (idx * 2) + 1 else: idx = len(self.ptlist) - ((idx + 1) * 2) - 2 return self.ptlist[idx] def do_call(self, parser: BasicParser) -> bool: parser._stream.save_context() for pt in self.ptlist: if not pt(parser): return parser._stream.restore_context() return parser._stream.validate_context()
class Seq(Functor): ''' A B C bnf primitive as a functor. ''' def __init__(self, *ptlist: Functor): pass def __getitem__(self, idx) -> Functor: ''' Hide SkipIgnore object from outside ''' pass def do_call(self, parser: BasicParser) -> bool: pass
4
2
8
0
8
0
3
0.08
1
4
2
0
3
1
3
5
29
3
24
7
20
2
23
7
19
5
1
2
10
146,106
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/ast/match.py
match.MatchAttr
class MatchAttr(MatchExpr): """ Ast Node for matching one attribute. """ def __init__(self, name: str=None, v=None): self.name = name if v is None: v = MatchValue() self.v = v def __eq__(self, other) -> bool: return self.name == other.name def is_in_state(self, s: state.State): if self.name in s.attrs: return s.attrs[self.name] return None def attach( self, s1: state.State, s2: state.State, sr: state.StateRegister ): if self.name is not None: s1.matchAttr(self.name, s2) else: s1.matchDefault(s2) def build_state_tree(self, tree: list): # go deeper self.v.build_state_tree(tree) #TODO: match all attr # add ourself tree.append(self) return tree def to_fmt(self) -> fmt.indentable: n = '*' if self.name is not None: n = self.name n = '.' + n v = '*' if self.v is not None: v = self.v.to_fmt() res = fmt.sep('=', [n, v]) return res def __repr__(self) -> str: return str(self.to_fmt())
class MatchAttr(MatchExpr): ''' Ast Node for matching one attribute. ''' def __init__(self, name: str=None, v=None): pass def __eq__(self, other) -> bool: pass def is_in_state(self, s: state.State): pass def attach( self, s1: state.State, s2: state.State, sr: state.StateRegister ): pass def build_state_tree(self, tree: list): pass def to_fmt(self) -> fmt.indentable: pass def __repr__(self) -> str: pass
8
1
6
0
5
0
2
0.16
1
8
5
0
7
2
7
7
50
6
38
18
25
6
32
13
24
3
1
1
12
146,107
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/grammar_directive.py
tests.grammar_directive.IgnoreCPP
class IgnoreCPP(grammar.Grammar): grammar = """ root =[ @ignore("C/C++") [ #init(_) [ word:w #add_to(_, w) ]* eof ] ] word = [ @ignore("null") ['a'..'z'|'A'..'Z']+ ] """ entry = "root"
class IgnoreCPP(grammar.Grammar): pass
1
0
0
0
0
0
0
0.17
1
0
0
0
0
0
0
0
7
1
6
2
5
1
3
2
2
0
1
0
0
146,108
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/grammar_directive.py
tests.grammar_directive.IgnoreNull
class IgnoreNull(grammar.Grammar): grammar = """ root =[ @ignore("null") [ item : i #add_to(_, i) ]+ eof ] item = [ ' ' | 'a'..'z' | 'A'..'Z' | '\n' | '\t' | '\v' | '.' ] """ entry = "root"
class IgnoreNull(grammar.Grammar): pass
1
0
0
0
0
0
0
0.17
1
0
0
0
0
0
0
0
7
1
6
2
5
1
3
2
2
0
1
0
0
146,109
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/grammar_type.py
tests.grammar_type.GrammarType_Test
class GrammarType_Test(unittest.TestCase): def test_01_typeliteral(self): # fun call test = TL4T() res = test.parse(""" a(42); """) txt = res.to_tl4t() self.assertEqual(str(txt), "a(42);\n") # TODO: could be mask the attribute infer_node # and just provide a scope to infer_type method scope = Scope( sig=Fun('a', 'void', ['int']), is_namespace=False ) scope.add(Type("void")) scope.add(Type("int")) res.infer_type(scope) print("!!![[%s]]" % res.to_yml()) self.assertFalse(res.diagnostic.have_errors, "Bad inference") #self.assertEqual( # str(res.body[0].infer_node.scope_node.first().get_compute_sig()), # "fun a : (int) -> void", # "Bad computing of signature" #) ## expr #test = TL4T() #res = test.parse(""" # var a = 42; #""") #txt = res.to_tl4t() #self.assertEqual(str(txt), "var a = 42;\n") #scope = Scope(sig=Type('int')) #res.infer_type(scope) #self.assertFalse(res.diagnostic.have_errors, "Bad inference") ##print(to_yml(res.body[0].type_node)) ##print(res.diagnostic) ##print(res.body[0].type_node) ## funcvariadic complex #test = TL4T() #res = test.parse(""" # printf("tutu %d", 42, a); #""") #txt = res.to_tl4t() #self.assertEqual(str(txt), 'printf("tutu %d", 42, a);\n') #scope = Scope( # sig=Fun('printf', 'void', ['string'], variadic=True) #) #scope.add(Type("void")) #scope.add(Type("string")) #scope.add(Type("int")) #scope.add(Var("a", "int")) ## TODO: on veut aussi la liste de type reel des types variadiques #res.infer_type(scope) #self.assertFalse(res.diagnostic.have_errors, "Bad inference") #self.assertEqual( # str(res.body[0].type_node.first().get_compute_sig()), # "fun printf : (string, int, int) -> void", # "Bad computing of signature" #) ## funcvariadic simple #test = TL4T() #res = test.parse(r""" # printf("cool\n"); #""") #txt = res.to_tl4t() #self.assertEqual(str(txt), 'printf("cool\\n");\n') #scope = Scope( # sig=Fun('printf', 'void', ['string'], variadic=True) #) #scope.add(Type("void")) #scope.add(Type("string")) ## TODO: on veut aussi la liste de type reel des types variadiques #res.infer_type(scope) #self.assertFalse(res.diagnostic.have_errors, "Bad inference") #self.assertEqual( # str(res.body[0].type_node.first().get_compute_sig()), # "fun printf : (string) -> void", # "Bad computing of signature" #) ## Automatically add a translation #test = TL4T() #res = test.parse(""" # s = "toto" + 42; #""") #txt = str(res.to_tl4t()) #self.assertEqual(txt, 's = "toto" + 42;\n') #scope = Scope(is_namespace=False) #scope.add(Type("string")) #scope.add(Type("int")) #scope.add(Var("s", "string")) #scope.add(Fun("=", "string", ["string", "string"])) #scope.add(Fun("+", "string", ["string", "string"])) #f = Fun("to_str", "string", ["int"]) #scope.add(f) #n = Notification( # Severity.WARNING, # "implicit conversion of int to string" #) #scope.addTranslator(Translator(f, n)) #scope.addTranslatorInjector(createFunWithTranslator) #res.infer_type(scope) #self.assertFalse(res.diagnostic.have_errors, "Bad inference") #self.assertEqual( # str(res.to_tl4t()), # 's = "toto" + to_str(42);\n', # "Bad pretty print" #) ## poly-poly ##test = TL4T() ##res = test.parse(""" ## f(a); ##""") ##txt = str(res.to_tl4t()) ##self.assertEqual(txt, 'f(a);\n') ##res.type_node = Scope(is_namespace=False) ##res.type_node.add(Type("?a")) ##res.type_node.add(Var("a", "?a")) ##res.type_node.add(Fun("f", "?", ["?"])) ##res.infer_type(res.diagnostic) ##print(res.diagnostic.get_content()) ##self.assertFalse(res.diagnostic.have_errors, "Bad inference") def test_02_typerror(self): test = TL4T() res = test.parse(""" a(42); """) scope = Scope(sig=Fun('a', 'void', ['char'])) res.infer_type(scope) self.assertTrue(res.diagnostic.have_errors, "Bad error detection") # Automatically add a translation test = TL4T() res = test.parse(""" s = "toto" + 42; """) txt = str(res.to_tl4t()) self.assertEqual(txt, 's = "toto" + 42;\n') scope = Scope(is_namespace=False) scope.add(Type("string")) scope.add(Type("int")) scope.add(Var("s", "string")) scope.add(Fun("=", "string", ["string", "string"])) scope.add(Fun("+", "string", ["string", "string"])) f = Fun("to_str", "string", ["int"]) scope.add(f) n = Notification( Severity.ERROR, "implicit conversion of int to string" ) scope.addTranslator(Translator(f, n)) scope.addTranslatorInjector(createFunWithTranslator) res.infer_type(scope) self.assertTrue(res.diagnostic.have_errors, "Bad inference") self.assertEqual(res.diagnostic.get_infos()[Severity.ERROR], 1)
class GrammarType_Test(unittest.TestCase): def test_01_typeliteral(self): pass def test_02_typerror(self): pass
3
0
26
0
24
2
1
2.21
1
3
2
0
2
0
2
74
155
1
48
13
45
106
36
13
33
1
2
0
2
146,110
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/hooks.py
tests.hooks.Hooks_Test
class Hooks_Test(unittest.TestCase): def test_01(self): class parserExample(grammar.Grammar): entry = "Example" grammar = """ Example = [ id eof #setint(_, 12) ] """ Ex = parserExample() res = Ex.parse("someExample") self.assertEqual(res.value, 12, "Can't set .value in the node to 12") class parserExample2(grammar.Grammar): entry = "Example" grammar = """ Example = [ id eof #setstr(_, 'toto') ] """ Ex = parserExample2() res = Ex.parse("someExample") self.assertEqual(res.value, 'toto', "Can't set .value in the node to 'toto'") class parserExample3(grammar.Grammar): entry = "Example" grammar = """ Example = [ id:i eof #setcapture(_, i) ] """ Ex = parserExample3() res = Ex.parse("someExample") self.assertEqual(res.value, 'someExample', "Can't set .value in the node to value of node 'i'")
class Hooks_Test(unittest.TestCase): def test_01(self): pass class parserExample(grammar.Grammar): class parserExample2(grammar.Grammar): class parserExample3(grammar.Grammar):
5
0
31
3
28
3
1
0.1
1
3
3
0
1
0
1
73
32
3
29
10
24
3
20
10
15
1
2
0
1
146,111
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/internal_ast.py
tests.internal_ast.H
class H(dict): def __repr__(self) -> str: return dict.__repr__(self) + " - " + str(vars(self))
class H(dict): def __repr__(self) -> str: pass
2
0
2
0
2
0
1
0
1
1
0
0
1
0
1
28
3
0
3
2
1
0
3
2
1
1
2
0
1
146,112
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/internal_ast.py
tests.internal_ast.InternalAst_Test
class InternalAst_Test(unittest.TestCase): def test_000(self): """ListNode tests""" # ListNodeItem l = ListNodeItem("a") self.assertEqual(l.prev, None, "Bad construction of l") self.assertEqual(l.next, None, "Bad construction of l") l.append("b") self.assertEqual(l.prev, None, "Bad construction of l") self.assertNotEqual(l.next, None, "Bad construction of l") self.assertEqual(id(l.next.prev), id(l), "Bad construction of l") self.assertEqual(l.next.next, None, "Bad construction of l") thelist = l.thelist() self.assertEqual(len(thelist), 2, "Bad construction of l") self.assertEqual(thelist.must_update, False, "Bad construction of l") self.assertEqual(id(thelist.begin), id(l), "Bad construction of l") self.assertEqual(id(thelist.begin), id(l.next.prev), "Bad construction of l") self.assertEqual(id(thelist.end), id(l.next), "Bad construction of l") self.assertEqual(thelist.begin.data, 'a', "Bad construction of l") self.assertEqual(thelist.end.data, 'b', "Bad construction of l") l.append("c") self.assertEqual(thelist.must_update, True, "Bad construction of l") self.assertEqual(len(thelist), 3, "Bad construction of l") self.assertEqual(thelist.must_update, False, "Bad construction of l") self.assertEqual(thelist.begin.data, 'a', "Bad construction of l") self.assertEqual(thelist.end.data, 'b', "Bad construction of l") self.assertEqual(thelist.begin.next.data, 'c', "Bad construction of l") self.assertEqual(thelist.end.prev.data, 'c', "Bad construction of l") self.assertEqual(l[0], 'a', "Bad construction of l") self.assertEqual(l[1], 'c', "Bad construction of l") self.assertEqual(l[2], 'b', "Bad construction of l") l.thelist().append('g') self.assertEqual(l[3], 'g', "Bad construction of l") self.assertEqual(l[-1], 'g', "Bad construction of l") self.assertEqual(l[-2], 'b', "Bad construction of l") self.assertEqual(l[-3], 'c', "Bad construction of l") self.assertEqual(l[-4], 'a', "Bad construction of l") with self.assertRaises(IndexError): l[-5] = 'g' subelm = [] for it in l._fwd(): subelm.append(it.data) self.assertEqual(subelm, ['a', 'c', 'b', 'g'], "Bad construction of l") subelm = [] for it in l.values(): subelm.append(it) self.assertEqual(subelm, ['a', 'c', 'b', 'g'], "Bad construction of l") subelm = [] end = l.next.next for it in end._bwd(): subelm.append(it.data) self.assertEqual(subelm, ['b', 'c', 'a'], "Bad construction of l") subelm = [] end = l.next.next for it in end.rvalues(): subelm.append(it) self.assertEqual(subelm, ['b', 'c', 'a'], "Bad construction of l") l = ListNodeItem("a") l.prepend("b") self.assertEqual(l.next, None, "Bad construction of l") self.assertNotEqual(l.prev, None, "Bad construction of l") self.assertEqual(id(l.prev.next), id(l), "Bad construction of l") self.assertEqual(l.prev.prev, None, "Bad construction of l") thelist = l.thelist() self.assertEqual(len(thelist), 2, "Bad construction of l") self.assertEqual(thelist.must_update, False, "Bad construction of l") self.assertEqual(id(thelist.end), id(l), "Bad construction of l") self.assertEqual(id(thelist.end), id(l.prev.next), "Bad construction of l") self.assertEqual(id(thelist.begin), id(l.prev), "Bad construction of l") self.assertEqual(thelist.begin.data, 'b', "Bad construction of l") self.assertEqual(thelist.end.data, 'a', "Bad construction of l") l.prepend("c") self.assertEqual(thelist.must_update, True, "Bad construction of l") self.assertEqual(len(thelist), 3, "Bad construction of l") self.assertEqual(thelist.must_update, False, "Bad construction of l") self.assertEqual(thelist.begin.data, 'b', "Bad construction of l") self.assertEqual(thelist.end.data, 'a', "Bad construction of l") self.assertEqual(thelist.begin.next.data, 'c', "Bad construction of l") self.assertEqual(thelist.end.prev.data, 'c', "Bad construction of l") self.assertEqual(l[0], 'b', "Bad construction of l") self.assertEqual(l[-1], 'a', "Bad construction of l") self.assertEqual(l[-2], 'c', "Bad construction of l") subelm = [] for it in l._bwd(): subelm.append(it.data) self.assertEqual(subelm, ['a', 'c', 'b'], "Bad construction of l") subelm = [] for it in l.rvalues(): subelm.append(it) self.assertEqual(subelm, ['a', 'c', 'b'], "Bad construction of l") subelm = [] begin = l.prev.prev for it in begin._fwd(): subelm.append(it.data) self.assertEqual(subelm, ['b', 'c', 'a'], "Bad construction of l") subelm = [] begin = l.prev.prev for it in begin.values(): subelm.append(it) self.assertEqual(subelm, ['b', 'c', 'a'], "Bad construction of l") lbegin = ListNodeItem('a') l = lbegin l = l.append('b') l = l.append('c') l = l.append('d') l = l.append('e') l = l.append('f') idx = 0 for it in lbegin._fwd(): if idx == 2: it.popitem() idx += 1 self.assertEqual(lbegin.thelist(), ['a', 'b', 'd', 'e', 'f'], "Bad construction of l") self.assertEqual(l.thelist().must_update, False, "Bad construction of l") lbegin = ListNodeItem('a') l = lbegin l = l.append('b') l = l.append('c') l = l.append('d') l = l.append('e') l = l.append('f') del lbegin[2] self.assertEqual(str(lbegin.thelist()), "['a', 'b', 'd', 'e', 'f']", "Bad construction of l") self.assertEqual(l.thelist().must_update, True, "Bad construction of l") # ListNode ls = ListNode() ls.append('a') self.assertEqual(ls.begin.data, 'a', "Bad construction of ls") self.assertEqual(ls.end.data, 'a', "Bad construction of ls") ls.append('b') self.assertEqual(ls.begin.data, 'a', "Bad construction of ls") self.assertEqual(ls.end.data, 'b', "Bad construction of ls") ls.append('c') self.assertEqual(ls.begin.data, 'a', "Bad construction of ls") self.assertEqual(ls.begin.next.data, 'b', "Bad construction of ls") self.assertEqual(ls.end.prev.data, 'b', "Bad construction of ls") self.assertEqual(ls.end.data, 'c', "Bad construction of ls") self.assertEqual(ls.must_update, True, "Bad construction of ls") self.assertEqual(len(ls), 3, "Bad construction of ls") self.assertEqual(ls.must_update, False, "Bad construction of ls") self.assertEqual(len(ls.cache), 3, "Bad construction of ls") self.assertEqual(ls[0], 'a', "Bad construction of ls") self.assertEqual(ls[1], 'b', "Bad construction of ls") self.assertEqual(ls[2], 'c', "Bad construction of ls") ls = ListNode() ls.prepend('c') self.assertEqual(ls.must_update, True, "Bad construction of ls") self.assertNotEqual(ls.begin, None, "Bad construction of ls") self.assertNotEqual(ls.end, None, "Bad construction of ls") ls.prepend('b') ls.prepend('a') self.assertEqual(len(ls), 3, "Bad construction of ls") self.assertEqual(ls.must_update, False, "Bad construction of ls") self.assertEqual(ls[0], 'a', "Bad construction of ls") self.assertEqual(ls.must_update, False, "Bad construction of ls") ls.append('d') self.assertEqual(len(ls), 4, "Bad construction of ls") self.assertEqual(ls[1], 'b', "Bad construction of ls") self.assertEqual(ls[2], 'c', "Bad construction of ls") self.assertEqual(ls[3], 'd', "Bad construction of ls") # ListNode vs list ls = ListNode([1, 2, 3, 4, 5, 6]) self.assertEqual(len(ls), 6, "Bad construction of ls") ls2 = list(ls) self.assertEqual(ls2, [1, 2, 3, 4, 5, 6], "Bad construction of ls") ls3 = list(reversed(ls)) self.assertEqual(ls3, [6, 5, 4, 3, 2, 1], "Bad construction of ls") node = ls.get(3) self.assertEqual(node.data, 4, "Bad construction of ls") self.assertEqual(node.next.data, 5, "Bad construction of ls") self.assertEqual(node.prev.data, 3, "Bad construction of ls") # slice s1 = ls[4:] self.assertEqual(s1, [1, 2, 3, 4, 5, 6][4:], "Bad slice of ls") # del del ls[3] self.assertEqual(ls[3], 5, "Bad construction of ls") self.assertEqual(id(ls.get(3).prev), id(ls.get(2)), "Bad construction of ls") self.assertEqual(id(ls.get(3).next), id(ls.get(4)), "Bad construction of ls") self.assertEqual(id(ls.get(2).next), id(ls.get(3)), "Bad construction of ls") self.assertEqual(id(ls.get(4).prev), id(ls.get(3)), "Bad construction of ls") sz = len(ls) - 1 del ls[sz] sz -= 1 self.assertEqual(ls[sz], 5, "Bad construction of ls") self.assertEqual(id(ls.get(sz).next), id(None), "Bad construction of ls") def test_00(self): """Basic test on state creation""" nsr = StateRegister() s0 = State(nsr) s1 = State(nsr) self.assertIn(s0, nsr, "Failed State %d in StateRegister" % id(s0)) self.assertIn(s1, nsr, "Failed State %d in StateRegister" % id(s1)) # attr, indice, key, value, type, default s0.matchAttr('a', s1) self.assertEqual(id(s1), id(s0.checkAttr('a')), "Failed to return correct state") s0.matchIndice(1, s1) self.assertEqual(id(s1), id(s0.checkIndice(1)), "Failed to return correct state") s0.matchKey('tutu', s1) self.assertEqual(id(s1), id(s0.checkKey('tutu')), "Failed to return correct state") s0.matchValue('tutu', s1) self.assertEqual(id(s1), id(s0.checkValue('tutu')), "Failed to return correct state") s0.matchType(int, s1) self.assertEqual(id(s1), id(s0.checkType(int)), "Failed to return correct state") s0.matchDefault(s1) self.assertEqual(id(s1), id(s0.doDefault()), "Failed to return correct state") # Event s0.matchEvent('lolo', s1) self.assertEqual(id(s1), id(s0.doResultEvent()), "Failed to return correct state") # Hook def dummy(nodes, user_data): pass s0.matchHook(dummy, s1) sh = s0.default_hook self.assertTrue(type(sh) is StateHook, "Failed to return correct state") self.assertEqual(id(s1), id(s0.doResultHook()), "Failed to return correct state") def test_01(self): """Event Expr event""" nsr = StateRegister() s0 = State(nsr) s1 = State(nsr) s2 = State(nsr) # set one event s1.matchEvent('lolo', s0) self.assertIn('lolo', nsr.named_events, "Failed to set an event") sX = s1.doResultEvent() self.assertEqual(id(s0), id(sX), "Failed to init the event for the test") # check if is set e = EventNamed('lolo') s2 = State(nsr) s0.matchEventExpr(e, s2, False) self.assertEqual(id(s2), id(s0.checkEventExpr()), "Failed to return correct state") # ?? ( ... ) is the syntax for none cleaning event expression #?? ( lala & lulu ) s0.cleanAll() s3 = State(nsr) s3.matchEvent('lala', s0) s3.doResultEvent() e = EventSeq([EventNamed('lala'), EventNamed('lulu')]) s0.matchEventExpr(e, s2, False) sX = s0.checkEventExpr() self.assertTrue(id(s2) != id(sX), "Failed to return correct state") s4 = State(nsr) s4.matchEvent('lulu', s0) s4.doResultEvent() self.assertTrue(id(s2) == id(s0.checkEventExpr()), "Failed to return correct state") #?? ( lala & !lulu ) s0.events_expr = list() s0.cleanAll() s3.matchEvent('lala', s0) s3.doResultEvent() s4.matchEvent('lulu', s0) s4.doResultEvent() e = EventSeq([EventNamed('lala'), EventNot(EventNamed('lulu'))]) s0.matchEventExpr(e, s2, False) sX = s0.checkEventExpr() self.assertTrue(id(s2) != id(sX), "Failed to return correct state") s0.cleanAll() s3.matchEvent('lala', s0) s3.doResultEvent() sX = s0.checkEventExpr() self.assertTrue(id(s2) == id(sX), "Failed to return correct state") #?? ( lala | lulu ) s0.events_expr = list() s0.cleanAll() s4.matchEvent('lulu', s0) s4.doResultEvent() e = EventAlt([EventNamed('lala'), EventNamed('lulu')]) s0.matchEventExpr(e, s2, False) sX = s0.checkEventExpr() self.assertTrue(id(s2) == id(sX), "Failed to return correct state") #?? ( lala & ( lolo | lulu) ) s0.events_expr = list() nsr.cleanAll() s3.matchEvent('lala', s0) s3.doResultEvent() s4.matchEvent('lulu', s0) s4.doResultEvent() e = EventSeq([EventNamed('lala'), EventAlt([EventNamed('lolo'), EventNamed('lulu')])]) s0.matchEventExpr(e, s2, False) sX = s0.checkEventExpr() self.assertTrue(id(s2) == id(sX), "Failed to return correct state") #? ( lala & lulu ) s0.events_expr = list() s0.cleanAll() s3 = State(nsr) s3.matchEvent('lala', s0) s3.doResultEvent() s4.matchEvent('lulu', s0) s4.doResultEvent() e = EventSeq([EventNamed('lala'), EventNamed('lulu')]) s0.matchEventExpr(e, s2, True) sX = s0.checkEventExpr() self.assertTrue(id(s2) == id(sX), "Failed to return correct state") self.assertFalse('lala' in nsr.named_events, "Events not correctly clean after match") self.assertFalse('lulu' in nsr.named_events, "Events not correctly clean after match") #? (lala & ( lolo | lulu)) s0.events_expr = list() nsr.cleanAll() s3.matchEvent('lala', s0) s3.doResultEvent() s4.matchEvent('lulu', s0) s4.doResultEvent() s5 = State(nsr) s5.matchEvent('lolo', s0) s5.doResultEvent() e = EventSeq([EventNamed('lala'), EventAlt([EventNamed('lolo'), EventNamed('lulu')])]) s0.matchEventExpr(e, s2, True) sX = s0.checkEventExpr() self.assertTrue(id(s2) == id(sX), "Failed to return correct state") self.assertFalse('lala' in nsr.named_events, "Events not correctly clean after match") self.assertFalse('lolo' in nsr.named_events, "Events not correctly clean after match") self.assertFalse('lulu' in nsr.named_events, "Events not correctly clean after match") def test_03(self): """Test tree automata construction""" def checkMatch(tree: Node, user_data) -> Node: pass # { Test(.b = 42) -> #checkMatch; Test(.c = 42) -> #checkMatch; } m = MatchBlock([ MatchHook(checkMatch, MatchType(Test, [MatchAttr('b', MatchValue(42))])), MatchHook(checkMatch, MatchType(Test, [MatchAttr('c', MatchValue(42))])), ]) tree = list() nsr = StateRegister() m.build_state_tree(tree, nsr) nsr.label = repr(m) nsr.to_png_file(rpath + os.sep + 't3_1.png') self.assertEqual(len(m.root_edge.next_edge), 1, "1 edge expected at this state for this pattern") it = iter(m.root_edge.next_edge.values()) eX = next(it) self.assertEqual(len(eX.next_edge), 2, "2 edge expected at this state for this pattern") # { Test(.b = 42) -> #checkMatch; A(.b = 42) -> #checkMatch; } class A: pass m = MatchBlock([ MatchHook(checkMatch, MatchType(Test, [MatchAttr('b', MatchValue(42))])), MatchHook(checkMatch, MatchType(A, [MatchAttr('b', MatchValue(42))])), ]) tree = list() nsr = StateRegister() m.build_state_tree(tree, nsr) nsr.label = repr(m) nsr.to_png_file(rpath + os.sep + 't3_2.png') self.assertEqual(len(m.root_edge.next_edge), 1, "1 edge expected at this state for this pattern") it = iter(m.root_edge.next_edge.values()) eX = next(it) self.assertEqual(len(eX.next_edge), 1, "1 edge expected at this state for this pattern") it = iter(eX.next_edge.values()) eX = next(it) self.assertEqual(len(eX.next_edge), 2, "2 edge expected at this state for this pattern") def test_04(self): """Test tree automata construction""" def checkMatch(tree: Node, user_data) -> Node: pass def otherHook(tree: Node, user_data) -> Node: pass lc = LivingContext() # { Test(.b = 42) -> #checkMatch; } m = MatchBlock([ MatchHook(checkMatch, MatchType(Test, [MatchAttr('b', MatchValue(42))])), ]) lc.add_match_block(m) # { Test(.b = 42) -> #otherHook; } m = MatchBlock([ MatchHook(otherHook, MatchType(Test, [MatchAttr('b', MatchValue(42))])), ]) lc.add_match_block(m) lc.build_automata() lc.to_png_file(rpath + os.sep + 't4_1.png') def test_05(self): """basic tree matching""" def checkMatch1(tree: Node, user_data) -> Node: global in_test in_test = True user_data[1].assertEqual(user_data[0], id(tree.node()), "Failed to match the node of tree") user_data[1].assertEqual(tree.attrs[0].value, 'b', "Failed to match the node of tree") user_data[1].assertEqual(tree.attrs[0].get(), 42, "Failed to match the node of tree") def checkMatch2(tree: Node, user_data) -> Node: global in_test in_test = True user_data[1].assertEqual(user_data[0], id(tree.node()), "Failed to match the node of tree") user_data[1].assertEqual(tree.attrs[0].value, 'a', "Failed to match the node of tree") user_data[1].assertEqual(tree.attrs[0].get(), 42, "Failed to match the node of tree") user_data[1].assertEqual(tree.attrs[1].value, 'c', "Failed to match the node of tree") user_data[1].assertEqual(tree.attrs[1].get(), 1.2, "Failed to match the node of tree") def checkMatch3(tree: Node, user_data) -> Node: global in_test in_test = True user_data[1].assertEqual(user_data[0], id(tree.node()), "Failed to match the node of tree") user_data[1].assertEqual(tree.indices[0].value, 2, "Failed to match the node of tree") user_data[1].assertEqual(tree.indices[0].get(), 42, "Failed to match the node of tree") def checkMatch4(tree: Node, user_data) -> Node: global in_test in_test = True user_data[1].assertEqual(user_data[0], id(tree.node()), "Failed to match the node of tree") user_data[1].assertEqual(tree.keys[0].value, 'toto', "Failed to match the node of tree") user_data[1].assertEqual(tree.keys[0].get(), 42, "Failed to match the node of tree") def checkMatch5(tree: Node, user_data) -> Node: global in_test print("MATCH TREE %s" % repr(tree.attrs), flush=True) in_test = True user_data[1].assertEqual(user_data[0], id(tree.node()), "Failed to match the node of tree") user_data[1].assertEqual(tree.attrs[0].value, 'a', "Failed to match the node of tree") user_data[1].assertEqual(tree.attrs[0].get(), 12, "Failed to match the node of tree") user_data[1].assertEqual(tree.attrs[1].value, 'c', "Failed to match the node of tree") user_data[1].assertEqual(tree.attrs[1].get(), 42, "Failed to match the node of tree") def checkMatch(tree: Node, user_data) -> Node: global in_test in_test = True user_data[1].assertEqual(user_data[0], id(tree.node()), "Failed to match the node of tree") def checkNoMatch(tree: Node, user_data) -> Node: global in_test in_test = True global in_test # Test(.b = 42) -> #checkMatch1; m = MatchBlock([ MatchHook(checkMatch1, MatchType(Test, [MatchAttr('b', MatchValue(42))])), ]) lc = LivingContext() lc.add_match_block(m) lc.build_automata() lc.to_png_file(rpath + os.sep + 't5_1.png') t = [Test()] t[0].b = 42 t.append(A()) t[1].b = 42 in_test = False walk(t, lc, (id(t[0]), self)) self.assertTrue(in_test, "Expect the Hook checkMatch is called") #self.assertTrue(lc.is_in_stable_state(), "LivingContext not in correct state") # Test(.b = 42) -> #checkNoMatch; m = MatchBlock([ MatchHook(checkNoMatch, MatchType(Test, [MatchAttr('b', MatchValue(42))])), ]) lc = LivingContext() lc.add_match_block(m) lc.build_automata() lc.to_png_file(rpath + os.sep + 't5_2.png') t = Test() t.a = 42 t.b = 12 in_test = False walk(t, lc, (id(t), self)) self.assertFalse(in_test, "Expect that the Hook checkNoMatch isn't called") #self.assertTrue(lc.is_in_stable_state(), "LivingContext not in correct state") # Test(.a=42, .c=1.2) -> #checkMatch2; m = MatchBlock([ MatchHook(checkMatch2, MatchType(Test, [MatchAttr('a', MatchValue(42)), MatchAttr('c', MatchValue(1.2))])), ]) c = LivingContext() lc.add_match_block(m) lc.build_automata() lc.to_png_file(rpath + os.sep + 't5_3.png') t = Test() t.a = 42 t.c = 1.2 in_test = False walk(t, lc, (id(t), self)) self.assertTrue(in_test, "Expect that the Hook checkMatch is called") #self.assertTrue(lc.is_in_stable_state(), "LivingContext not in correct state") t = Test() t.a = 42 t.b = Test() t.b.c = 1.2 in_test = False walk(t, lc, (id(t), self)) self.assertFalse(in_test, "Expect that the Hook checkMatch isn't called") #self.assertTrue(lc.is_in_stable_state(), "LivingContext not in correct state") # L([2: 42]) -> #checkMatch3; m = MatchBlock([ MatchHook(checkMatch3, MatchType(L, [MatchIndice(2, MatchValue(42))])), ]) lc = LivingContext() lc.add_match_block(m) lc.build_automata() lc.to_png_file(rpath + os.sep + 't5_4.png') t = [L(), L(), L()] t[0].append(10) t[0].append(42) t[1].append(11) t[1].append(12) t[1].append(13) t[2].append(14) t[2].append(15) t[2].append(42) in_test = False walk(t, lc, (id(t[2]), self)) self.assertTrue(in_test, "Expect the Hook checkMatch is called") #self.assertTrue(lc.is_in_stable_state(), "LivingContext not in correct state") # H({'toto': 42}) -> #checkMatch4; m = MatchBlock([ MatchHook(checkMatch4, MatchType(H, [MatchKey('toto', MatchValue(42))])), ]) lc = LivingContext() lc.add_match_block(m) lc.build_automata() lc.to_png_file(rpath + os.sep + 't5_5.png') t = [H(), H(), H()] t[0]['chausette'] = 12 t[0]['toto'] = 12 t[1]['toto'] = 42 t[2]['zozo'] = 42 in_test = False walk(t, lc, (id(t[1]), self)) self.assertTrue(in_test, "Expect the Hook checkMatch is called") #self.assertTrue(lc.is_in_stable_state(), "LivingContext not in correct state") # Test(.a = 12, .c = 42, ...) -> #checkMatch5; m = MatchBlock([ MatchHook(checkMatch5, MatchType(Test, [MatchAttr('a', MatchValue(12)), MatchAttr('c', MatchValue(42))], strict=False)), ]) lc = LivingContext() lc.add_match_block(m) lc.build_automata() lc.to_png_file(rpath + os.sep + 't5_6.png') t = [Test(), Test()] t[0].a = 12 t[0].b = 42 t[1].a = 12 t[1].b = 22 t[1].c = 42 t = normalize(t) in_test = False print("WALK BEGIN") #pdb.set_trace() walk(t, lc, (id(t[1]), self)) self.assertTrue(in_test, "Expect the Hook checkMatch is called") #self.assertTrue(lc.is_in_stable_state(), "LivingContext not in correct state") # Test^(.b = 42) -> #checkMatch; class ChildTest(Test): pass m = MatchBlock([ MatchHook(checkMatch, MatchType(Test, [MatchAttr('b', MatchValue(42))], iskindof=True)), ]) lc = LivingContext() lc.add_match_block(m) lc.build_automata() lc.to_png_file(rpath + os.sep + 't5_7.png') t = [ChildTest()] t[0].b = 42 t.append(A()) t[1].b = 42 in_test = False walk(t, lc, (id(t[0]), self)) self.assertTrue(in_test, "Expect the Hook checkMatch is called") #self.assertTrue(lc.is_in_stable_state(), "LivingContext not in correct state") def test_06(self): """tree rewriting""" def checkMatch1(tree: Node, user_data): global in_test in_test = True user_data[1].assertEqual(user_data[0], id(tree.node()), "Failed to match the node of tree") idx = tree.parent.index(tree.node()) tree.parent[idx] = "rewrited" def checkMatch2(tree: Node, user_data): global in_test in_test = True user_data[1].assertEqual(user_data[0], id(tree.node()), "Failed to match the node of tree") idx = tree.parent.index(tree.node()) tree.parent[idx] = "rewrited" def checkMatch3(tree: Node, user_data): global in_test in_test = True user_data[1].assertEqual(user_data[0], id(tree.node()), "Failed to match the node of tree") idx = tree.parent.index(tree.node()) tree.parent[idx] = "rewrited" def checkMatch4(tree: Node, user_data): global in_test in_test = True idx = tree.parent.index(tree.node()) tree.parent[idx] = "rewrited" global in_test # Test(.b = 42) -> #checkMatch1; m = MatchBlock([ MatchHook(checkMatch1, MatchType(Test, [MatchAttr('b', MatchValue(42))])), ]) lc = LivingContext() lc.add_match_block(m) lc.build_automata() lc.to_png_file(rpath + os.sep + 't6_1.png') t = [Test()] t[0].b = 42 t.append(A()) t[1].b = 42 in_test = False walk(t, lc, (id(t[0]), self)) self.assertTrue(in_test, "Expect the Hook checkMatch is called") #self.assertTrue(lc.is_in_stable_state(), "LivingContext not in correct state") self.assertEqual(t[0], "rewrited", "Failed to rewrite a node") # L([2: 42]) -> #checkMatch2; m = MatchBlock([ MatchHook(checkMatch2, MatchType(L, [MatchIndice(2, MatchValue(42))])), ]) lc = LivingContext() lc.add_match_block(m) lc.build_automata() lc.to_png_file(rpath + os.sep + 't6_2.png') t = [L(), L(), L()] t[0].append(10) t[0].append(42) t[1].append(11) t[1].append(12) t[1].append(13) t[2].append(14) t[2].append(15) t[2].append(42) in_test = False walk(t, lc, (id(t[2]), self)) self.assertTrue(in_test, "Expect the Hook checkMatch is called") #self.assertTrue(lc.is_in_stable_state(), "LivingContext not in correct state") self.assertEqual(t[2], "rewrited", "Failed to rewrite a node") # H({'toto': 42}) -> #checkMatch3; m = MatchBlock([ MatchHook(checkMatch3, MatchType(H, [MatchKey('toto', MatchValue(42))])), ]) lc = LivingContext() lc.add_match_block(m) lc.build_automata() lc.to_png_file(rpath + os.sep + 't6_3.png') t = ListNode([H(), H(), H()]) t[0]['chausette'] = 12 t[0]['toto'] = 13 t[1]['toto'] = 42 t[2]['zozo'] = 43 print("HHHHHHHHH %s" % repr(t)) in_test = False walk(t, lc, (id(t[1]), self)) ### self.assertTrue(in_test, "Expect the Hook checkMatch is called") #self.assertTrue(lc.is_in_stable_state(), "LivingContext not in correct state") self.assertEqual(t[1], "rewrited", "Failed to rewrite a node") # Test(.a = 12, .c = 42, ...) -> #checkMatch4; m = MatchBlock([ MatchHook(checkMatch4, MatchType(Test, [MatchAttr('a', MatchValue(12)), MatchAttr('c', MatchValue(42))], strict=False)), ]) lc = LivingContext() lc.add_match_block(m) lc.build_automata() lc.to_png_file(rpath + os.sep + 't6_4.png') t = ListNode([Test(), Test(), Test(), Test(), Test()]) t[0].a = 12 t[0].b = 42 t[1].a = 12 t[1].b = 22 t[1].c = 42 t[2] = "glubu" t[3].c = 42 t[3].a = 12 t[3].g = "plop" in_test = False walk(t, lc) self.assertTrue(in_test, "Expect the Hook checkMatch is called") #self.assertTrue(lc.is_in_stable_state(), "LivingContext not in correct state") self.assertEqual(t[1], "rewrited", "Failed to rewrite a node") self.assertEqual(t[3], "rewrited", "Failed to rewrite a node") def test_07(self): """wildcard tree matching""" global in_test # Test(.b = *) -> #checkMatch; def checkMatch1(tree: Node, user_data): global in_test in_test = True tree.node().is_rewrited = True m = MatchBlock([ MatchHook(checkMatch1, MatchType(Test, [MatchAttr('b')])), ]) lc = LivingContext() lc.add_match_block(m) lc.build_automata() lc.to_png_file(rpath + os.sep + 't7_1.png') t = [Test()] t[0].b = 42 t.append(A()) t[1].b = 666 t.append(Test()) t[2].b = "cool" in_test = False walk(t, lc) self.assertTrue(in_test, "Expect the Hook checkMatch is called") self.assertTrue(hasattr(t[0], "is_rewrited"), "Failed to rewrite a node") self.assertTrue(hasattr(t[2], "is_rewrited"), "Failed to rewrite a node") #self.assertFalse(lc.is_in_stable_state(), "LivingContext not in correct state due to WILDCAR MATCH") # L([2: *]) -> #checkMatch2; def checkMatch2(tree: Node, user_data): global in_test in_test = True print("++++++++++") tree.get().is_rewrited = True print("==========") print("RECV %s" % tree.dbg_str()) m = MatchBlock([ MatchHook(checkMatch2, MatchType(L, [MatchIndice(2)])), ]) lc = LivingContext() lc.add_match_block(m) lc.build_automata() lc.to_png_file(rpath + os.sep + 't7_2.png') t = L() t.append(Test()) t.append(A()) t.append(L()) t[0].a = 42 t[1].b = 42 t[2].c = 42 t[2].subls = [0, 1, L([2, 3, Test(), 4]), 5] t = normalize(t) in_test = False with self.assertRaises(ValueError): walk(t, lc) t[2].subls = L([0, 1, L([2, 3, Test(), 4]), 5]) walk(t, lc) self.assertTrue(in_test, "Expect the Hook checkMatch is called") self.assertTrue(hasattr(t[2], "is_rewrited"), "Failed to rewrite a node") self.assertTrue(hasattr(t[2].subls[2][2], "is_rewrited"), "Failed to rewrite a node") #self.assertFalse(lc.is_in_stable_state(), "LivingContext not in correct state due to WILDCAR MATCH") # H({'toto': *}) -> #checkMatch; def checkMatch3(tree: Node, user_data): global in_test in_test = True tree.node().is_rewrited = True m = MatchBlock([ MatchHook(checkMatch3, MatchType(H, [MatchKey("toto")])), ]) lc = LivingContext() lc.add_match_block(m) lc.build_automata() lc.to_png_file(rpath + os.sep + 't7_3.png') t = H() t['bla'] = Test() t['bla'].a = 42 t['toto'] = Test() t['toto'].b = 42 t['blu'] = Test() t['blu'].c = 42 t['blu'].subh = {'t': 0, 'x': 1, 'toto': H({'2': 2, '3': 3, 'toto': Test(), '4': 4}), 'z': 5} in_test = False with self.assertRaises(ValueError): walk(t, lc) t['blu'].subh = H({'t': 0, 'x': 1, 'toto': H({'2': 2, '3': 3, 'toto': Test(), '4': 4}), 'z': 5}) walk(t, lc) self.assertTrue(in_test, "Expect the Hook checkMatch is called") self.assertTrue(hasattr(t, "is_rewrited"), "Failed to rewrite a node") self.assertTrue(hasattr(t['blu'].subh['toto'], "is_rewrited"), "Failed to rewrite a node") #self.assertFalse(lc.is_in_stable_state(), "LivingContext not in correct state due to WILDCAR MATCH") # Test([*: 12]) -> #checkMatch; print('-------------------------------------------------------------------------------') def checkMatch4(tree: Node, user_data): global in_test in_test = True tree.node().is_rewrited = True m = MatchBlock([ MatchHook(checkMatch4, MatchType(L, [MatchIndice(None, MatchValue(12))])), ]) lc = LivingContext() lc.add_match_block(m) lc.build_automata() lc.to_png_file(rpath + os.sep + 't7_4.png') t = L([1, 12, 2, 12, 3, 12]) in_test = False walk(t, lc) self.assertTrue(in_test, "Expect the Hook checkMatch is called") self.assertTrue(hasattr(t, "is_rewrited"), "Failed to rewrite a node") # Test(.* = *) -> #checkMatch; # *(.a = 12) -> #checkMatch; # L([*: 12]) -> #checkMatch; # L([*: *]) -> #checkMatch; # H({*: 12}) -> #checkMatch; # H({*: *}) -> #checkMatch; def test_08(self): """CollectContext test for tree matching""" class A(Node): pass a = A() a.attr1 = 6.6 a["toto"] = 42 a["plop"] = 'gram' ## ct = CaptureContext() ct.is_key(a, "toto") ct2 = CaptureContext() ct2.is_key(a, "plop") ctx = CaptureContext.make_from_unorder_list([ct, ct2]) ctx.is_node(a, "A") ca = CaptureContext().is_attr(a, "attr1") ctx.add_sub(ca) self.assertEqual(a.attr1, ca.get(), "Failed to get a captured value in a tree") self.assertEqual(a["toto"], ct.get(), "Failed to get a captured value in a tree") self.assertEqual(a["plop"], ct2.get(), "Failed to get a captured value in a tree") ct.set('pouet') ct2.set('chaussure') ca.set(999) self.assertEqual(a.attr1, 999, "Failed to get a captured value in a tree") self.assertEqual(a["toto"], "pouet", "Failed to get a captured value in a tree") self.assertEqual(a["plop"], "chaussure", "Failed to get a captured value in a tree") ctx.set(Node()) self.assertTrue(not hasattr(ctx, 'keys'), "Failed to clean a node by setting it") def test_09(self): """node.normalize test""" # dict d = {'blabal': 12, 'lolo': 555, 'hyhy': 1000} d = normalize(d) self.assertTrue(type(d) is DictNode) d = {'blabal': 12, 'hash':{'xoxo': 111, 'koko': 44, 'juju': 12121}, 'lolo': 555, 'hyhy': 1000} d = normalize(d) self.assertTrue(type(d) is DictNode) self.assertTrue(type(d['hash']) is DictNode) # list l = L() l.append(12) l.append(23) l.append([1, 3, 4, 5]) l.append(45) l = normalize(l) self.assertTrue(type(l) is L) self.assertTrue(type(l[2]) is ListNode) # tuple t = (1, 2, 3) t = normalize(t) self.assertTrue(type(t) is TupleNode) t = (1, [2, {'toto': 5}], 3) t = normalize(t) self.assertTrue(type(t) is TupleNode) self.assertTrue(type(t[1]) is ListNode) self.assertTrue(type(t[1][1]) is DictNode) r = weakref.ref(t[1][1]) r()['glagla'] = 'chaussette' self.assertIn('glagla', t[1][1]) self.assertEqual(t[1][1]['glagla'], 'chaussette') l = [1, 2, [3, 4, [5, 6], 7], 8] l = normalize(l) r = weakref.ref(l[2][2]) r()[1] = 42 self.assertEqual(l[2][2][1], 42)
class InternalAst_Test(unittest.TestCase): def test_000(self): '''ListNode tests''' pass def test_000(self): '''Basic test on state creation''' pass def dummy(nodes, user_data): pass def test_01(self): '''Event Expr event''' pass def test_03(self): '''Test tree automata construction''' pass def checkMatch(tree: Node, user_data) -> Node: pass class A: def test_04(self): '''Test tree automata construction''' pass def checkMatch(tree: Node, user_data) -> Node: pass def otherHook(tree: Node, user_data) -> Node: pass def test_05(self): '''basic tree matching''' pass def checkMatch1(tree: Node, user_data) -> Node: pass def checkMatch2(tree: Node, user_data) -> Node: pass def checkMatch3(tree: Node, user_data) -> Node: pass def checkMatch4(tree: Node, user_data) -> Node: pass def checkMatch5(tree: Node, user_data) -> Node: pass def checkMatch(tree: Node, user_data) -> Node: pass def checkNoMatch(tree: Node, user_data) -> Node: pass class ChildTest(Test): def test_06(self): '''tree rewriting''' pass def checkMatch1(tree: Node, user_data) -> Node: pass def checkMatch2(tree: Node, user_data) -> Node: pass def checkMatch3(tree: Node, user_data) -> Node: pass def checkMatch4(tree: Node, user_data) -> Node: pass def test_07(self): '''wildcard tree matching''' pass def checkMatch1(tree: Node, user_data) -> Node: pass def checkMatch2(tree: Node, user_data) -> Node: pass def checkMatch3(tree: Node, user_data) -> Node: pass def checkMatch4(tree: Node, user_data) -> Node: pass def test_08(self): '''CollectContext test for tree matching''' pass class A: def test_09(self): '''node.normalize test''' pass
33
10
31
0
29
2
1
0.1
1
35
28
0
10
0
10
82
842
14
756
107
708
73
719
107
668
11
2
2
39
146,113
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/internal_ast.py
tests.internal_ast.InternalAst_Test.test_05.ChildTest
class ChildTest(Test): pass
class ChildTest(Test): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
1
1
0
1
1
1
0
2
1
1
0
2
0
0
146,114
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.Hook
class Hook(Functor, Leaf): """ Call a hook by his name. """ def __init__(self, name: str, param: [(object, type)]): Functor.__init__(self) self.name = name # compose the list of value param, check type for v, t in param: if type(t) is not type: raise TypeError("Must be pair of value and type (i.e: int, " "str, Node)") self.param = param def do_call(self, parser: BasicParser) -> bool: valueparam = [] for v, t in self.param: if t is Node: if v not in parser.rule_nodes: parser.diagnostic.notify( error.Severity.ERROR, "Unknown capture variable : %s" % v, error.LocationInfo.from_stream( parser._stream, is_error=True ) ) raise parser.diagnostic valueparam.append(parser.rule_nodes[v]) elif type(v) is t: valueparam.append(v) else: raise TypeError("Type mismatch expected {} got {}".format( t, type(v))) return parser.eval_hook(self.name, valueparam)
class Hook(Functor, Leaf): ''' Call a hook by his name. ''' def __init__(self, name: str, param: [(object, type)]): pass def do_call(self, parser: BasicParser) -> bool: pass
3
1
15
0
15
1
4
0.07
2
8
3
0
2
2
2
4
34
2
30
8
27
2
19
8
16
5
1
3
8
146,115
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/type_system/type_expr.py
pyrser.type_system.type_expr.TypeExpr
class TypeExpr: def __init__(self, expr): self.expr = expr parser = TypeExprParser() self.tn = parser.parse(self.expr) @property def getCTN(self) -> ComponentTypeName: return self.tn
class TypeExpr: def __init__(self, expr): pass @property def getCTN(self) -> ComponentTypeName: pass
4
0
3
0
3
0
1
0
0
2
2
0
2
2
2
2
9
1
8
7
4
0
7
6
4
1
0
0
2
146,116
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/type_system/type_expr.py
pyrser.type_system.type_expr.RealName
class RealName(TypeName): pass
class RealName(TypeName): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
4
2
0
2
1
1
0
2
1
1
0
1
0
0
146,117
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/type_system/type_expr.py
pyrser.type_system.type_expr.DeltaComponentTypeName
class DeltaComponentTypeName: def __init__(self): self.diff = [] def __len__(self): return 0 def add(self, d1, d2): class D(dict): pass d = D() d.wref1 = ref(d1) d.wref2 = ref(d2) self.diff.append(d)
class DeltaComponentTypeName: def __init__(self): pass def __len__(self): pass def add(self, d1, d2): pass class DeltaComponentTypeName:
5
0
4
0
4
0
1
0
0
1
1
0
3
1
3
3
14
2
12
7
7
0
12
7
7
1
0
0
3
146,118
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.RewritingRules
class RewritingRules(Functor): """ Allow to write rewriting rules that transform the AST before code generation/interpretation. """ def __init__(self, name: str=""): self.name = name
class RewritingRules(Functor): ''' Allow to write rewriting rules that transform the AST before code generation/interpretation. ''' def __init__(self, name: str=""): pass
2
1
2
0
2
0
1
1
1
1
0
0
1
1
1
3
7
1
3
3
1
3
3
3
1
1
1
0
1
146,119
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.RepOptional
class RepOptional(Functor): """ []? bnf primitive as a functor. """ def __init__(self, pt: Seq): Functor.__init__(self) self.pt = pt if (isinstance(self.pt, Text) or isinstance(self.pt, Char) or isinstance(self.pt, Range) or isinstance(self.pt, Directive) ): self.pt = Seq(self.pt) def do_call(self, parser: BasicParser) -> bool: res = self.pt(parser) if res: return res return True
class RepOptional(Functor): ''' []? bnf primitive as a functor. ''' def __init__(self, pt: Seq): pass def do_call(self, parser: BasicParser) -> bool: pass
3
1
6
0
6
0
2
0.08
1
7
6
0
2
1
2
4
15
1
13
5
10
1
11
5
8
2
1
1
4
146,120
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.Rep1N
class Rep1N(Functor): """ []+ bnf primitive as a functor. """ def __init__(self, pt: Seq): Functor.__init__(self) self.pt = pt if (isinstance(self.pt, Text) or isinstance(self.pt, Char) or isinstance(self.pt, Range) or isinstance(self.pt, Directive) ): self.pt = Seq(self.pt) def do_call(self, parser: BasicParser) -> bool: parser._stream.save_context() parser.push_rule_nodes() if self.pt(parser): while self.pt(parser): pass parser.pop_rule_nodes() return parser._stream.validate_context() parser.pop_rule_nodes() return parser._stream.restore_context()
class Rep1N(Functor): ''' []+ bnf primitive as a functor. ''' def __init__(self, pt: Seq): pass def do_call(self, parser: BasicParser) -> bool: pass
3
1
9
0
9
0
3
0.06
1
7
6
0
2
1
2
4
21
2
18
4
15
1
16
4
13
3
1
2
5
146,121
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/grammar_directive.py
tests.grammar_directive.IgnoreBlanks
class IgnoreBlanks(grammar.Grammar): grammar = """ root =[ @ignore("blank") [ [ item : i #add_to(_, i) ]+ eof ] ] item = [ 'a'..'z' | 'A'..'Z' | '.' | '!' | ' ' | '\n' | '\r' | '\t' | '\v' | '\f' | '\b' ] """ entry = "root"
class IgnoreBlanks(grammar.Grammar): pass
1
0
0
0
0
0
0
0.11
1
0
0
0
0
0
0
0
10
1
9
2
8
1
3
2
2
0
1
0
0
146,122
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/ast/state.py
state.LivingContext
class LivingContext: """ Create & Destroy Living State during tree walking for a current StateRegister. """ def __init__(self): self.mblock = [] self.nsr = [] self.ls = [] self.named_events = {} def add_match_block(self, m): self.mblock.append(m) def build_automata(self): for b in self.mblock: tree = list() nsr = StateRegister(named_events=self.named_events) b.build_state_tree(tree, nsr) nsr.label = repr(b) self.nsr.append(nsr) self.ls = [] self.init_all() def init_all(self): for nsr in self.nsr: self.ls.append((nsr.default, LivingState(nsr.default))) def is_in_stable_state(self) -> bool: return len(self.nsr) == len(self.ls) #TODO: forward call to internal state def checkEventExpr(self): for ls in self.ls: ls[1].checkEventExpr() def checkAttr(self, a, thenode=None): for ls in self.ls: ls[1].checkAttr(a, thenode) def checkIndice(self, i, thenode=None): # TODO: must store indice and restore state... # if wildcard, type are not strict... # so set an event after parsing all indices fork_state = [] l = len(self.ls) for idx, ls in zip(range(l), self.ls): store_indice = False if ls[1].thestate().wild_indice: store_indice = True ls[1].checkIndice(i, thenode) def checkKey(self, k, thenode=None): for ls in self.ls: ls[1].checkKey(k, thenode) def checkType(self, t, thenode=None, parent=None): for ls in self.ls: ls[1].checkType(t, thenode, parent) def checkValue(self, v): #print("check value") for ls in self.ls: ls[1].checkValue(v) def doResultHook(self, thenode=None, user_data=None, parent=None): for ls in self.ls: ls[1].doResultHook(thenode, user_data, parent) #TODO: check subEvent for put it in LivingState ls[1].have_finish = True def doSubEvent(self): # TODO: doSubEvent on livingState and State for ls in self.ls: ls[1].doResultEvent() def doResultEvent(self): for ls in self.ls: ls[1].doResultEvent() #TODO: check subEvent for put it in LivingState ls[1].have_finish = True def doDefault(self): for ls in self.ls: if ls[1].alive is False: ls[1].doDefault() def resetLivingState(self): """Only one Living State on the S0 of each StateRegister""" # TODO: add some test to control number of instanciation of LivingState # clean all living state on S0 must_delete = [] l = len(self.ls) for idx, ls in zip(range(l), self.ls): # TODO: alive by default on False, change to True on the first match ids = id(ls[1].thestate()) if ids == id(ls[0]) and (ls[1].have_finish or not ls[1].alive): must_delete.append(idx) elif ls[1].alive: ls[1].alive = False for delete in reversed(must_delete): self.ls.pop(delete) self.init_all() ############# def to_dot(self) -> str: lscat = [] for nsr in self.nsr: f = tempfile.NamedTemporaryFile(delete=False) f.close() lscat.append(f.name) nsr.to_dot_file(f.name) cmd = pipes.Template() cmd.prepend('gvpack 2>/dev/null -u ' + ' '.join(lscat), '.-') content = "" with cmd.open('pipefile', 'r') as f: content += f.read() for f in lscat: os.unlink(f) return content def to_dot_file(self, fname: str): with open(fname, 'w') as f: f.write(self.to_dot()) def to_png_file(self, fname: str): cmd = pipes.Template() cmd.append('dot -Tpng > %s' % fname, '-.') with cmd.open('pipefile', 'w') as f: f.write(self.to_dot())
class LivingContext: ''' Create & Destroy Living State during tree walking for a current StateRegister. ''' def __init__(self): pass def add_match_block(self, m): pass def build_automata(self): pass def init_all(self): pass def is_in_stable_state(self) -> bool: pass def checkEventExpr(self): pass def checkAttr(self, a, thenode=None): pass def checkIndice(self, i, thenode=None): pass def checkKey(self, k, thenode=None): pass def checkType(self, t, thenode=None, parent=None): pass def checkValue(self, v): pass def doResultHook(self, thenode=None, user_data=None, parent=None): pass def doSubEvent(self): pass def doResultEvent(self): pass def doDefault(self): pass def resetLivingState(self): '''Only one Living State on the S0 of each StateRegister''' pass def to_dot(self) -> str: pass def to_dot_file(self, fname: str): pass def to_png_file(self, fname: str): pass
20
2
6
0
5
1
2
0.17
0
9
2
0
19
4
19
19
129
18
95
54
75
16
94
52
74
5
0
2
39
146,123
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/ast/state.py
state.LivingState
class LivingState: """ State instances in a StateRegister represents all the tree automata but only LivingState that reference a State instance are used during the walk. """ def __init__(self, s: State): self.alive = False self.have_finish = False self.thestate = weakref.ref(s) # list of CaptureContext # TODO: MUST be surround by another # when the living state return to first state self.nodectx = CaptureContext() # for attrs,indices,keys collect id of parents self.subelmtctx = [] self.subelmt = [] #TODO: forward call to internal state def checkEventExpr(self): s = self.thestate().checkEventExpr() if id(s) != id(self.thestate()): self.thestate = weakref.ref(s) self.alive = True def checkAttr(self, a, thenode=None): s = self.thestate().checkAttr(a) if id(s) != id(self.thestate()): ctx = CaptureContext() ctx.is_attr(thenode, a) self.subelmtctx.append(ctx) self.subelmt.append(id(thenode)) #print("ADDSUBELMT %s in %d" % (self.subelmtctx, id(self))) self.thestate = weakref.ref(s) self.alive = True def checkIndice(self, i, thenode=None): s = self.thestate().checkIndice(i) if id(s) != id(self.thestate()): ctx = CaptureContext() ctx.is_indice(thenode, i) self.subelmtctx.append(ctx) self.subelmt.append(id(thenode)) self.thestate = weakref.ref(s) self.alive = True def checkKey(self, k, thenode=None): s = self.thestate().checkKey(k) if id(s) != id(self.thestate()): ctx = CaptureContext() ctx.is_key(thenode, k) self.subelmtctx.append(ctx) self.subelmt.append(id(thenode)) self.thestate = weakref.ref(s) self.alive = True def checkType(self, t, thenode=None, parent=None): statetype = self.thestate() # count the number of subelmt that belong to this type nsubelm = 0 toremove = [] l = len(self.subelmt) for idx, subelmtid in zip(range(l), self.subelmt): if id(thenode) == subelmtid: toremove.append(idx) nsubelm += 1 # check the num min of subelmt associate with this type if nsubelm >= statetype.minsubelmt: s = self.thestate().checkType(t) if id(s) == id(self.thestate()): s = self.thestate().checkKindOfType(t) if id(s) != id(self.thestate()): #print("ADD THENODE: %s" % thenode) subnodes = [] for idx in toremove: subnodes.append(self.subelmtctx[idx]) ctx = CaptureContext.make_from_unorder_list(subnodes) # TODO: must extract the correct sublist # to surround by the node #self.nodectx.is_node(thenode, t.__name__, parent) ctx.is_node(thenode, t.__name__, parent) self.nodectx = ctx self.subelmtctx.append(ctx) self.subelmt.append(id(parent)) # TODO: think a better way to store # in // old ref for ancestors...siblings... self.thestate = weakref.ref(s) self.alive = True for idx in reversed(toremove): self.subelmt.pop(idx) #print("remove %d in %d" % (idx, id(self))) self.subelmtctx.pop(idx) def checkValue(self, v): s = self.thestate().checkValue(v) if id(s) != id(self.thestate()): self.thestate = weakref.ref(s) self.alive = True def doResultHook(self, thenode=None, user_data=None, parent=None): #TODO: must handle parent s = self.thestate().doResultHook(self.nodectx, user_data) if id(s) != id(self.thestate()): #print("RESET MATCHED NODES HOOK") #self.matched_nodes = [] #self.old_ref = [] self.thestate = weakref.ref(s) self.alive = True def doResultEvent(self): # TODO: event stored in the LivingState olds = self.thestate() s = self.thestate().doResultEvent() if id(s) != id(self.thestate()): #print("RESET MATCHED NODES EV") ##self.matched_nodes = [] ##self.old_ref = [] self.thestate = weakref.ref(s) self.alive = True def doDefault(self): # TODO: ??? kill livingState in LivingContext?? s = self.thestate().doDefault() if id(s) != id(self.thestate()): #print("RESET MATCHED NODES DEFAULT") #self.matched_nodes = [] #self.old_ref = [] self.thestate = weakref.ref(s) self.alive = True
class LivingState: ''' State instances in a StateRegister represents all the tree automata but only LivingState that reference a State instance are used during the walk. ''' def __init__(self, s: State): pass def checkEventExpr(self): pass def checkAttr(self, a, thenode=None): pass def checkIndice(self, i, thenode=None): pass def checkKey(self, k, thenode=None): pass def checkType(self, t, thenode=None, parent=None): pass def checkValue(self, v): pass def doResultHook(self, thenode=None, user_data=None, parent=None): pass def doResultEvent(self): pass def doDefault(self): pass
11
1
11
0
9
3
3
0.35
0
5
2
0
10
6
10
10
128
9
88
37
77
31
88
37
77
8
0
3
25
146,124
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/ast/state.py
state.State
class State: pass
class State: pass
1
0
10
0
9
1
3
0.13
0
12
6
0
28
18
28
28
327
35
259
64
230
33
207
64
178
17
0
4
86
146,125
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/ast/state.py
state.StateEvent
class StateEvent: """ State for handling Resulting Event. """ def __init__(self, n: str, st: State): self.name = n self.st = st
class StateEvent: ''' State for handling Resulting Event. ''' def __init__(self, n: str, st: State): pass
2
1
3
0
3
0
1
0.75
0
2
1
0
1
2
1
1
7
0
4
4
2
3
4
4
2
1
0
0
1
146,126
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/ast/state.py
state.StateHook
class StateHook: """ State for handling Resulting Hooks. """ def __init__(self, call: callable, st: State): if not callable(call): raise ValueError("'call' argument must be a callable") self.call = call self.st = st
class StateHook: ''' State for handling Resulting Hooks. ''' def __init__(self, call: callable, st: State): pass
2
1
5
0
5
0
2
0.5
0
2
1
0
1
2
1
1
9
0
6
4
4
3
6
4
4
2
0
1
2
146,127
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/ast/state.py
state.StatePrecond
class StatePrecond: """ State for handling Precondition using predicates. """ def __init__(self, e: EventExpr, st: State, clean_event: bool): self.expr = e self.txtevent = repr(e) self.st = st self.clean_event = clean_event def to_fmt(self) -> fmt.indentable: res = fmt.sep(' : ', []) res.lsdata.append(self.txtevent) res.lsdata.append(id(self.st)) res.lsdata.append(self.clean_event) return res def __repr__(self) -> str: return str(self.to_fmt())
class StatePrecond: ''' State for handling Precondition using predicates. ''' def __init__(self, e: EventExpr, st: State, clean_event: bool): pass def to_fmt(self) -> fmt.indentable: pass def __repr__(self) -> str: pass
4
1
4
0
4
0
1
0.21
0
6
4
0
3
4
3
3
19
2
14
9
10
3
14
9
10
1
0
0
3
146,128
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/ast/state.py
state.StateRegister
class StateRegister(): """ All State belongs to a global register that manage named events. """ def __init__(self, named_events: dict={}, label=None): # default state self.__default = None # all state belonging to this register self.states = dict() # label store the string representation of the PSL expression # that is responsible of all these states self.label = label # handle events self.named_events = named_events def cleanAll(self): """ Set all events to empty. """ self.named_events.clear() def set_default_state(self, s: State): if id(s) not in self.states: raise ValueError("%d not in StateRegister" % id(s)) self.__default = s @property def default(self) -> State: return self.__default def add_state(self, s: State): """ all state in the register have a uid """ ids = id(s) uid = len(self.states) if ids not in self.states: self.states[ids] = (uid, s) def get_uid(self, s: State) -> int: if id(s) not in self.states: raise ValueError("%d not in StateRegister" % id(s)) return self.states[id(s)][0] def __contains__(self, s: State) -> bool: sts = set(list(self.states.keys())) return id(s) in sts def to_dot(self) -> str: """ Provide a '.dot' representation of all State in the register. """ txt = "" txt += "digraph S%d {\n" % id(self) if self.label is not None: txt += '\tlabel="%s";\n' % (self.label + '\l').replace('\n', '\l') txt += "\trankdir=LR;\n" #txt += '\tlabelloc="t";\n' txt += '\tgraph [labeljust=l, labelloc=t, nojustify=true];\n' txt += "\tesep=1;\n" txt += '\tranksep="equally";\n' txt += "\tnode [shape = circle];\n" txt += "\tsplines = ortho;\n" for s in self.states.values(): txt += s[1].to_dot() txt += "}\n" return txt def to_dot_file(self, fname: str): """ write a '.dot' file. """ with open(fname, 'w') as f: f.write(self.to_dot()) def to_png_file(self, fname: str): """ write a '.png' file. """ cmd = pipes.Template() cmd.append('dot -Tpng > %s' % fname, '-.') with cmd.open('pipefile', 'w') as f: f.write(self.to_dot()) def to_fmt(self) -> str: """ Provide a useful representation of the register. """ infos = fmt.end(";\n", []) s = fmt.sep(', ', []) for ids in sorted(self.states.keys()): s.lsdata.append(str(ids)) infos.lsdata.append(fmt.block('(', ')', [s])) infos.lsdata.append("events:" + repr(self.events)) infos.lsdata.append( "named_events:" + repr(list(self.named_events.keys())) ) infos.lsdata.append("uid_events:" + repr(list(self.uid_events.keys()))) return infos def __repr__(self) -> str: return str(self.to_fmt())
class StateRegister(): ''' All State belongs to a global register that manage named events. ''' def __init__(self, named_events: dict={}, label=None): pass def cleanAll(self): ''' Set all events to empty. ''' pass def set_default_state(self, s: State): pass @property def default(self) -> State: pass def add_state(self, s: State): ''' all state in the register have a uid ''' pass def get_uid(self, s: State) -> int: pass def __contains__(self, s: State) -> bool: pass def to_dot(self) -> str: ''' Provide a '.dot' representation of all State in the register. ''' pass def to_dot_file(self, fname: str): ''' write a '.dot' file. ''' pass def to_png_file(self, fname: str): ''' write a '.png' file. ''' pass def to_fmt(self) -> str: ''' Provide a useful representation of the register. ''' pass def __repr__(self) -> str: pass
14
7
7
0
5
2
2
0.42
0
12
4
0
12
4
12
12
102
11
64
29
50
27
61
26
48
3
0
1
18
146,129
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/ast/state.py
state.CaptureContext
class CaptureContext: pass
class CaptureContext: pass
1
0
10
0
10
1
3
0.07
0
10
5
0
12
4
12
12
143
12
122
35
109
9
102
35
89
11
0
4
34
146,130
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/gen_dsl.py
tests.gen_dsl.GenDsl_Test
class GenDsl_Test(unittest.TestCase): def test_000_init(self): os.makedirs('build_cython', exist_ok=True); # add the path for modules import sys sys.path.append('./build_cython') def test_00_seqchar(self): """Test sequence and char """ class SeqChar(grammar.Grammar): entry = "test" grammar = """test = [ 'a' 'c' 'b' 'e' ] """ p = SeqChar() cython.generate(p, indir='build_cython', keep_tmp=True) primit = importlib.import_module('build_cython.seqchar') p = primit.SeqChar("acbe") res = p.test() self.assertTrue(res, "Bad parsing") p = primit.SeqChar("acb") res = p.test() self.assertFalse(res, "Bad parsing") p = primit.SeqChar("coucou") res = p.test() self.assertFalse(res, "Bad parsing") def test_01_altchar(self): """Test alternative and char """ class AltChar(grammar.Grammar): entry = "test" grammar = """test = [ 'a' ['c' | 'b' ['e' | 'z'] ] 'd'] """ p = AltChar() cython.generate(p, indir='build_cython', keep_tmp=True) primit = importlib.import_module('build_cython.altchar') p = primit.AltChar("coucou") res = p.test() self.assertFalse(res, "Bad parsing") p = primit.AltChar("acd") res = p.test() self.assertTrue(res, "Bad parsing") p = primit.AltChar("abed") res = p.test() self.assertTrue(res, "Bad parsing") p = primit.AltChar("abzd") res = p.test() self.assertTrue(res, "Bad parsing") p = primit.AltChar("abd") res = p.test() self.assertFalse(res, "Bad parsing") def test_02_text(self): """Test gen text """ class Text(grammar.Grammar): entry = "test" grammar = """test = ["hello"|"world"] """ p = Text() cython.generate(p, indir='build_cython') primit = importlib.import_module('build_cython.text') p = primit.Text("hello") res = p.test() self.assertTrue(res, "Bad parsing") p = primit.Text("world") res = p.test() self.assertTrue(res, "Bad parsing") p = primit.Text("abed") res = p.test() self.assertFalse(res, "Bad parsing") p = primit.Text("helworld") res = p.test() self.assertFalse(res, "Bad parsing") p = primit.Text("helloworld") res = p.test() self.assertTrue(res, "Bad parsing") def test_03_number(self): """Test gen number """ class Number(grammar.Grammar): entry = "test" grammar = """test = [ ['0'..'9']* | "coucou" ] """ p = Number() cython.generate(p, indir='build_cython', keep_tmp=True) primit = importlib.import_module('build_cython.number') p = primit.Number("12") res = p.test() self.assertTrue(res, "Bad parsing") p = primit.Number("123hy") res = p.test() self.assertTrue(res, "Bad parsing") p = primit.Number("abed") res = p.test() self.assertFalse(res, "Bad parsing") p = primit.Number("coucou") res = p.test() self.assertTrue(res, "Bad parsing") def test_03_number2(self): """Test gen number2 """ class Number2(grammar.Grammar): entry = "test" grammar = """test = [ ['0'..'9' | '_']+ ] """ p = Number2() cython.generate(p, indir='build_cython', keep_tmp=True) primit = importlib.import_module('build_cython.number2') p = primit.Number2("12") res = p.test() self.assertTrue(res, "Bad parsing") p = primit.Number2("_") res = p.test() self.assertTrue(res, "Bad parsing") p = primit.Number2("abed") res = p.test() self.assertFalse(res, "Bad parsing") p = primit.Number2("") res = p.test() self.assertFalse(res, "Bad parsing") p = primit.Number2("12__23_123414232_123") res = p.test() self.assertTrue(res, "Bad parsing") def test_04_optional(self): """Test gen optional """ class Optional(grammar.Grammar): entry = "test" grammar = """test = [ ['!']? 'A' | ['?']? 'B' ] """ p = Optional() cython.generate(p, indir='build_cython', keep_tmp=True) primit = importlib.import_module('build_cython.optional') p = primit.Optional("A") res = p.test() self.assertTrue(res, "Bad parsing") p = primit.Optional("B") res = p.test() self.assertTrue(res, "Bad parsing") p = primit.Optional("!A") res = p.test() self.assertTrue(res, "Bad parsing") p = primit.Optional("?B") res = p.test() self.assertTrue(res, "Bad parsing") p = primit.Optional("!?B") res = p.test() self.assertFalse(res, "Bad parsing") def test_05_neg(self): """Test gen neg """ class Neg(grammar.Grammar): entry = "test" grammar = """test = [ '=' !'=' ] """ p = Neg() cython.generate(p, indir='build_cython', keep_tmp=True) primit = importlib.import_module('build_cython.neg') p = primit.Neg("=") res = p.test() self.assertTrue(res, "Bad parsing") p = primit.Neg("==") res = p.test() self.assertFalse(res, "Bad parsing") p = primit.Neg("=a") res = p.test() self.assertTrue(res, "Bad parsing") def test_06_complement(self): """Test gen complement """ try: class Complement(grammar.Grammar): entry = "test" #grammar = """test = [ '"' [~"\\\\" | "\\\\" ~' ']* '"' ] #""" grammar = """ test = [ [~'A']+ 'A' ] """ except error.Diagnostic as d: print(d.get_content()) raise d p = Complement() cython.generate(p, indir='build_cython', keep_tmp=True) primit = importlib.import_module('build_cython.complement') p = primit.Complement("CDBA") res = p.test() self.assertTrue(res, "Bad parsing") p = primit.Complement("A") res = p.test() self.assertFalse(res, "Bad parsing") p = primit.Complement("C +\`3BA") res = p.test() self.assertTrue(res, "Bad parsing") p = primit.Complement("C[]") res = p.test() self.assertFalse(res, "Bad parsing") def test_07_string(self): """Test gen string """ try: class String(grammar.Grammar): entry = "test" grammar = """ test = [ '"' [ ~["\\\\"|'"'] | "\\\\" ~' ']* '"' ] """ except error.Diagnostic as d: print(d.get_content()) raise d p = String() cython.generate(p, indir='build_cython', keep_tmp=True) primit = importlib.import_module('build_cython.string') # TODO: Why I can't pass the following test? #p = primit.String('""') #res = p.test() #self.assertTrue(res, "Bad parsing") p = primit.String('" "') res = p.test() self.assertTrue(res, "Bad parsing") p = primit.String('"toto"') res = p.test() self.assertTrue(res, "Bad parsing") p = primit.String('"lolo\\"kiki"') res = p.test() self.assertTrue(res, "Bad parsing") p = primit.String('"lolo\\"') res = p.test() self.assertFalse(res, "Bad parsing") p = primit.String('"lolo\\ kiki"') res = p.test() self.assertFalse(res, "Bad parsing") def test_08_lookahead(self): """Test gen lookahead """ try: class LookAhead(grammar.Grammar): entry = "test" grammar = """ test = [ !!["toto"| '0'..'9'] ["toto"| '0'..'9' ['0'..'9']+ ] | !'0'..'9' ~' ' ] """ except error.Diagnostic as d: print(d.get_content()) raise d p = LookAhead() cython.generate(p, indir='build_cython', keep_tmp=True) primit = importlib.import_module('build_cython.lookahead') p = primit.LookAhead('123') res = p.test() self.assertTrue(res, "Bad parsing") p = primit.LookAhead('toto') res = p.test() self.assertTrue(res, "Bad parsing") p = primit.LookAhead('t') res = p.test() self.assertTrue(res, "Bad parsing") p = primit.LookAhead('1t') res = p.test() self.assertFalse(res, "Bad parsing") def test_09_until(self): """Test gen until """ try: class Until(grammar.Grammar): entry = "test" grammar = """ test = [ 'a'..'z'+ ->'A'..'Z' 'A'..'Z'+ ] """ except error.Diagnostic as d: print(d.get_content()) raise d p = Until() cython.generate(p, indir='build_cython', keep_tmp=True) primit = importlib.import_module('build_cython.until') p = primit.Until('blabla +- TOTO') res = p.test() self.assertTrue(res, "Bad parsing") def test_zzz_fini(self): import shutil shutil.rmtree('build_cython')
class GenDsl_Test(unittest.TestCase): def test_000_init(self): pass def test_00_seqchar(self): '''Test sequence and char ''' pass class SeqChar(grammar.Grammar): def test_01_altchar(self): '''Test alternative and char ''' pass class AltChar(grammar.Grammar): def test_02_text(self): '''Test gen text ''' pass class Text(grammar.Grammar): def test_03_number(self): '''Test gen number ''' pass class Number(grammar.Grammar): def test_03_number2(self): '''Test gen number2 ''' pass class Number2(grammar.Grammar): def test_04_optional(self): '''Test gen optional ''' pass class Optional(grammar.Grammar): def test_05_neg(self): '''Test gen neg ''' pass class Neg(grammar.Grammar): def test_06_complement(self): '''Test gen complement ''' pass class Complement(grammar.Grammar): def test_07_string(self): '''Test gen string ''' pass class String(grammar.Grammar): def test_08_lookahead(self): '''Test gen lookahead ''' pass class LookAhead(grammar.Grammar): def test_09_until(self): '''Test gen until ''' pass class Until(grammar.Grammar): def test_zzz_fini(self): pass
25
11
21
0
19
2
1
0.12
1
11
11
0
13
0
13
85
290
13
248
75
221
29
233
71
206
2
2
1
17
146,131
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/grammar_basic.py
tests.grammar_basic.DummyCpp
class DummyCpp(grammar.Grammar): entry = "main" grammar = """ main =[ @ignore("C/C++") [id:i #add(_, i)]+ ] """
class DummyCpp(grammar.Grammar): pass
1
0
0
0
0
0
0
0.2
1
0
0
0
0
0
0
52
5
0
5
2
4
1
3
2
2
0
6
0
0
146,132
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/grammar_basic.py
tests.grammar_basic.WordList
class WordList(grammar.Grammar): grammar = """ wordlist =[ [word : w #add_to(_, w)]+ eof ] word =[ @ignore("null") ['a'..'z'|'A'..'Z']+ ] """ entry = "wordlist"
class WordList(grammar.Grammar): pass
1
0
0
0
0
0
0
0.17
1
0
0
0
0
0
0
52
7
1
6
2
5
1
3
2
2
0
6
0
0
146,133
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.PeekText
class PeekText(Functor, Leaf): """ !!"TXT" bnf primitive functor. """ def __init__(self, c: str): self.char = c def do_call(self, parser: BasicParser) -> bool: return parser.peek_text(self.char)
class PeekText(Functor, Leaf): ''' !!"TXT" bnf primitive functor. ''' def __init__(self, c: str): pass def do_call(self, parser: BasicParser) -> bool: pass
3
1
2
0
2
0
1
0.2
2
3
1
0
2
1
2
4
8
2
5
4
2
1
5
4
2
1
1
0
2
146,134
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.Range
class Range(Functor, Leaf): """ 'A'..'Z' bnf primitive functor. """ def __init__(self, begin: str, end: str): self.begin = begin self.end = end def do_call(self, parser: BasicParser) -> bool: return parser.read_range(self.begin, self.end)
class Range(Functor, Leaf): ''' 'A'..'Z' bnf primitive functor. ''' def __init__(self, begin: str, end: str): pass def do_call(self, parser: BasicParser) -> bool: pass
3
1
3
0
3
0
1
0.17
2
3
1
0
2
2
2
4
9
2
6
5
3
1
6
5
3
1
1
0
2
146,135
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.Rep0N
class Rep0N(Functor): """ []* bnf primitive as a functor. """ def __init__(self, pt: Seq): Functor.__init__(self) self.pt = pt if (isinstance(self.pt, Text) or isinstance(self.pt, Char) or isinstance(self.pt, Range) or isinstance(self.pt, Directive) ): self.pt = Seq(self.pt) def do_call(self, parser: BasicParser) -> bool: parser._stream.save_context() parser.push_rule_nodes() while self.pt(parser): pass parser.pop_rule_nodes() return parser._stream.validate_context()
class Rep0N(Functor): ''' []* bnf primitive as a functor. ''' def __init__(self, pt: Seq): pass def do_call(self, parser: BasicParser) -> bool: pass
3
1
7
0
7
0
2
0.07
1
7
6
0
2
1
2
4
18
2
15
4
12
1
13
4
10
2
1
1
4
146,136
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/grammar_decorator.py
tests.grammar_decorator.GrammarDecorator_Test
class GrammarDecorator_Test(unittest.TestCase): def test_01_trace_failure(self): """ Test @trace decorator directive """ source = "word" l = TraceSimple(source, raise_diagnostic=False) res = l.parse() trace = "" with open("logfile") as flog: trace = flog.read() os.remove("logfile") self.assertFalse(res, "Did not fail to parse TraceSimple") self.assertEqual(trace, "[space] Entering\n" + "[space] Failed\n" + "[ponctuation] Entering\n" + "[ponctuation] Failed\n" + "[word] Entering\n" + "[word] Failed\n", "Trace doesn't match expected result.") def test_02_trace_success(self): """ Test @trace decorator directive """ source = " " l = TraceSimple(source) res = l.parse() trace = "" with open("logfile") as flog: trace = flog.read() os.remove("logfile") self.assertTrue(res, "Failed to parse TraceSimple") self.assertEqual(trace, "[space] Entering\n" + "[space] Succeeded\n" + "[space] Entering\n" + "[space] Failed\n" + "[ponctuation] Entering\n" + "[ponctuation] Failed\n" + "[word] Entering\n" + "[word] Failed\n" + "[eof] Entering\n" + "[eof] Succeeded\n", "Trace doesn't match expected result.")
class GrammarDecorator_Test(unittest.TestCase): def test_01_trace_failure(self): ''' Test @trace decorator directive ''' pass def test_02_trace_success(self): ''' Test @trace decorator directive ''' pass
3
2
24
2
19
3
1
0.15
1
1
1
0
2
0
2
74
50
5
39
13
36
6
21
11
18
1
2
1
2
146,137
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/grammar_decorator.py
tests.grammar_decorator.TraceSimple
class TraceSimple(grammar.Grammar): grammar = """ root = [ @ignore("null") @trace("logfile") [ space | ponctuation | word ]+ eof ] space = [ ' ' ] word = [ 'This' | 'is' | 'a' | 'warning' ] ponctuation = [ '!' | '.' | '?' ] """ entry = "root"
class TraceSimple(grammar.Grammar): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
14
4
10
2
9
0
3
2
2
0
1
0
0
146,138
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/grammar_basic.py
tests.grammar_basic.DumCsv
class DumCsv(grammar.Grammar): entry = "csv" grammar = """ csv =[ @ignore("null") [line:l eol #rows(_, l)]+ [line:l #rows(_, l)]? eof ] line = [ item:i #cols(_, i) [';' item:i #cols(_, i)]* ] item = [ [~[';'|eol]]* ] """
class DumCsv(grammar.Grammar): pass
1
0
0
0
0
0
0
0.23
1
0
0
0
0
0
0
52
15
2
13
2
12
3
3
2
2
0
6
0
0
146,139
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.Functor
class Functor: """ Dummy Base class for all parse tree classes. common property: pt if contain a Functor ptlist if contain a list of Functor """ def do_call(self, parser: BasicParser) -> Node: pass def __call__(self, parser: BasicParser) -> Node: global _decorators # call the begin methods in order for i in range(0, len(_decorators)): _decorators[i].begin(parser, self) # forward the call to the functor res = self.do_call(parser) # call the end methods in reverse order for i in range(len(_decorators) - 1, -1, -1): _decorators[i].end(res, parser, self) return res
class Functor: ''' Dummy Base class for all parse tree classes. common property: pt if contain a Functor ptlist if contain a list of Functor ''' def do_call(self, parser: BasicParser) -> Node: pass def __call__(self, parser: BasicParser) -> Node: pass
3
1
7
0
5
2
2
0.73
0
3
2
30
2
0
2
2
22
3
11
6
7
8
11
6
7
3
0
1
4
146,140
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/type_system/var.py
pyrser.type_system.var.Var
class Var(Signature): """ Describe a variable signature for the language """ def __init__(self, name: str, tret: str): super().__init__(name) if not isinstance(tret, TypeName): tret = TypeName(tret) self.tret = tret @property def is_polymorphic(self) -> bool: return self.tret.is_polymorphic @property def is_var(self) -> bool: return True def internal_name(self): """ Return the unique internal name """ unq = 'v_' + super().internal_name() if self.tret is not None: unq += "_" + self.tret return unq def __str__(self) -> str: import pyrser.type_system.to_fmt return str(self.to_fmt())
class Var(Signature): ''' Describe a variable signature for the language ''' def __init__(self, name: str, tret: str): pass @property def is_polymorphic(self) -> bool: pass @property def is_var(self) -> bool: pass def internal_name(self): ''' Return the unique internal name ''' pass def __str__(self) -> str: pass
8
2
4
0
3
1
1
0.3
1
4
1
0
5
1
5
17
31
5
20
11
11
6
18
9
11
2
2
1
7
146,141
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/type_system/type_name.py
pyrser.type_system.type_name.TypeName
class TypeName(str): def __init__(self, value): super().__init__() self.value = value # split value into composed type and/or qualifiers self.components = value.split() def __str__(self) -> str: return self.value def __hash__(self) -> int: return self.value.__hash__() def __lt__(self, oth) -> bool: if isinstance(oth, TypeName): return self.value < oth.value return self.value < oth def __eq__(self, oth) -> bool: if isinstance(oth, TypeName): return self.value == oth.value return self.value == oth def get_subcomponents(self) -> list: return self.components[1:] @property def is_polymorphic(self) -> bool: """ Check if one of composed type name is poly """ for c in self.components: if c[0] == '?': return True return False
class TypeName(str): def __init__(self, value): pass def __str__(self) -> str: pass def __hash__(self) -> int: pass def __lt__(self, oth) -> bool: pass def __eq__(self, oth) -> bool: pass def get_subcomponents(self) -> list: pass @property def is_polymorphic(self) -> bool: ''' Check if one of composed type name is poly ''' pass
9
1
4
0
3
1
2
0.16
1
4
0
0
7
2
7
73
36
7
25
12
16
4
24
11
16
3
2
2
11
146,142
LionelAuroux/pyrser
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LionelAuroux_pyrser/tests/grammar_directive.py
tests.grammar_directive.GrammarDirective_Test
class GrammarDirective_Test(unittest.TestCase): def test_01_ignore_null(self): """ Test @ignore("null") directive """ @meta.hook(IgnoreNull) def add_to(self, mylist, item): if not hasattr(mylist, 'lst'): mylist.lst = [self.value(item)] else: mylist.lst.append(self.value(item)) return True source = "a\nb\tc d\vF." l = IgnoreNull(source) res = l.parse() self.assertTrue(res, "Failed to parse IgnoreNull") self.assertEqual(len(res.lst), len(source), "failed to retrieve {} tokens".format(len(source))) def test_02_ignore_blank(self): """ Test @ignore("blank") directive """ @meta.hook(IgnoreBlanks) def add_to(self, mylist, item): if not hasattr(mylist, 'lst'): mylist.lst = [self.value(item)] else: mylist.lst.append(self.value(item)) return True source = "a\nb\tc d\vF\f.\r!\b" l = IgnoreBlanks(source) res = l.parse() self.assertTrue(res, "Failed to parse IgnoreBlanks") self.assertEqual(len(res.lst), 8, "failed to retrieve 8 tokens") self.assertEqual(res.lst[6], "!", "Failed to reach lst[6]") def test_03_ignore_cpp(self): """ Test @ignore("C/C++") directive """ @meta.hook(IgnoreCPP) def init(self, mylist): mylist.lst = [] return True @meta.hook(IgnoreCPP) def add_to(self, mylist, item): mylist.lst.append(self.value(item)) return True source = """/* Only enclosed */""" expected = [] l = IgnoreCPP(source) res = l.parse() self.assertTrue(res, "Failed to parse CPP enclosed-comment only") self.assertEqual(len(res.lst), len(expected), "Found tokens when none expected") self.assertEqual(res.lst, expected, "Result didn't match expected result") def test_04_ignore_cpp(self): """ Test @ignore("C/C++") directive """ @meta.hook(IgnoreCPP) def init_ignore(self, mylist): mylist.lst = [] return True @meta.hook(IgnoreCPP) def add_to2(self, mylist, item): mylist.lst.append(self.value(item)) return True source = """// Only double slash """ expected = [] l = IgnoreCPP(source) res = l.parse() self.assertTrue(res, "Failed to parse CPP double-slash comment only") self.assertEqual(len(res.lst), len(expected), "Found tokens when none expected") self.assertEqual(res.lst, expected, "Result didn't match expected result") def test_05_ignore_cpp(self): """ Test @ignore("C/C++") directive """ @meta.hook(IgnoreCPP) def init_ignore2(self, mylist): mylist.lst = [] return True @meta.hook(IgnoreCPP) def add_to3(self, mylist, item): mylist.lst.append(self.value(item)) return True source = """ /* * This is * a simple * multiline comment */ """ expected = [] l = IgnoreCPP(source) res = l.parse() self.assertTrue(res, "Failed to parse CPP multi-line comment only") self.assertEqual(len(res.lst), len(expected), "Found tokens when none expected") self.assertEqual(res.lst, expected, "Result didn't match expected result") def test_08_ignore_cpp(self): """ Test @ignore("C/C++") directive """ @meta.hook(IgnoreCPP) def init_ignore4(self, mylist): mylist.lst = [] return True @meta.hook(IgnoreCPP) def add_to5(self, mylist, item): mylist.lst.append(self.value(item)) return True source = """ int pouet paf /* inline comment */ pouf int pouet paf pouf //end comment paf/* int pouet */pouf int pouet/*paf*/pouf //test qui /* pouet paf */ // Test int/* * Multi-line * comment */test test end /*last comment for the road*/""" expected = ["int", "pouet", "paf", "pouf", "int", "pouet", "paf", "pouf", "paf", "pouf", "int", "pouet", "pouf", "int", "test", "test", "end"] l = IgnoreCPP(source) res = l.parse() self.assertTrue(res, "Failed to parse IgnoreBlanks") self.assertEqual(len(res.lst), len(expected), "failed to retrieve {} tokens".format(len(expected))) self.assertEqual(res.lst, expected, "Result didn't match expected result")
class GrammarDirective_Test(unittest.TestCase): def test_01_ignore_null(self): ''' Test @ignore("null") directive ''' pass @meta.hook(IgnoreNull) def add_to(self, mylist, item): pass def test_02_ignore_blank(self): ''' Test @ignore("blank") directive ''' pass @meta.hook(IgnoreBlanks) def add_to(self, mylist, item): pass def test_03_ignore_cpp(self): ''' Test @ignore("C/C++") directive ''' pass @meta.hook(IgnoreCPP) def init(self, mylist): pass @meta.hook(IgnoreCPP) def add_to(self, mylist, item): pass def test_04_ignore_cpp(self): ''' Test @ignore("C/C++") directive ''' pass @meta.hook(IgnoreCPP) def init_ignore(self, mylist): pass @meta.hook(IgnoreCPP) def add_to2(self, mylist, item): pass def test_05_ignore_cpp(self): ''' Test @ignore("C/C++") directive ''' pass @meta.hook(IgnoreCPP) def init_ignore2(self, mylist): pass @meta.hook(IgnoreCPP) def add_to3(self, mylist, item): pass def test_08_ignore_cpp(self): ''' Test @ignore("C/C++") directive ''' pass @meta.hook(IgnoreCPP) def init_ignore4(self, mylist): pass @meta.hook(IgnoreCPP) def add_to5(self, mylist, item): pass
27
6
12
1
10
1
1
0.14
1
3
3
0
6
0
6
78
158
15
125
49
98
18
80
39
63
2
2
1
18
146,143
LionelAuroux/pyrser
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LionelAuroux_pyrser/tests/pyrser/test_meta.py
tests.pyrser.test_meta.TestAddMethod.test_it_attach_method_to_class.cls
class cls: pass
class cls: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
1
1
0
2
1
1
0
0
0
0
146,144
LionelAuroux/pyrser
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LionelAuroux_pyrser/tests/pyrser/test_meta.py
tests.pyrser.test_meta.TestAddMethod.test_it_does_not_attach_method_if_attribute_exists.cls
class cls: def method(self): pass
class cls: def method(self): pass
2
0
2
0
2
0
1
0
0
0
0
0
1
0
1
1
3
0
3
2
1
0
3
2
1
1
0
0
1
146,145
LionelAuroux/pyrser
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LionelAuroux_pyrser/tests/pyrser/test_meta.py
tests.pyrser.test_meta.TestRule.test_it_does_not_attach_a_rule_if_method_already_exist.cls
class cls: _rules = {} def method(self): pass
class cls: def method(self): pass
2
0
2
0
2
0
1
0
0
0
0
0
1
0
1
1
5
1
4
3
2
0
4
3
2
1
0
0
1
146,146
LionelAuroux/pyrser
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LionelAuroux_pyrser/tests/grammar_basic.py
tests.grammar_basic.GrammarBasic_Test.test_30_read_until.Exemple
class Exemple(grammar.Grammar): entry = 'exemple' grammar = """ exemple = [ [broken_read_until:res #dump(res) ]+ eof ] """
class Exemple(grammar.Grammar): pass
1
0
0
0
0
0
0
0.2
1
0
0
0
0
0
0
52
5
0
5
2
4
1
3
2
2
0
6
0
0
146,147
LionelAuroux/pyrser
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LionelAuroux_pyrser/tests/grammar_basic.py
tests.grammar_basic.GrammarBasic_Test
class GrammarBasic_Test(unittest.TestCase): def test_01_list_word(self): """ Test List Word """ @meta.hook(WordList, erase=True) def add_to(self, mylist, word): if not hasattr(mylist, 'lst'): mylist.lst = [self.value(word)] else: mylist.lst.append(self.value(word)) return True ws = WordList("ab cd ef gh") res = ws.parse() self.assertTrue(res, "failed to parse WordList") self.assertEqual(res.lst[2], "ef", "failed to reach lst[2]") def test_02_csv(self): """ Test CSV """ @meta.hook(CSV) def add_line(self, csv, l): if not hasattr(csv, 'tab'): csv.tab = [l.cols] else: csv.tab.append(l.cols) return True @meta.hook(CSV, erase=True) def add_col(self, line, c): if not hasattr(line, 'cols'): line.cols = [c.value] else: line.cols.append(c.value) return True @meta.hook(CSV) def add_item(self, item, i): item.value = self.value(i) return True csv = CSV() if csv: txt = """ 1;a;3;b;5 l;r o 4;1 7;u;p """ res = csv.parse(txt) self.assertTrue(res, "failed to parse CSV") self.assertEqual(res.tab[2][0], "o", "failed to reach tab[2][0]") self.assertEqual(res.tab[4][1], "u", "failed to reach tab[4][1]") def test_03_inherit_csv(self): """ Test CSV2 """ @meta.hook(CSV2, erase=True) def add_col(self, line, c): colval = '' if hasattr(c, 'value'): colval = c.value if not hasattr(line, 'cols'): line.cols = [colval] else: line.cols.append(colval) return True csv2 = CSV2() res = csv2.parse(""" 3;;2;;1 ; ;1 6;;8 """) self.assertTrue(res, "failed to parse CSV2") self.assertEqual(res.tab[0][2], "2", "failed to reach tab[0][2]") self.assertEqual(res.tab[1][0], "", "failed to reach tab[1][0] as empty string") self.assertEqual(res.tab[1][1], "", "failed to reach tab[1][1] as empty string") def test_04_parse_error_csv(self): """ Test parser error in CSV """ content = """ 1;2;3;4 8;9;10;11 a;b;c;';4;5 o;l;p """ csv = CSV(raise_diagnostic=False) res = csv.parse(content) self.assertFalse(res, "Failed to detect the error") s = res.diagnostic.get_content() self.assertEqual( res.diagnostic.logs[0].msg, "Parse error in 'eof'", "Bad message in Diagnostic" ) self.assertEqual( res.diagnostic.logs[0].location.line, 4, "Bad line in Diagnostic" ) self.assertEqual( res.diagnostic.logs[0].location.col, 19, "Bad line in Diagnostic" ) csv = CSV() with self.assertRaises(error.Diagnostic) as e: res = csv.parse(content) exp = '' try: res = csv.parse(content) except error.Diagnostic as e: exp = e.logs[0].msg self.assertEqual( exp, "Parse error in 'eof'", "Bad message in Diagnostic" ) def test_05_parse_error_dsl(self): """ Test parser error in the DSL """ with self.assertRaises(error.Diagnostic) as pe: class TestDsl(grammar.Grammar): grammar = """ not_finished_bnf""" entry = "not_finished_bnf" self.assertEqual(pe.exception.logs[0].msg, "Expected '='", "failed to get the correct message") self.assertEqual(pe.exception.logs[0].location.col, 37, "failed to get the correct position") def test_06_parse_error_dsl(self): """ Test parser error in the DSL """ with self.assertRaises(error.Diagnostic) as pe: class TestDsl(grammar.Grammar): grammar = """ not_finished_bnf = [ clause""" entry = "not_finished_bnf" self.assertEqual(pe.exception.logs[0].msg, "Expected ']'", "failed to get the correct message") self.assertEqual(pe.exception.logs[0].location.col, 48, "failed to get the correct position") def test_07_parse_error_dsl(self): """ Test parser error in the DSL """ with self.assertRaises(error.Diagnostic) as pe: class TestDsl(grammar.Grammar): grammar = """ not_finished_bnf =[ #hook(12""" entry = "not_finished_bnf" self.assertEqual(pe.exception.logs[0].msg, "Expected ')'", "failed to get the correct message") self.assertEqual(pe.exception.logs[0].location.col, 49, "failed to get the correct position") def test_08_parse_error_dsl(self): """ Test parser error in the DSL """ with self.assertRaises(error.Diagnostic) as pe: class TestDsl(grammar.Grammar): grammar = """ not_finished_bnf = [ @dir(12""" entry = "not_finished_bnf" self.assertEqual(pe.exception.logs[0].msg, "Expected ')'", "failed to get the correct message") self.assertEqual(pe.exception.logs[0].location.col, 49, "failed to get the correct position") def test_09_parse_error_dsl(self): """ Test parser error in the DSL """ with self.assertRaises(error.Diagnostic) as pe: class TestDsl(grammar.Grammar): grammar = """ not_finished_bnf =[ #hook(12,""" entry = "not_finished_bnf" self.assertEqual(pe.exception.logs[0].msg, "Expected parameter", "failed to get the correct message") self.assertEqual(pe.exception.logs[0].location.col, 50, "failed to get the correct position") def test_10_parse_error_dsl(self): """ Test parser error in the DSL """ with self.assertRaises(error.Diagnostic) as pe: class TestDsl(grammar.Grammar): grammar = """ not_finished_bnf =[ #hook(""" entry = "not_finished_bnf" self.assertEqual(pe.exception.logs[0].msg, "Expected ')'", "failed to get the correct message") self.assertEqual(pe.exception.logs[0].location.col, 47, "failed to get the correct position") def test_11_parse_error_dsl(self): """ Test parser error in the DSL """ with self.assertRaises(error.Diagnostic) as pe: class TestDsl(grammar.Grammar): grammar = """ not_finished_bnf =[ @dir(12,""" entry = "not_finished_bnf" self.assertEqual(pe.exception.logs[0].msg, "Expected parameter", "failed to get the correct message") self.assertEqual(pe.exception.logs[0].location.col, 49, "failed to get the correct position") def test_12_parse_error_dsl(self): """ Test parser error in the DSL """ with self.assertRaises(error.Diagnostic) as pe: class TestDsl(grammar.Grammar): grammar = """ not_finished_bnf =[ @dir(""" entry = "not_finished_bnf" self.assertEqual(pe.exception.logs[0].msg, "Expected parameter", "failed to get the correct message") self.assertEqual(pe.exception.logs[0].location.col, 46, "failed to get the correct position") def test_13_parse_error_dsl(self): """ Test parser error in the DSL """ with self.assertRaises(error.Diagnostic) as pe: class TestDsl(grammar.Grammar): grammar = """ not_finished_bnf =[ [a""" entry = "not_finished_bnf" self.assertEqual(pe.exception.logs[0].msg, "Expected ']'", "failed to get the correct message") self.assertEqual(pe.exception.logs[0].location.col, 43, "failed to get the correct position") def test_14_parse_error_dsl(self): """ Test parser error in the DSL """ with self.assertRaises(error.Diagnostic) as pe: class TestDsl(grammar.Grammar): grammar = """ not_finished_bnf =[ [""" entry = "not_finished_bnf" self.assertEqual(pe.exception.logs[0].msg, "Expected sequences", "failed to get the correct message") self.assertEqual(pe.exception.logs[0].location.col, 42, "failed to get the correct position") def test_15_ignore_cpp(self): """ Test ignore directive for C/C++ """ @meta.hook(DummyCpp) def add(self, ast, i): ast.last = self.value(i) return True cxx = DummyCpp() res = cxx.parse(""" a b c /* comment */ // another comment d e/**/f// g """) self.assertTrue(res, "failed to parse dummyCpp") self.assertEqual(res.last, 'g', "failed to parse comments") def test_28_extra_complement(self): @meta.hook(DumCsv) def cols(self, ast, p): if not hasattr(ast, 'cols'): ast.cols = [] ast.cols.append(self.value(p).strip()) return True @meta.hook(DumCsv) def rows(self, ast, p): if not hasattr(ast, 'lines'): ast.lines = [] ast.lines.append(p.cols) return True bnf = DumCsv(""" 21;21;32;212;31;231;3 1231;3;123;123;12;312;31 ;123;12312;312;312;31 1;23;123;123;123;12;;123;12;3 3123;123;--;12 """) # with dummyData as s: res = bnf.parse() self.assertEqual(res.lines[5][2], '--', "failed to parse correctly with ~") def test_29_parse_file(self): @meta.hook(WordList, erase=True) def add_to(self, mylist, word): return True ws = WordList() with self.assertRaises(FileNotFoundError) as ve: res = ws.parse_file("test.ws") res = ws.parse_file("tests/files/test.ws") def test_30_read_until(self): a = 0 class Exemple(grammar.Grammar): entry = 'exemple' grammar = """ exemple = [ [broken_read_until:res #dump(res) ]+ eof ] """ @meta.rule(Exemple) def broken_read_until(self): return self.read_until('\n', r"\\") @meta.hook(Exemple) def dump(self, stuff): nonlocal a elem = ['stuff on \\\n', 'multiple \\\\\\\n', 'line\n'] item = self.value(stuff) self.test.assertTrue( item == elem[a], "Fail to handle correctly read_until. %r != %r" % (item, elem[a])) a += 1 return True ex = Exemple() ex.test = self ex.parse_file('tests/files/test_read_until') self.assertTrue(a == 3, "Fail to parse entirely with read_until")
class GrammarBasic_Test(unittest.TestCase): def test_01_list_word(self): ''' Test List Word ''' pass @meta.hook(WordList, erase=True) def add_to(self, mylist, word): pass def test_02_csv(self): ''' Test CSV ''' pass @meta.hook(CSV) def add_line(self, csv, l): pass @meta.hook(CSV, erase=True) def add_col(self, line, c): pass @meta.hook(CSV) def add_item(self, item, i): pass def test_03_inherit_csv(self): ''' Test CSV2 ''' pass @meta.hook(CSV2, erase=True) def add_col(self, line, c): pass def test_04_parse_error_csv(self): ''' Test parser error in CSV ''' pass def test_05_parse_error_dsl(self): ''' Test parser error in the DSL ''' pass class TestDsl(grammar.Grammar): def test_06_parse_error_dsl(self): ''' Test parser error in the DSL ''' pass class TestDsl(grammar.Grammar): def test_07_parse_error_dsl(self): ''' Test parser error in the DSL ''' pass class TestDsl(grammar.Grammar): def test_08_parse_error_dsl(self): ''' Test parser error in the DSL ''' pass class TestDsl(grammar.Grammar): def test_09_parse_error_dsl(self): ''' Test parser error in the DSL ''' pass class TestDsl(grammar.Grammar): def test_10_parse_error_dsl(self): ''' Test parser error in the DSL ''' pass class TestDsl(grammar.Grammar): def test_11_parse_error_dsl(self): ''' Test parser error in the DSL ''' pass class TestDsl(grammar.Grammar): def test_12_parse_error_dsl(self): ''' Test parser error in the DSL ''' pass class TestDsl(grammar.Grammar): def test_13_parse_error_dsl(self): ''' Test parser error in the DSL ''' pass class TestDsl(grammar.Grammar): def test_14_parse_error_dsl(self): ''' Test parser error in the DSL ''' pass class TestDsl(grammar.Grammar): def test_15_ignore_cpp(self): ''' Test ignore directive for C/C++ ''' pass @meta.hook(DummyCpp) def add_to(self, mylist, word): pass def test_28_extra_complement(self): pass @meta.hook(DumCsv) def cols(self, ast, p): pass @meta.hook(DumCsv) def rows(self, ast, p): pass def test_29_parse_file(self): pass @meta.hook(WordList, erase=True) def add_to(self, mylist, word): pass def test_30_read_until(self): pass class Exemple(grammar.Grammar): @meta.rule(Exemple) def broken_read_until(self): pass @meta.hook(Exemple) def dump(self, stuff): pass
52
15
13
0
11
2
1
0.18
1
7
6
0
18
0
18
90
346
26
274
99
221
50
182
76
140
3
2
1
38