Beispiel #1
0
	def gen_code(self, file_name):
		ensem_name = self.exec_dec.name

		extern_dec_codes = []
		for e in self.get_extern_decs():
			extern_dec_codes.append( ExternDecCodeGen(e).gen_code() )

		import_list = compile_template( template('''
			from msr_ensemble.interpret.mpi_runtime import execute_msr
			from msr_ensemble.facts.location import loc

			{| '\\n'.join( extern_dec_codes ) |}

			from {| ensem_name |} import *
		'''), ensem_name=ensem_name, extern_dec_codes=extern_dec_codes)

		assign_dec_codes = []
		for a in self.get_assign_decs():
			assign_dec_codes.append( AssignDecCodeGen(a).gen_code() )		

		locs = {}
		for loc in self.exec_dec.locs:
			locs[loc] = []

		for init in self.get_init_decs():
			loc = init.name
			fact_strs = []
			for fact in init.facts:
				fact_strs.append( LocFactCodeGen(ast.FactLoc(ast.TermCons(loc),[fact])).gen_code() )
			locs[loc] = ', '.join(fact_strs)

		count = 0
		loc_assigns    = []
		loc_inits      = []
		loc_init_names = []
		for loc in locs:
			loc_assigns.append( "%s = lift(loc(%s))" % (loc,count) )
			loc_inits.append( "init_%s = [%s]" % (loc,locs[loc]) )
			loc_init_names.append( "init_%s" % loc )
			count += 1

		exec_dec_code = template('''
			{| import_list |}

			{| '\\n'.join(assign_dec_codes) |}

			{| '\\n'.join(loc_assigns) |}

			{| '\\n'.join(loc_inits) |}

			init_goals = {| ' + '.join(loc_init_names) |}

			execute_msr(init_goals, {| ensem_name |}_rule_classes)
		''')

		output = open(file_name, 'w')

		output.write( compile_template(exec_dec_code, ensem_name=ensem_name, loc_assigns=loc_assigns, loc_inits=loc_inits
                                              ,loc_init_names=loc_init_names, import_list=import_list, assign_dec_codes=assign_dec_codes) )
Beispiel #2
0
    def gen_code(self):
        loc = self.loc_fact.loc
        fact = self.loc_fact.facts[0]
        priority = self.loc_fact.priority

        # loc_str   = self.gen_term_code(loc, inst=inst)
        loc_str = TermCodeGen(loc).gen_code(TERM_LEVEL)
        pred_str = pred_name(fact.name)
        # term_strs = map(lambda t: self.gen_term_code(t, inst=inst), fact.terms)

        term_strs = []
        for term in fact.terms:
            term_strs.append(TermCodeGen(term).gen_code(TERM_LEVEL))

        fact_code = template(
            "{| pred_str |}({| ','.join(term_strs) |}) |at| {| loc_str |}")

        gen_fact_code = compile_template(fact_code,
                                         pred_str=pred_str,
                                         term_strs=term_strs,
                                         loc_str=loc_str)

        if priority == 0:
            return gen_fact_code
        else:
            return "(%s) |priority| %s" % (gen_fact_code, priority)
Beispiel #3
0
	def gen_code(self):
		
		extern_funcs = []
		for (name,type) in self.extern_dec.type_sigs:
			extern_funcs.append( name )

		extern_code = template('''
			from {| extern_mod_name |} import {| ','.join(extern_funcs) |} 
		''')

		return compile_template(extern_code, extern_mod_name=self.extern_dec.name, extern_funcs=extern_funcs)
Beispiel #4
0
	def gen_code(self):

		extern_codes = []
		for e in self.get_extern_decs():
			extern_codes.append( ExternDecCodeGen(e).gen_code() )

		fact_dec_codes = []
		fs = self.get_fact_decs()
		for f in fs:
			fact_dec_codes.append( FactDecCodeGen(f, self.source_text).gen_code() )

		rule_names = []
		rule_dec_codes = []
		rs = self.get_rule_decs()
		for r in rs:
			rule_dec_codes.append( RuleDecCodeGen(r, self.source_text).gen_code() )
			rule_names.append( mk_rule_name(r.name) )

		assign_dec_codes = []
		ass = self.get_assign_decs()
		for a in ass:
			assign_dec_codes.append( AssignDecCodeGen(a).gen_code() )

		import_list = template('''
			from msr_ensemble.facts.fact import Fact, get_all_fact_classes

			from msr_ensemble.facts.term import Term, new_vars, lift, val, inst, _
			from msr_ensemble.facts.fact import Fact, register_fact, at, priority
			from msr_ensemble.facts.guard import Guard
			
			from msr_ensemble.rules.rule import Rule, register_rule

			from msr_ensemble.context.store import FactStore, pretty_stores
		''')

		ensem_code = template('''
			{| import_list |}

			{| '\\n'.join(extern_codes) |}

			{| '\\n'.join(assign_dec_codes) |}

			{| '\\n'.join(fact_dec_codes) |}

			{| '\\n\\n'.join(rule_dec_codes) |}

			{| ensem_name |}_rule_classes = [{| ', '.join(rule_names) |}]
		''') 

		output = open(self.ensem_dec.name + ".py", 'w')
		output.write( compile_template(ensem_code, fact_dec_codes=fact_dec_codes, rule_dec_codes=rule_dec_codes, import_list=import_list
                                              ,ensem_name=self.ensem_dec.name, rule_names=rule_names, assign_dec_codes=assign_dec_codes
                                              ,extern_codes=extern_codes ) )
