Ejemplo n.º 1
0
	def check_scope(self, ast_node, ctxt):
		ctxt = copy_ctxt(ctxt)
		heads   = ast_node.slhs + ast_node.plhs
		inspect = Inspector()

		# Extend location context with all rule head variables
		for fact in map(inspect.get_fact, heads):
			terms = inspect.get_atoms( [inspect.get_loc(fact)] + inspect.get_args(fact) )
			ctxt['vars'] += inspect.filter_atoms(terms, var=True)
			
		# Check scope of rule heads. This step is mainly for checking for constant name and 
		# predicate name scope of rule heads
		map(lambda h: self.check_scope(h, ctxt) , heads)
		map(lambda g: self.check_scope(g, ctxt) , ast_node.grd)

		# Include exist variables scopes
		ctxt['vars'] += ast_node.exists

		# Incremental include where assign statements
		for ass_stmt in ast_node.where:
			self.check_scope(ass_stmt.builtin_exp, ctxt)
			self.compose_out_scope_error_report(ctxt)
			ctxt['vars'] += inspect.filter_atoms( inspect.get_atoms(ass_stmt.term_pat), var=True)

		map(lambda b: self.check_scope(b, ctxt) , ast_node.rhs)

		'''
		for fact in map(inspect.get_fact, ast_node.rhs), fact_atoms=True ):
			loc = inspect.get_loc(fact)
			loc_key = loc.compare_value()
			args = inspect.get_args(fact)
			atoms = inspect.get_atoms(args)
			arg_map[loc_key] += map(lambda t: t.name,inspect.filter_atoms(atoms, var=True))
		'''

		self.compose_out_scope_error_report(ctxt)
Ejemplo n.º 2
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)
Ejemplo n.º 3
0
	def int_check(self, ast_node):
		heads   = ast_node.slhs + ast_node.plhs
		inspect = Inspector()

		# Build the neighborhood free variables mapping of the rule heads (NFV mapping)
		locs    = []
		neighbor_fvs = {}
		for fact in map(inspect.get_fact, heads):
			loc = inspect.get_loc(fact)
			loc_key = loc.name		
			if loc_key not in neighbor_fvs:
				neighbor_fvs[loc_key] = []
			args = inspect.get_args(fact)
			atoms = inspect.get_atoms(args)
			locs.append( loc )
			neighbor_fvs[loc_key] += inspect.filter_atoms(atoms, var=True)

		# From NFV mapping, nominate the primary location
		all_locs = neighbor_fvs.keys()
		ast_node.primary_loc = None
		ast_node.primary_fv  = None
		missing_vars = {}
		for loc in neighbor_fvs:
			fv = map(lambda t: t.name, neighbor_fvs[loc])
			contains_all_locs = True
			for t_loc in all_locs:
				if (t_loc not in fv) and t_loc != loc:
					contains_all_locs = False
					if loc in missing_vars:
						missing_vars[loc].append( t_loc )
					else:
						missing_vars[loc] = [t_loc]
			if contains_all_locs:
				ast_node.primary_loc = loc
				ast_node.primary_fv  = neighbor_fvs[loc]
				del neighbor_fvs[loc]
				break
		ast_node.neighbor_fvs = neighbor_fvs
		ast_node.neighbor_restriction = len(neighbor_fvs.keys())

		if ast_node.primary_loc == None:
			legend = ("%s %s: Location variable(s).\n" % (terminal.T_GREEN_BACK,terminal.T_NORM)) + ("%s %s: Argument variable.\n" % (terminal.T_RED_BACK,terminal.T_NORM))
			for loc in missing_vars:
				legend += "Location %s has no links to %s.\n" % (loc,','.join(missing_vars[loc]))
			error_report = "Rule %s is not neighbor restricted; None of location(s) %s can be primary location." % (ast_node.name,','.join(neighbor_fvs.keys()) )
			error_idx = self.declare_error(error_report , legend)
			for loc in neighbor_fvs:
				map(lambda t: self.extend_error(error_idx,t), neighbor_fvs[loc])
			map(lambda t: self.extend_info(error_idx,t), locs)
			return None

		# print "\n\n\n"
		# print ast_node.primary_loc
		# print ast_node.primary_fv
		# print ast_node.neighbor_fvs
		# print ast_node.neighbor_restriction

		primary_loc = ast_node.primary_loc
		primary_fv  = ast_node.primary_fv		
	
		primary_grds = []
		neighbor_grds = {}

		# Identify guards that are grounded by primary location
		for g_term in ast_node.grd: 
			g_vars = inspect.filter_atoms( inspect.get_atoms(g_term), var=True)
			excluded = not_contained(primary_fv, g_vars, key=lambda t:t.name)
			# print (ast_node.primary_loc,map(lambda t:t.name,excluded))
			if len(excluded) == 0:
				primary_grds.append(g_term)
			else:
				for loc in neighbor_fvs:
					excluded = not_contained(primary_fv + neighbor_fvs[loc], g_vars, key=lambda t:t.name)
					if len(excluded) == 0:
						if loc in neighbor_grds:
							neighbor_grds[loc].append( g_term )
						else:
							neighbor_grds[loc] = [g_term]

		# TODO: Add neighbor restriction guard test
		
		ast_node.primary_grds  = primary_grds
		ast_node.neighbor_grds = neighbor_grds
