Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Constants between single quotes #3

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/pylo/engines/SWIProlog.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ def _lit_to_swipy(clause: Atom, lit_var_store: Dict[Variable, int]):
functor = _functor_to_swipy(clause.get_predicate())
compound_arg = swipy.swipy_new_term_refs(clause.get_predicate().get_arity())
args = clause.get_arguments()

_to_swipy_ref(args[0], compound_arg, lit_var_store)
for i in range(1, clause.get_predicate().get_arity()):
_to_swipy_ref(args[i], compound_arg+i, lit_var_store)
Expand Down Expand Up @@ -388,7 +389,7 @@ def retract(self, clause: Union[Atom, Clause]):
lit = _cl_to_swipy(clause, {})

retract = swipy.swipy_predicate("retract", 1, None)
query = swipy.swipy_open_query(retract, lit)
query = swipy.swipy_open_query(retract, swipl_object)
r = swipy.swipy_next_solution(query)
swipy.swipy_close_query(query)

Expand Down
35 changes: 23 additions & 12 deletions src/pylo/engines/XSBProlog.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
# from src.pylo import Constant, Variable, Functor, Structure, List, Predicate, Atom, Negation, Clause, \
# c_var, c_pred, c_functor, c_const, c_symbol
from .Prolog import Prolog
from .language import Variable, Structure, List, Atom, Clause, c_var, c_pred, c_functor, c_const, c_symbol
from .language import Variable, Structure, List, Atom, Clause, c_var, c_pred, c_functor, c_const, c_symbol, is_valid_constant, is_surrounded_by_single_quotes
import sys

#sys.path.append("../../build")
Expand All @@ -22,23 +22,31 @@ def _is_list(term: str):


def _is_structure(term: str):
first_bracket = term.find('(')

if first_bracket == -1:
if is_surrounded_by_single_quotes(term):
return False
else:
tmp = term[:first_bracket]
return all([x.isalnum() for x in tmp]) and tmp[0].isalpha()
first_bracket = term.find('(')

if first_bracket == -1:
return False
else:
try:
tmp = term[:first_bracket]
return all([x.isalnum() for x in tmp]) and tmp[0].isalpha()
except Exception as err:
print(term)
raise err


def _pyxsb_string_to_const_or_var(term: str):
if term[0].islower():
return c_const(term)
elif term.isnumeric():
if '.' in term:
return float(term)
if is_valid_constant(term):
if term.isnumeric():
if '.' in term:
return float(term)
else:
return int(term)
else:
return int(term)
return c_const(term)
else:
return c_var(term)

Expand All @@ -48,6 +56,9 @@ def _extract_arguments_from_compound(term: str):
term = term[1:-1] # remove '[' and ']'
else:
first_bracket = term.find('(')
if term[-1] != ')':
raise Exception(f"incorrect compound: {term}")

term = term[first_bracket+1:-1] # remove outer brackets

args = []
Expand Down
73 changes: 66 additions & 7 deletions src/pylo/engines/language.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
import typing


class InputError(Exception):
pass


class Term(ABC):

def __init__(self, name: str):
Expand All @@ -24,17 +28,69 @@ def __repr__(self):
return self._name


def is_float(value: str):
try:
float(value)
return True
except ValueError:
return False


def starts_with_digit(name: str):
return name[0].isdigit()


def starts_with_lower_case(name: str):
return name[0].islower()


def is_surrounded_by_single_quotes(name: str):
quote_char = "'"
return len(name) >= 3 and name[0] == quote_char and name[-1] == quote_char and quote_char not in name[1:-1]


def is_valid_constant(name: str):
if len(name) == 0:
return False

return (starts_with_digit(name)
or starts_with_lower_case(name)
or is_float(name)
or is_surrounded_by_single_quotes(name)
)

def starts_with_upper_case(name: str):
return name[0].isupper()


def starts_with_underscore(name: str):
return name[0] == '_'


def is_valid_variable(name: str):
if len(name) == 0:
return False

return (starts_with_upper_case(name)
or starts_with_underscore(name)
)

class Constant(Term):

def __init__(self, name):
assert name.islower(), f"Constants should be name with lowercase {name}"
def __init__(self, name: str):
if len(name) == 0:
raise InputError('empty Constant')
assert is_valid_constant(name), f"Constants should be name with lowercase {name}"
super().__init__(name)


class Variable(Term):

def __init__(self, name):
assert name.isupper(), f"Variables should be name uppercase {name}"
def __init__(self, name: str):
if len(name) == 0:
raise InputError("empty variable")

assert is_valid_variable(name), f"Variables should be name uppercase {name}"
super().__init__(name)


Expand Down Expand Up @@ -67,10 +123,13 @@ def __call__(self, *args: Union[str, "Constant", "Variable", "Structure", "List"
global global_context
elem: Union[str, "Constant", "Variable", "Structure", "List", int, float]
for elem in args:
# STARTS with lower case
if isinstance(elem, str) and elem.islower():
args_to_use.append(global_context.get_constant(elem))
elif isinstance(elem, str) and elem.isupper():
# STARTS with uppercase
elif isinstance(elem, str) and is_valid_variable(name):
args_to_use.append(global_context.get_variable(elem))
# Is a Constant, Variable, Structure, List, int or Float
elif isinstance(elem, (Constant, Variable, Structure, List, int, float)):
args_to_use.append(elem)
else:
Expand Down Expand Up @@ -177,9 +236,9 @@ def __call__(self, *args: Union[str, "Constant", "Variable", "Structure", "Predi
argsToUse.append(float(elem))
else:
argsToUse.append(int(elem))
if isinstance(elem, str) and elem[0].isupper():
elif isinstance(elem, str) and elem[0].isupper():
argsToUse.append(global_context.get_variable(elem))
elif isinstance(elem, str) and elem[0].islower():
elif isinstance(elem, str) and is_valid_constant(elem):
argsToUse.append(global_context.get_constant(elem))
elif isinstance(elem, (Constant, Variable, Structure, Predicate)):
argsToUse.append(elem)
Expand Down