Beispiel #5
0
    def gen_code(self):

        extern_funcs = []
        for (name, type) in self.extern_dec.type_sigs:
            extern_funcs.append(name)

        extern_code = template('''
			from {| extern_mod_name |} import {| ','.join(extern_funcs) |} 
		''')

        return compile_template(extern_code,
                                extern_mod_name=self.extern_dec.name,
                                extern_funcs=extern_funcs)
Beispiel #6
0
	def gen_code(self):
		num_of_terms = self.count_terms(self.fact_dec)		
		terms = self.next_vars(num_of_terms)
		fact_dec_code = template('''
			\'\'\'
			{| source_snippet |}
			\'\'\'
			class {|fact_name|}(Fact):
				def __init__(self, {| ', '.join(terms) |}):
					self.initialize({| ', '.join(terms) |})
			register_fact({|fact_name|})
		''')
	
		source_snippet = self.fact_dec.gen_snippet(self.source_text)

		return compile_template(fact_dec_code, fact_name=pred_name(self.fact_dec.name), terms=terms
                                       ,source_snippet=source_snippet)
Beispiel #7
0
    def gen_code(self):
        num_of_terms = self.count_terms(self.fact_dec)
        terms = self.next_vars(num_of_terms)
        fact_dec_code = template('''
			\'\'\'
			{| source_snippet |}
			\'\'\'
			class {|fact_name|}(Fact):
				def __init__(self, {| ', '.join(terms) |}):
					self.initialize({| ', '.join(terms) |})
			register_fact({|fact_name|})
		''')

        source_snippet = self.fact_dec.gen_snippet(self.source_text)

        return compile_template(fact_dec_code,
                                fact_name=pred_name(self.fact_dec.name),
                                terms=terms,
                                source_snippet=source_snippet)
Beispiel #8
0
	def gen_code(self):
		loc  = self.loc_fact.loc
		fact = self.loc_fact.facts[0]
		priority = self.loc_fact.priority

		# loc_str   = self.gen_term_code(loc, inst=inst)
		loc_str = TermCodeGen(loc).gen_code(TERM_LEVEL)
		pred_str  = pred_name(fact.name)
		# term_strs = map(lambda t: self.gen_term_code(t, inst=inst), fact.terms)

		term_strs = []
		for term in fact.terms:
			 term_strs.append( TermCodeGen(term).gen_code(TERM_LEVEL) )

		fact_code = template("{| pred_str |}({| ','.join(term_strs) |}) |at| {| loc_str |}")

		gen_fact_code = compile_template(fact_code, pred_str=pred_str, term_strs=term_strs, loc_str=loc_str)

		if priority == 0:
			return gen_fact_code
		else:
			return "(%s) |priority| %s" % (gen_fact_code,priority)