Ejemplo n.º 4
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)
Ejemplo n.º 5
0
    def int_check(self, ast_node):
        heads = ast_node.slhs + ast_node.plhs
        inspect = Inspector()

        # Build the neighborhood free variables mapping of the rule heads (NFV mapping)
        locs = []
        neighbor_fvs = {}
        for fact in map(inspect.get_fact, heads):
            loc = inspect.get_loc(fact)
            loc_key = loc.name
            if loc_key not in neighbor_fvs:
                neighbor_fvs[loc_key] = []
            args = inspect.get_args(fact)
            atoms = inspect.get_atoms(args)
            locs.append(loc)
            neighbor_fvs[loc_key] += inspect.filter_atoms(atoms, var=True)

        # From NFV mapping, nominate the primary location
        all_locs = neighbor_fvs.keys()
        ast_node.primary_loc = None
        ast_node.primary_fv = None
        missing_vars = {}
        for loc in neighbor_fvs:
            fv = map(lambda t: t.name, neighbor_fvs[loc])
            contains_all_locs = True
            for t_loc in all_locs:
                if (t_loc not in fv) and t_loc != loc:
                    contains_all_locs = False
                    if loc in missing_vars:
                        missing_vars[loc].append(t_loc)
                    else:
                        missing_vars[loc] = [t_loc]
            if contains_all_locs:
                ast_node.primary_loc = loc
                ast_node.primary_fv = neighbor_fvs[loc]
                del neighbor_fvs[loc]
                break
        ast_node.neighbor_fvs = neighbor_fvs
        ast_node.neighbor_restriction = len(neighbor_fvs.keys())

        if ast_node.primary_loc == None:
            legend = ("%s %s: Location variable(s).\n" %
                      (terminal.T_GREEN_BACK, terminal.T_NORM)) + (
                          "%s %s: Argument variable.\n" %
                          (terminal.T_RED_BACK, terminal.T_NORM))
            for loc in missing_vars:
                legend += "Location %s has no links to %s.\n" % (loc, ','.join(
                    missing_vars[loc]))
            error_report = "Rule %s is not neighbor restricted; None of location(s) %s can be primary location." % (
                ast_node.name, ','.join(neighbor_fvs.keys()))
            error_idx = self.declare_error(error_report, legend)
            for loc in neighbor_fvs:
                map(lambda t: self.extend_error(error_idx, t),
                    neighbor_fvs[loc])
            map(lambda t: self.extend_info(error_idx, t), locs)
            return None

        # print "\n\n\n"
        # print ast_node.primary_loc
        # print ast_node.primary_fv
        # print ast_node.neighbor_fvs
        # print ast_node.neighbor_restriction

        primary_loc = ast_node.primary_loc
        primary_fv = ast_node.primary_fv

        primary_grds = []
        neighbor_grds = {}

        # Identify guards that are grounded by primary location
        for g_term in ast_node.grd:
            g_vars = inspect.filter_atoms(inspect.get_atoms(g_term), var=True)
            excluded = not_contained(primary_fv, g_vars, key=lambda t: t.name)
            # print (ast_node.primary_loc,map(lambda t:t.name,excluded))
            if len(excluded) == 0:
                primary_grds.append(g_term)
            else:
                for loc in neighbor_fvs:
                    excluded = not_contained(primary_fv + neighbor_fvs[loc],
                                             g_vars,
                                             key=lambda t: t.name)
                    if len(excluded) == 0:
                        if loc in neighbor_grds:
                            neighbor_grds[loc].append(g_term)
                        else:
                            neighbor_grds[loc] = [g_term]

        # TODO: Add neighbor restriction guard test

        ast_node.primary_grds = primary_grds
        ast_node.neighbor_grds = neighbor_grds