Beispiel #9
0
    def gen_code(self):
        vars = map(var_name, self.get_vars(self.rule_dec))

        props = self.gen_facts(map(lambda f: f.elem, self.rule_dec.plhs))
        simps = self.gen_facts(map(lambda f: f.elem, self.rule_dec.slhs))
        grds = map(lambda g: TermCodeGen(g).gen_code(IGNORE),
                   self.rule_dec.grd)

        rhs_atoms, rhs_comps = self.partition_rhs(self.rule_dec.rhs)
        consq = self.gen_facts(map(lambda f: f.elem, rhs_atoms))

        if len(rhs_comps) > 0:
            comp_set_names = []
            comp_codes = []
            comp_idx = 0
            for comp in rhs_comps:
                comp_facts = self.gen_facts(comp.elem.facts)
                term_pat = TermCodeGen(comp.elem.term_pat).gen_code(
                    IGNORE, inner=IGNORE)
                # term_subj  = TermCodeGen(comp.elem.term_subj).gen_code(META_LEVEL)
                term_subj = TermCodeGen(
                    comp.elem.term_subj).gen_code(META_LEVEL)
                wrapper_pat = "lambda t: %s" % (AssignDecCodeGen(
                    None).get_exp_wrapper(comp.elem.term_pat) % "t")
                term_subj = "map(%s,%s)" % (wrapper_pat, term_subj)
                comp_set_name = "comp_set_%s" % comp_idx
                comp_code = compile_template(template('''
					{| comp_set_name |} = []
					for {| term_pat |} in {| term_subj |}:
						{| comp_set_name |} += [{| ', '.join(comp_facts) |}]
				'''),
                                             term_pat=term_pat,
                                             term_subj=term_subj,
                                             comp_set_name=comp_set_name,
                                             comp_facts=comp_facts)
                comp_set_names.append(comp_set_name)
                comp_codes.append(comp_code)
                comp_idx += 1
            comp_set_post_fix = " + " + ' + '.join(comp_set_names)
        else:
            comp_codes = []
            comp_set_post_fix = ""

        wheres = []
        for assign in self.rule_dec.where:
            wheres.append(AssignDecCodeGen(assign).gen_code())

        grd_class = ""
        grd_inst = ""
        if len(grds) > 0:
            grd_inst = mk_rule_name(
                self.rule_dec.name) + "Grd(%s)" % ','.join(vars)
            grd_class = compile_template(
                template('''
				class {| grd_class_name |}(Guard):
					def __init__(self, {| ', '.join(vars) |}):
						self.initialize(\"{| grd_class_name |}\",{| ','.join(vars) |})
					def evaluate(self):
						{| ','.join(vars) |} = self.get_vars()
						return {| ' and '.join(grds) |}
				'''),
                grd_class_name=mk_rule_name(self.rule_dec.name) + "Grd",
                vars=vars,
                grds=grds)

        # Generate code to handle existential variables
        inspect = Inspector()

        exists_code = ""
        loc_exist_code = ""
        num_of_loc_exists = 0
        if len(self.rule_dec.exists) > 0:

            rule_rhs_locs = map(
                lambda v: v.name,
                inspect.filter_atoms(map(lambda a: inspect.get_loc(a.elem),
                                         rhs_atoms),
                                     var=True))

            loc_exists = []
            pure_exists = []
            for exist_var in self.rule_dec.exists:
                if exist_var.name in rule_rhs_locs:
                    loc_exists.append(exist_var.name)
                else:
                    pure_exists.append(exist_var.name)

            if len(pure_exists) > 0:
                exists_code = "%s = self.exists(%s)" % (','.join(
                    map(var_name, pure_exists)), len(pure_exists))
            if len(loc_exists) > 0:
                num_of_loc_exists = len(loc_exists)
                loc_exist_code = "%s, = self.exist_locs()" % (','.join(
                    map(var_name, loc_exists)))

        rule_dec_code = template('''
			\'\'\'
			{| source_snippet |}
			\'\'\'
			class {| rule_name |}(Rule):
				def __init__(self):
					self.initialize(forall={| len(vars) |},exist_locs={| num_of_loc_exists |})
				def propagate(self):
					{| ','.join(vars) |} = self.get_vars()
					return [{| ', '.join(props) |}]
				def simplify(self):
					{| ','.join(vars) |} = self.get_vars()
					return [{| ', '.join(simps) |}]
				def guards(self):
					{| ','.join(vars) |} = self.get_vars()
					return [{| grd_inst |}]
				def consequents(self):
					{| ','.join(vars) |} = self.get_vars()
					{| exists_code |}
					{| loc_exist_code |}
					{| '\\n'.join(wheres) |}
					{| '\\n'.join(comp_codes) |}
					return [{| ', '.join(consq) |}] {| comp_set_post_fix |}
			register_rule({| rule_name |})
			 
			{| grd_class |}
		''')

        source_snippet = self.rule_dec.gen_snippet(self.source_text)

        output = compile_template(rule_dec_code,
                                  rule_name=mk_rule_name(self.rule_dec.name),
                                  source_snippet=source_snippet,
                                  vars=vars,
                                  props=props,
                                  simps=simps,
                                  grd_class=grd_class,
                                  grd_inst=grd_inst,
                                  wheres=wheres,
                                  consq=consq,
                                  exists_code=exists_code,
                                  loc_exist_code=loc_exist_code,
                                  num_of_loc_exists=num_of_loc_exists,
                                  comp_codes=comp_codes,
                                  comp_set_post_fix=comp_set_post_fix)

        return compact(output)
Beispiel #10
0
    def gen_code(self, file_name):
        ensem_name = self.exec_dec.name

        extern_dec_codes = []
        for e in self.get_extern_decs():
            extern_dec_codes.append(ExternDecCodeGen(e).gen_code())

        import_list = compile_template(template('''
			from msr_ensemble.interpret.mpi_runtime import execute_msr
			from msr_ensemble.facts.location import loc

			{| '\\n'.join( extern_dec_codes ) |}

			from {| ensem_name |} import *
		'''),
                                       ensem_name=ensem_name,
                                       extern_dec_codes=extern_dec_codes)

        assign_dec_codes = []
        for a in self.get_assign_decs():
            assign_dec_codes.append(AssignDecCodeGen(a).gen_code())

        locs = {}
        for loc in self.exec_dec.locs:
            locs[loc] = []

        for init in self.get_init_decs():
            loc = init.name
            fact_strs = []
            for fact in init.facts:
                fact_strs.append(
                    LocFactCodeGen(ast.FactLoc(ast.TermCons(loc),
                                               [fact])).gen_code())
            locs[loc] = ', '.join(fact_strs)

        count = 0
        loc_assigns = []
        loc_inits = []
        loc_init_names = []
        for loc in locs:
            loc_assigns.append("%s = lift(loc(%s))" % (loc, count))
            loc_inits.append("init_%s = [%s]" % (loc, locs[loc]))
            loc_init_names.append("init_%s" % loc)
            count += 1

        exec_dec_code = template('''
			{| import_list |}

			{| '\\n'.join(assign_dec_codes) |}

			{| '\\n'.join(loc_assigns) |}

			{| '\\n'.join(loc_inits) |}

			init_goals = {| ' + '.join(loc_init_names) |}

			execute_msr(init_goals, {| ensem_name |}_rule_classes)
		''')

        output = open(file_name, 'w')

        output.write(
            compile_template(exec_dec_code,
                             ensem_name=ensem_name,
                             loc_assigns=loc_assigns,
                             loc_inits=loc_inits,
                             loc_init_names=loc_init_names,
                             import_list=import_list,
                             assign_dec_codes=assign_dec_codes))
Beispiel #11
0
    def gen_code(self):

        extern_codes = []
        for e in self.get_extern_decs():
            extern_codes.append(ExternDecCodeGen(e).gen_code())

        fact_dec_codes = []
        fs = self.get_fact_decs()
        for f in fs:
            fact_dec_codes.append(
                FactDecCodeGen(f, self.source_text).gen_code())

        rule_names = []
        rule_dec_codes = []
        rs = self.get_rule_decs()
        for r in rs:
            rule_dec_codes.append(
                RuleDecCodeGen(r, self.source_text).gen_code())
            rule_names.append(mk_rule_name(r.name))

        assign_dec_codes = []
        ass = self.get_assign_decs()
        for a in ass:
            assign_dec_codes.append(AssignDecCodeGen(a).gen_code())

        import_list = template('''
			from msr_ensemble.facts.fact import Fact, get_all_fact_classes

			from msr_ensemble.facts.term import Term, new_vars, lift, val, inst, _
			from msr_ensemble.facts.fact import Fact, register_fact, at, priority
			from msr_ensemble.facts.guard import Guard
			
			from msr_ensemble.rules.rule import Rule, register_rule

			from msr_ensemble.context.store import FactStore, pretty_stores
		''')

        ensem_code = template('''
			{| import_list |}

			{| '\\n'.join(extern_codes) |}

			{| '\\n'.join(assign_dec_codes) |}

			{| '\\n'.join(fact_dec_codes) |}

			{| '\\n\\n'.join(rule_dec_codes) |}

			{| ensem_name |}_rule_classes = [{| ', '.join(rule_names) |}]
		''')

        output = open(self.ensem_dec.name + ".py", 'w')
        output.write(
            compile_template(ensem_code,
                             fact_dec_codes=fact_dec_codes,
                             rule_dec_codes=rule_dec_codes,
                             import_list=import_list,
                             ensem_name=self.ensem_dec.name,
                             rule_names=rule_names,
                             assign_dec_codes=assign_dec_codes,
                             extern_codes=extern_codes))
Beispiel #12
0
	def gen_code(self):
		vars  = map(var_name, self.get_vars(self.rule_dec) )
		
		props = self.gen_facts( map(lambda f: f.elem, self.rule_dec.plhs) )
		simps = self.gen_facts( map(lambda f: f.elem, self.rule_dec.slhs) )
		grds  = map(lambda g: TermCodeGen(g).gen_code(IGNORE), self.rule_dec.grd)

		rhs_atoms,rhs_comps = self.partition_rhs(self.rule_dec.rhs)
		consq = self.gen_facts( map(lambda f: f.elem, rhs_atoms) )

		if len(rhs_comps) > 0:
			comp_set_names = []
			comp_codes = []
			comp_idx = 0
			for comp in rhs_comps:
				comp_facts = self.gen_facts( comp.elem.facts )
				term_pat   = TermCodeGen(comp.elem.term_pat).gen_code(IGNORE, inner=IGNORE)
				# term_subj  = TermCodeGen(comp.elem.term_subj).gen_code(META_LEVEL)
				term_subj = TermCodeGen(comp.elem.term_subj).gen_code(META_LEVEL)
				wrapper_pat = "lambda t: %s" % (AssignDecCodeGen(None).get_exp_wrapper(comp.elem.term_pat) % "t")
				term_subj =  "map(%s,%s)"  % (wrapper_pat ,term_subj)
				comp_set_name = "comp_set_%s" % comp_idx 
				comp_code = compile_template( template('''
					{| comp_set_name |} = []
					for {| term_pat |} in {| term_subj |}:
						{| comp_set_name |} += [{| ', '.join(comp_facts) |}]
				'''), term_pat=term_pat, term_subj=term_subj, comp_set_name=comp_set_name, comp_facts=comp_facts)
				comp_set_names.append( comp_set_name )
				comp_codes.append( comp_code )
				comp_idx += 1
			comp_set_post_fix = " + " + ' + '.join(comp_set_names)
		else:
			comp_codes = []
			comp_set_post_fix = ""

		wheres = []
		for assign in self.rule_dec.where:
			wheres.append( AssignDecCodeGen(assign).gen_code() )

		grd_class = ""
		grd_inst = ""
		if len(grds) > 0:
			grd_inst = mk_rule_name(self.rule_dec.name) + "Grd(%s)" % ','.join(vars)
			grd_class = compile_template(template(
				'''
				class {| grd_class_name |}(Guard):
					def __init__(self, {| ', '.join(vars) |}):
						self.initialize(\"{| grd_class_name |}\",{| ','.join(vars) |})
					def evaluate(self):
						{| ','.join(vars) |} = self.get_vars()
						return {| ' and '.join(grds) |}
				'''
			), grd_class_name=mk_rule_name(self.rule_dec.name) + "Grd", vars=vars, grds=grds)

	
		# Generate code to handle existential variables
		inspect = Inspector()

		exists_code = ""
		loc_exist_code = ""
		num_of_loc_exists = 0
		if len(self.rule_dec.exists) > 0:

			rule_rhs_locs = map(lambda v: v.name, inspect.filter_atoms( map(lambda a: inspect.get_loc(a.elem),rhs_atoms), var=True ) )
			
			loc_exists  = []
			pure_exists = []
			for exist_var in self.rule_dec.exists:
				if exist_var.name in rule_rhs_locs:
					loc_exists.append( exist_var.name )
				else:
					pure_exists.append( exist_var.name )

			if len(pure_exists) > 0:
				exists_code = "%s = self.exists(%s)" % (','.join(map(var_name,pure_exists)),len(pure_exists))
			if len(loc_exists) > 0:
				num_of_loc_exists = len(loc_exists)
				loc_exist_code = "%s, = self.exist_locs()" % (','.join(map(var_name,loc_exists)))

		rule_dec_code = template('''
			\'\'\'
			{| source_snippet |}
			\'\'\'
			class {| rule_name |}(Rule):
				def __init__(self):
					self.initialize(forall={| len(vars) |},exist_locs={| num_of_loc_exists |})
				def propagate(self):
					{| ','.join(vars) |} = self.get_vars()
					return [{| ', '.join(props) |}]
				def simplify(self):
					{| ','.join(vars) |} = self.get_vars()
					return [{| ', '.join(simps) |}]
				def guards(self):
					{| ','.join(vars) |} = self.get_vars()
					return [{| grd_inst |}]
				def consequents(self):
					{| ','.join(vars) |} = self.get_vars()
					{| exists_code |}
					{| loc_exist_code |}
					{| '\\n'.join(wheres) |}
					{| '\\n'.join(comp_codes) |}
					return [{| ', '.join(consq) |}] {| comp_set_post_fix |}
			register_rule({| rule_name |})
			 
			{| grd_class |}
		''')

		source_snippet = self.rule_dec.gen_snippet(self.source_text)

		output = compile_template(rule_dec_code, rule_name=mk_rule_name(self.rule_dec.name),source_snippet=source_snippet
                                         ,vars=vars, props=props, simps=simps, grd_class=grd_class, grd_inst=grd_inst, wheres=wheres
                                         ,consq=consq, exists_code=exists_code, loc_exist_code=loc_exist_code, num_of_loc_exists=num_of_loc_exists
                                         ,comp_codes=comp_codes, comp_set_post_fix=comp_set_post_fix)
	
		return compact(output)
	def one_neighbor_restrict_trans(self, rule_dec):

		inspect = Inspector()

		prop_heads = inspect.get_facts( rule_dec.plhs )
		simp_heads = inspect.get_facts( rule_dec.slhs )

		rule_name = rule_dec.name
		x = rule_dec.primary_loc		
		y = rule_dec.neighbor_fvs.keys()[0]

		x_prop_heads = ','.join(map(lambda f: "[%s]%s" % (x,f.gen_snippet(self.source_text)), inspect.filter_facts( prop_heads, x ) ))
		y_prop_heads = ','.join(map(lambda f: "[%s]%s" % (y,f.gen_snippet(self.source_text)), inspect.filter_facts( prop_heads, y ) ))
		x_simp_heads = ','.join(map(lambda f: "[%s]%s" % (x,f.gen_snippet(self.source_text)), inspect.filter_facts( simp_heads, x ) ))
		y_simp_heads = ','.join(map(lambda f: "[%s]%s" % (y,f.gen_snippet(self.source_text)), inspect.filter_facts( simp_heads, y ) ))

		x_prop_heads = x_prop_heads if len(x_prop_heads) > 0 else "1"
		y_prop_heads = y_prop_heads if len(y_prop_heads) > 0 else "1"
		x_simp_heads = x_simp_heads if len(x_simp_heads) > 0 else "1"
		y_simp_heads = y_simp_heads if len(y_simp_heads) > 0 else "1"

		x_guards = ','.join( map(lambda f: f.gen_snippet(self.source_text), rule_dec.primary_grds) )
		if y in rule_dec.neighbor_grds:
			y_guards = ','.join( map(lambda f: f.gen_snippet(self.source_text), rule_dec.neighbor_grds[y]) ) 
		else:
			y_guards = []
		x_guards = ("| %s" % x_guards) if len(x_guards) > 0 else ""
		y_guards = ("| %s" % y_guards) if len(y_guards) > 0 else ""

		lxs = set(map(lambda t:t.name,rule_dec.primary_fv) + [x])
		lrs = set(map(lambda t:t.name,rule_dec.primary_fv + rule_dec.neighbor_fvs[y]) + [x])
		xs = ','.join( lxs )
		rs = ','.join( lrs )
		xs_types = ','.join( map(lambda _: "int" ,lxs) )
		rs_types = ','.join( map(lambda _: "int" ,lrs) )

		rule_body = ','.join( map(lambda f: f.gen_snippet(self.source_text), inspect.get_facts(rule_dec.rhs) ) )

		'''
		print "Xs: %s" % xs
		print "Rs: %s" % rs
		print "X Guards: %s" % x_guards
		print "Y Guards: %s" % y_guards
		print "X Prop: %s" % x_prop_heads
		print "Y Prop: %s" % y_prop_heads
		print "X Simp: %s" % x_simp_heads
		print "Y Simp: %s" % y_simp_heads
		'''

		if inspect.filter_facts( simp_heads, x ) > 0:
			match_rule_code = template('''
				{| y_prop_heads |},{| y_simp_heads |} \ [{| y_loc |}]{| rule_name |}_req({| xs_args |}) {| y_guards |} --o [{| x_loc |}]{| rule_name |}_match({| rs_args |}) priority 2.
			''')
		else:
			match_rule_code = template('''
				[{| y_loc |}]{| rule_name |}_req({| xs_args |}),{| y_prop_heads |},{| y_simp_heads |} \ 1 {| y_guards |} --o [{| x_loc |}]{| rule_name |}_match({| rs_args |}) priority 2.
			''')
		match_rule = compile_template(match_rule_code, y_loc=y, xs_args=xs, rs_args=rs, y_prop_heads=y_prop_heads, y_simp_heads=y_simp_heads
                                             ,x_loc=x, rule_name=rule_dec.name, y_guards=y_guards)

		# print match_rule

		exists_code = ""
		if len(rule_dec.exists) > 0:
			exists_code = "exists %s." % ( ','.join(map(lambda e: e.name,rule_dec.exists)) )
			# sys.stdout.write("Here: %s" % exists_code)

		zero_nr_code = template('''
			predicate {| rule_name |}_req    :: ({| xs_types |}) -> fact.
			predicate {| rule_name |}_match  :: ({| rs_types |}) -> fact.
			predicate {| rule_name |}_commit :: ({| rs_types |}) -> fact.

			rule {| rule_name |}1  :: {| x_prop_heads |},{| x_simp_heads |} \ 1 {| x_guards |} --o [{| y_loc |}]{| rule_name |}_req({| xs_args |}).
			rule {| rule_name |}2  :: {| match_rule |}
			rule {| rule_name |}3  :: {| x_prop_heads |},{| x_simp_heads |},[{| x_loc |}]{| rule_name |}_match({| rs_args |}) --o [{| y_loc |}]{| rule_name |}_commit({| rs_args |}).
			rule {| rule_name |}4a :: {| y_prop_heads |} \ [{| y_loc |}]{| rule_name |}_commit({| rs_args |}),{| y_simp_heads |} --o {| exists_code |} {| x_prop_heads |},{| rule_body |}.
			rule {| rule_name |}4b :: [{| y_loc |}]{| rule_name |}_commit({| rs_args |}) --o {| x_prop_heads |},{| x_simp_heads |}.
		''')

		zero_nr_rules = compact( compile_template(zero_nr_code, match_rule=match_rule, rule_name=rule_dec.name, x_loc=x, y_loc=y, xs_args=xs, rs_args=rs
                                                         ,x_guards=x_guards, y_guards=y_guards, x_simp_heads=x_simp_heads, y_simp_heads=y_simp_heads
                                                         ,x_prop_heads=x_prop_heads, y_prop_heads=y_prop_heads, exists_code=exists_code, rule_body=rule_body
                                                         ,xs_types=xs_types, rs_types=rs_types) )
		
		# print zero_nr_rules

		msr_code_gen = MSRCodeGen("", bypass_checkers=True, input=zero_nr_rules)

		trans_decs = msr_code_gen.decs

		for dec in trans_decs:
			dec.add_trans_snippet( dec.gen_snippet( zero_nr_rules ) )

		lead_rule_snippet = "One Neighbor Restriction translation applied.\n\nSource rule:\n%s\n\n" % rule_dec.gen_snippet( self.source_text )
		lead_rule_snippet += "Generated fragment:\n%s\n\n" % zero_nr_rules
		lead_rule_snippet += trans_decs[0].gen_snippet( zero_nr_rules )
		trans_decs[0].add_trans_snippet( lead_rule_snippet )

		trans_decs[len(trans_decs)-2].where = rule_dec.where

		return trans_decs
Beispiel #14
0
    def one_neighbor_restrict_trans(self, rule_dec):

        inspect = Inspector()

        prop_heads = inspect.get_facts(rule_dec.plhs)
        simp_heads = inspect.get_facts(rule_dec.slhs)

        rule_name = rule_dec.name
        x = rule_dec.primary_loc
        y = rule_dec.neighbor_fvs.keys()[0]

        x_prop_heads = ','.join(
            map(lambda f: "[%s]%s" % (x, f.gen_snippet(self.source_text)),
                inspect.filter_facts(prop_heads, x)))
        y_prop_heads = ','.join(
            map(lambda f: "[%s]%s" % (y, f.gen_snippet(self.source_text)),
                inspect.filter_facts(prop_heads, y)))
        x_simp_heads = ','.join(
            map(lambda f: "[%s]%s" % (x, f.gen_snippet(self.source_text)),
                inspect.filter_facts(simp_heads, x)))
        y_simp_heads = ','.join(
            map(lambda f: "[%s]%s" % (y, f.gen_snippet(self.source_text)),
                inspect.filter_facts(simp_heads, y)))

        x_prop_heads = x_prop_heads if len(x_prop_heads) > 0 else "1"
        y_prop_heads = y_prop_heads if len(y_prop_heads) > 0 else "1"
        x_simp_heads = x_simp_heads if len(x_simp_heads) > 0 else "1"
        y_simp_heads = y_simp_heads if len(y_simp_heads) > 0 else "1"

        x_guards = ','.join(
            map(lambda f: f.gen_snippet(self.source_text),
                rule_dec.primary_grds))
        if y in rule_dec.neighbor_grds:
            y_guards = ','.join(
                map(lambda f: f.gen_snippet(self.source_text),
                    rule_dec.neighbor_grds[y]))
        else:
            y_guards = []
        x_guards = ("| %s" % x_guards) if len(x_guards) > 0 else ""
        y_guards = ("| %s" % y_guards) if len(y_guards) > 0 else ""

        lxs = set(map(lambda t: t.name, rule_dec.primary_fv) + [x])
        lrs = set(
            map(lambda t: t.name, rule_dec.primary_fv +
                rule_dec.neighbor_fvs[y]) + [x])
        xs = ','.join(lxs)
        rs = ','.join(lrs)
        xs_types = ','.join(map(lambda _: "int", lxs))
        rs_types = ','.join(map(lambda _: "int", lrs))

        rule_body = ','.join(
            map(lambda f: f.gen_snippet(self.source_text),
                inspect.get_facts(rule_dec.rhs)))
        '''
		print "Xs: %s" % xs
		print "Rs: %s" % rs
		print "X Guards: %s" % x_guards
		print "Y Guards: %s" % y_guards
		print "X Prop: %s" % x_prop_heads
		print "Y Prop: %s" % y_prop_heads
		print "X Simp: %s" % x_simp_heads
		print "Y Simp: %s" % y_simp_heads
		'''

        if inspect.filter_facts(simp_heads, x) > 0:
            match_rule_code = template('''
				{| y_prop_heads |},{| y_simp_heads |} \ [{| y_loc |}]{| rule_name |}_req({| xs_args |}) {| y_guards |} --o [{| x_loc |}]{| rule_name |}_match({| rs_args |}) priority 2.
			''')
        else:
            match_rule_code = template('''
				[{| y_loc |}]{| rule_name |}_req({| xs_args |}),{| y_prop_heads |},{| y_simp_heads |} \ 1 {| y_guards |} --o [{| x_loc |}]{| rule_name |}_match({| rs_args |}) priority 2.
			''')
        match_rule = compile_template(match_rule_code,
                                      y_loc=y,
                                      xs_args=xs,
                                      rs_args=rs,
                                      y_prop_heads=y_prop_heads,
                                      y_simp_heads=y_simp_heads,
                                      x_loc=x,
                                      rule_name=rule_dec.name,
                                      y_guards=y_guards)

        # print match_rule

        exists_code = ""
        if len(rule_dec.exists) > 0:
            exists_code = "exists %s." % (','.join(
                map(lambda e: e.name, rule_dec.exists)))
            # sys.stdout.write("Here: %s" % exists_code)

        zero_nr_code = template('''
			predicate {| rule_name |}_req    :: ({| xs_types |}) -> fact.
			predicate {| rule_name |}_match  :: ({| rs_types |}) -> fact.
			predicate {| rule_name |}_commit :: ({| rs_types |}) -> fact.

			rule {| rule_name |}1  :: {| x_prop_heads |},{| x_simp_heads |} \ 1 {| x_guards |} --o [{| y_loc |}]{| rule_name |}_req({| xs_args |}).
			rule {| rule_name |}2  :: {| match_rule |}
			rule {| rule_name |}3  :: {| x_prop_heads |},{| x_simp_heads |},[{| x_loc |}]{| rule_name |}_match({| rs_args |}) --o [{| y_loc |}]{| rule_name |}_commit({| rs_args |}).
			rule {| rule_name |}4a :: {| y_prop_heads |} \ [{| y_loc |}]{| rule_name |}_commit({| rs_args |}),{| y_simp_heads |} --o {| exists_code |} {| x_prop_heads |},{| rule_body |}.
			rule {| rule_name |}4b :: [{| y_loc |}]{| rule_name |}_commit({| rs_args |}) --o {| x_prop_heads |},{| x_simp_heads |}.
		''')

        zero_nr_rules = compact(
            compile_template(zero_nr_code,
                             match_rule=match_rule,
                             rule_name=rule_dec.name,
                             x_loc=x,
                             y_loc=y,
                             xs_args=xs,
                             rs_args=rs,
                             x_guards=x_guards,
                             y_guards=y_guards,
                             x_simp_heads=x_simp_heads,
                             y_simp_heads=y_simp_heads,
                             x_prop_heads=x_prop_heads,
                             y_prop_heads=y_prop_heads,
                             exists_code=exists_code,
                             rule_body=rule_body,
                             xs_types=xs_types,
                             rs_types=rs_types))

        # print zero_nr_rules

        msr_code_gen = MSRCodeGen("",
                                  bypass_checkers=True,
                                  input=zero_nr_rules)

        trans_decs = msr_code_gen.decs

        for dec in trans_decs:
            dec.add_trans_snippet(dec.gen_snippet(zero_nr_rules))

        lead_rule_snippet = "One Neighbor Restriction translation applied.\n\nSource rule:\n%s\n\n" % rule_dec.gen_snippet(
            self.source_text)
        lead_rule_snippet += "Generated fragment:\n%s\n\n" % zero_nr_rules
        lead_rule_snippet += trans_decs[0].gen_snippet(zero_nr_rules)
        trans_decs[0].add_trans_snippet(lead_rule_snippet)

        trans_decs[len(trans_decs) - 2].where = rule_dec.where

        return trans_decs