funasp 0.0.1.post21__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- funasp/__init__.py +0 -0
- funasp/__main__.py +44 -0
- funasp/__version__.py +1 -0
- funasp/app.py +150 -0
- funasp/control.py +134 -0
- funasp/solve.py +106 -0
- funasp/symbol.py +48 -0
- funasp/syntax_tree/__init__.py +89 -0
- funasp/syntax_tree/_context.py +40 -0
- funasp/syntax_tree/_nodes.py +620 -0
- funasp/syntax_tree/collectors.py +108 -0
- funasp/syntax_tree/parsing/__init__.py +0 -0
- funasp/syntax_tree/parsing/parser.py +693 -0
- funasp/syntax_tree/rewritings/__init__.py +61 -0
- funasp/syntax_tree/rewritings/aggregates.py +61 -0
- funasp/syntax_tree/rewritings/integration.py +151 -0
- funasp/syntax_tree/rewritings/negated_literals.py +52 -0
- funasp/syntax_tree/rewritings/protecting.py +766 -0
- funasp/syntax_tree/rewritings/protecting_operations.py +279 -0
- funasp/syntax_tree/rewritings/showf.py +19 -0
- funasp/syntax_tree/rewritings/some_assignments.py +93 -0
- funasp/syntax_tree/rewritings/to_asp.py +357 -0
- funasp/syntax_tree/rewritings/unnesting/__init__.py +0 -0
- funasp/syntax_tree/rewritings/unnesting/_statement.py +0 -0
- funasp/syntax_tree/rewritings/unnesting/literals.py +343 -0
- funasp/syntax_tree/rewritings/unnesting/rules.py +389 -0
- funasp/syntax_tree/types.py +18 -0
- funasp/tools/__init__.py +3 -0
- funasp/tools/print_ast.py +116 -0
- funasp/util/__init__.py +0 -0
- funasp/util/ast.py +495 -0
- funasp/util/clingox/__init__.py +0 -0
- funasp/util/iterables.py +22 -0
- funasp/util/tree_sitter.py +112 -0
- funasp-0.0.1.post21.dist-info/METADATA +45 -0
- funasp-0.0.1.post21.dist-info/RECORD +40 -0
- funasp-0.0.1.post21.dist-info/WHEEL +5 -0
- funasp-0.0.1.post21.dist-info/entry_points.txt +2 -0
- funasp-0.0.1.post21.dist-info/licenses/LICENSE +21 -0
- funasp-0.0.1.post21.dist-info/top_level.txt +1 -0
funasp/__init__.py
ADDED
|
File without changes
|
funasp/__main__.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def check_versions() -> int: # pragma: no cover
|
|
5
|
+
if sys.version_info < (3, 13):
|
|
6
|
+
sys.stderr.write(
|
|
7
|
+
f"*** ERROR: fasp requires Python 3.13 or higher, found version {sys.version_info} \n"
|
|
8
|
+
)
|
|
9
|
+
return 1
|
|
10
|
+
try:
|
|
11
|
+
from clingo import core # pylint: disable=import-outside-toplevel
|
|
12
|
+
|
|
13
|
+
clingo_version = core.version()
|
|
14
|
+
except ImportError:
|
|
15
|
+
sys.stderr.write(
|
|
16
|
+
"*** ERROR: fasp requires clingo library version 6.0.0 or higher.\n"
|
|
17
|
+
)
|
|
18
|
+
return 1
|
|
19
|
+
clingo_version_str = ".".join(map(str, clingo_version))
|
|
20
|
+
if clingo_version < (6, 0, 0):
|
|
21
|
+
sys.stderr.write(
|
|
22
|
+
f"*** ERROR: fasp requires clingo library version 6.0.0 or higher, found version {clingo_version_str}.\n"
|
|
23
|
+
)
|
|
24
|
+
return 1
|
|
25
|
+
# sys.stdout.write(f"clingo version {clingo_version_str}\n")
|
|
26
|
+
return 0
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def main() -> int:
|
|
30
|
+
args = frozenset(sys.argv[1:])
|
|
31
|
+
"-v" in args or "--version" in args
|
|
32
|
+
# if not version_mode:
|
|
33
|
+
# sys.stdout.write(f"fasp version {__version__}\n")
|
|
34
|
+
if error_code := check_versions() != 0: # pragma: no cover
|
|
35
|
+
return error_code
|
|
36
|
+
# if not version_mode:
|
|
37
|
+
# sys.stdout.write("\n")
|
|
38
|
+
from funasp.app import main as app_main # pylint: disable=import-outside-toplevel
|
|
39
|
+
|
|
40
|
+
return app_main(sys.argv[1:])
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
if __name__ == "__main__":
|
|
44
|
+
sys.exit(main())
|
funasp/__version__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.0.1"
|
funasp/app.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import ctypes
|
|
2
|
+
import sys
|
|
3
|
+
from typing import Callable, Optional, Sequence
|
|
4
|
+
|
|
5
|
+
from clingo import core, solve
|
|
6
|
+
from clingo.app import App, AppOptions, Flag, clingo_main
|
|
7
|
+
from clingo.control import Control as ClingoControl
|
|
8
|
+
from clingo.control import ControlMode as ClingoControlMode
|
|
9
|
+
from colorama import Fore, Style
|
|
10
|
+
from colorama import deinit as colorama_deinit
|
|
11
|
+
from colorama import init as colorama_init
|
|
12
|
+
|
|
13
|
+
from funasp.__version__ import __version__
|
|
14
|
+
from funasp.control import Control
|
|
15
|
+
from funasp.util.ast import ELibrary, ParsingException
|
|
16
|
+
|
|
17
|
+
LIBC_NAME: str | None = None
|
|
18
|
+
try:
|
|
19
|
+
if sys.platform.startswith("win"): # pragma: no cover
|
|
20
|
+
LIBC_NAME = "msvcrt"
|
|
21
|
+
except Exception as e: # pragma: no cover
|
|
22
|
+
pass
|
|
23
|
+
LIBC = ctypes.CDLL(LIBC_NAME) # None = current process's libc
|
|
24
|
+
|
|
25
|
+
# Declare fflush prototype
|
|
26
|
+
LIBC.fflush.argtypes = [ctypes.c_void_p]
|
|
27
|
+
LIBC.fflush.restype = ctypes.c_int
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class FaspApp(App):
|
|
31
|
+
def __init__(self, library: ELibrary, clingo_options: Sequence[str]) -> None:
|
|
32
|
+
super().__init__("funasp", __version__)
|
|
33
|
+
self._order = Flag()
|
|
34
|
+
self._library = library
|
|
35
|
+
self._clingo_options = clingo_options
|
|
36
|
+
self._prefix = "F"
|
|
37
|
+
self._print_rewrite = False
|
|
38
|
+
self._control: Optional[Control] = None
|
|
39
|
+
self._errors: list[Exception] = []
|
|
40
|
+
|
|
41
|
+
def register_options(self, options: AppOptions) -> None:
|
|
42
|
+
options.add_flag(
|
|
43
|
+
"fasp", "order", "Print atoms in models in order.", self._order
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
options.add(
|
|
47
|
+
"fasp",
|
|
48
|
+
"prefix-fun",
|
|
49
|
+
"Set prefix for rewritten function predicates (default: F).",
|
|
50
|
+
self._set_prefix,
|
|
51
|
+
argument="<prefix>",
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
def print_model(
|
|
55
|
+
self, model: solve.Model, default_printer: Callable[[], None]
|
|
56
|
+
) -> None:
|
|
57
|
+
assert self._control is not None
|
|
58
|
+
self._control.print_model(model, default_printer)
|
|
59
|
+
|
|
60
|
+
def _set_prefix(self, prefix: str) -> None:
|
|
61
|
+
self._prefix = prefix
|
|
62
|
+
|
|
63
|
+
def main(self, clingo_control: ClingoControl, files: Sequence[str]) -> None:
|
|
64
|
+
prefix = self._prefix
|
|
65
|
+
self._control = Control(
|
|
66
|
+
self._library,
|
|
67
|
+
self._clingo_options,
|
|
68
|
+
prefix,
|
|
69
|
+
clingo_control,
|
|
70
|
+
)
|
|
71
|
+
try:
|
|
72
|
+
self._control.parse_files(files)
|
|
73
|
+
if clingo_control.mode == ClingoControlMode.Rewrite:
|
|
74
|
+
print(self._control.get_rewritten_program())
|
|
75
|
+
return
|
|
76
|
+
except ParsingException as e:
|
|
77
|
+
for error in e.errors:
|
|
78
|
+
sys.stderr.write(str(error) + "\n")
|
|
79
|
+
self._errors.append(e)
|
|
80
|
+
return
|
|
81
|
+
except RuntimeError as e:
|
|
82
|
+
if "rewriting failed" == e.args[0]:
|
|
83
|
+
self._errors.append(e)
|
|
84
|
+
return
|
|
85
|
+
raise e # pragma: no cover
|
|
86
|
+
self._control.main()
|
|
87
|
+
|
|
88
|
+
def report_error_summary(self) -> None:
|
|
89
|
+
if any(isinstance(error, ParsingException) for error in self._errors):
|
|
90
|
+
print(
|
|
91
|
+
Style.BRIGHT
|
|
92
|
+
+ Fore.RED
|
|
93
|
+
+ "*** ERROR: (fasp):"
|
|
94
|
+
+ Style.RESET_ALL
|
|
95
|
+
+ " parsing failed\n",
|
|
96
|
+
file=sys.stderr,
|
|
97
|
+
)
|
|
98
|
+
if any(
|
|
99
|
+
isinstance(error, RuntimeError) and error.args[0] == "rewriting failed"
|
|
100
|
+
for error in self._errors
|
|
101
|
+
):
|
|
102
|
+
print(
|
|
103
|
+
Style.BRIGHT
|
|
104
|
+
+ Fore.RED
|
|
105
|
+
+ "*** ERROR: (fasp):"
|
|
106
|
+
+ Style.RESET_ALL
|
|
107
|
+
+ " rewriting failed\n",
|
|
108
|
+
file=sys.stderr,
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def fasp_main(
|
|
113
|
+
library: ELibrary, options: list[str] | None = None, raise_errors: bool = False
|
|
114
|
+
) -> int:
|
|
115
|
+
"""
|
|
116
|
+
Main function for the fasp application.
|
|
117
|
+
|
|
118
|
+
Parameters
|
|
119
|
+
----------
|
|
120
|
+
library
|
|
121
|
+
The Clingo library to use.
|
|
122
|
+
options
|
|
123
|
+
Command line options to pass to the application.
|
|
124
|
+
raise_errors
|
|
125
|
+
If True, raise exceptions on errors instead of printing them.
|
|
126
|
+
"""
|
|
127
|
+
colorama_init(autoreset=True)
|
|
128
|
+
if options is None: # pragma: no cover
|
|
129
|
+
options = []
|
|
130
|
+
app = FaspApp(library, options)
|
|
131
|
+
# options.append("--outf=3")
|
|
132
|
+
try:
|
|
133
|
+
result = clingo_main(library.library, options, app)
|
|
134
|
+
app.report_error_summary()
|
|
135
|
+
return result
|
|
136
|
+
except Exception: # pragma: no cover
|
|
137
|
+
if raise_errors:
|
|
138
|
+
raise
|
|
139
|
+
return 1
|
|
140
|
+
finally:
|
|
141
|
+
colorama_deinit()
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def main(options: Sequence[str] = ()) -> int:
|
|
145
|
+
def logger(ty: core.MessageType, message: str) -> None:
|
|
146
|
+
sys.stderr.write(message + "\n")
|
|
147
|
+
|
|
148
|
+
with ELibrary(logger=logger) as library:
|
|
149
|
+
return fasp_main(library, list(options))
|
|
150
|
+
return 1 # pragma: no cover
|
funasp/control.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import ctypes
|
|
2
|
+
import sys
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from typing import Any, Iterable, Optional, Sequence
|
|
5
|
+
|
|
6
|
+
import clingo
|
|
7
|
+
from clingo import ast
|
|
8
|
+
from clingo import solve as clingo_solve
|
|
9
|
+
from clingo import symbol
|
|
10
|
+
|
|
11
|
+
from funasp.solve import Model
|
|
12
|
+
from funasp.syntax_tree import rewrite_statements
|
|
13
|
+
from funasp.syntax_tree._context import RewriteContext
|
|
14
|
+
from funasp.syntax_tree.parsing import parser
|
|
15
|
+
from funasp.util.ast import ELibrary
|
|
16
|
+
|
|
17
|
+
LIBC_NAME: str | None = None
|
|
18
|
+
try:
|
|
19
|
+
if sys.platform.startswith("win"): # pragma: no cover
|
|
20
|
+
LIBC_NAME = "msvcrt"
|
|
21
|
+
except Exception as e: # pragma: no cover
|
|
22
|
+
pass
|
|
23
|
+
LIBC = ctypes.CDLL(LIBC_NAME) # None = current process's libc
|
|
24
|
+
|
|
25
|
+
# Declare fflush prototype
|
|
26
|
+
LIBC.fflush.argtypes = [ctypes.c_void_p]
|
|
27
|
+
LIBC.fflush.restype = ctypes.c_int
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Control:
|
|
31
|
+
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
library: ELibrary,
|
|
35
|
+
options: Sequence[str] = (),
|
|
36
|
+
prefix: str = "F",
|
|
37
|
+
clingo_control: Optional[clingo.control.Control] = None,
|
|
38
|
+
):
|
|
39
|
+
self.library = library
|
|
40
|
+
self.clingo_control = clingo_control or clingo.control.Control(
|
|
41
|
+
library.library, options
|
|
42
|
+
)
|
|
43
|
+
self.prefix = prefix
|
|
44
|
+
self._rewritten_program: Optional[str]
|
|
45
|
+
self._result: Optional[clingo.solve.SolveResult] = None
|
|
46
|
+
|
|
47
|
+
def parse_files(self, files: Sequence[str]) -> None:
|
|
48
|
+
"""
|
|
49
|
+
Extend the logic program with a (non-ground) logic program in a file.
|
|
50
|
+
|
|
51
|
+
Parameters
|
|
52
|
+
----------
|
|
53
|
+
file
|
|
54
|
+
The path of the file to load.
|
|
55
|
+
"""
|
|
56
|
+
rewrite_ctx = RewriteContext(self.library, self.prefix)
|
|
57
|
+
statements = parser.parse_files(self.library, files)
|
|
58
|
+
statements = rewrite_statements(rewrite_ctx, statements)
|
|
59
|
+
program = ast.Program(self.library.library)
|
|
60
|
+
for statement in statements:
|
|
61
|
+
program.add(statement)
|
|
62
|
+
self.clingo_control.join(program)
|
|
63
|
+
self._rewritten_program = "\n".join(str(s) for s in statements)
|
|
64
|
+
|
|
65
|
+
def ground(
|
|
66
|
+
self,
|
|
67
|
+
parts: Sequence[tuple[str, Sequence[symbol.Symbol]]] = (("base", ()),),
|
|
68
|
+
context: Any = None,
|
|
69
|
+
) -> None:
|
|
70
|
+
"""
|
|
71
|
+
Ground the given list of program parts specified by tuples of names and
|
|
72
|
+
arguments.
|
|
73
|
+
|
|
74
|
+
Parameters
|
|
75
|
+
----------
|
|
76
|
+
parts
|
|
77
|
+
List of tuples of program names and program arguments to ground.
|
|
78
|
+
context
|
|
79
|
+
A context object whose methods are called during grounding using
|
|
80
|
+
the `@`-syntax (if omitted, those from the main module are used).
|
|
81
|
+
|
|
82
|
+
Notes
|
|
83
|
+
-----
|
|
84
|
+
Note that parts of a logic program without an explicit `#program`
|
|
85
|
+
specification are by default put into a program called `base` without
|
|
86
|
+
arguments.
|
|
87
|
+
"""
|
|
88
|
+
return self.clingo_control.ground(parts, context)
|
|
89
|
+
|
|
90
|
+
def solve(
|
|
91
|
+
self,
|
|
92
|
+
assumptions: Sequence[tuple[clingo.symbol.Symbol, bool] | int] = (),
|
|
93
|
+
on_unsat: Callable[[Sequence[int]], None] | None = None,
|
|
94
|
+
on_stats: (
|
|
95
|
+
Callable[[clingo.stats.Stats, clingo.stats.Stats], None] | None
|
|
96
|
+
) = None,
|
|
97
|
+
on_finish: Callable[[clingo.solve.SolveResult], None] | None = None,
|
|
98
|
+
) -> Iterable[Model]:
|
|
99
|
+
with self.clingo_control.start_solve(
|
|
100
|
+
assumptions=assumptions,
|
|
101
|
+
on_unsat=on_unsat,
|
|
102
|
+
on_stats=on_stats,
|
|
103
|
+
on_finish=on_finish,
|
|
104
|
+
yield_=True,
|
|
105
|
+
) as handle:
|
|
106
|
+
for model in handle:
|
|
107
|
+
yield Model(model, self.prefix)
|
|
108
|
+
self._result = handle.get()
|
|
109
|
+
|
|
110
|
+
def print_model(self, model: clingo_solve.Model, _: Callable[[], None]) -> None:
|
|
111
|
+
LIBC.fflush(None) # Flush C's stdout
|
|
112
|
+
sys.stdout.write(str(Model(model, self.prefix)))
|
|
113
|
+
sys.stdout.write("\n")
|
|
114
|
+
sys.stdout.flush()
|
|
115
|
+
|
|
116
|
+
def main(self) -> None:
|
|
117
|
+
"""
|
|
118
|
+
Main function to be called after parsing and grounding.
|
|
119
|
+
"""
|
|
120
|
+
self.clingo_control.main()
|
|
121
|
+
|
|
122
|
+
def get_rewritten_program(self) -> str:
|
|
123
|
+
"""
|
|
124
|
+
Get the rewritten ASP program as a string.
|
|
125
|
+
|
|
126
|
+
Returns
|
|
127
|
+
-------
|
|
128
|
+
str
|
|
129
|
+
The rewritten ASP program.
|
|
130
|
+
"""
|
|
131
|
+
if self._rewritten_program is None:
|
|
132
|
+
return "No program has been parsed yet." # pragma: no cover
|
|
133
|
+
raise ValueError("No program has been parsed yet.")
|
|
134
|
+
return self._rewritten_program
|
funasp/solve.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
from typing import Sequence
|
|
2
|
+
|
|
3
|
+
from clingo import solve
|
|
4
|
+
from clingo.symbol import Symbol, SymbolType
|
|
5
|
+
|
|
6
|
+
from funasp.symbol import FunctionSymbol
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Model:
|
|
10
|
+
"""
|
|
11
|
+
Provides access to a model during a solve call and provides a
|
|
12
|
+
`SolveContext` object to influence the running search.
|
|
13
|
+
|
|
14
|
+
Notes
|
|
15
|
+
-----
|
|
16
|
+
The string representation of a model object is similar to the output of
|
|
17
|
+
models by clingo using the default output.
|
|
18
|
+
|
|
19
|
+
`Model` objects cannot be constructed from Python. Instead they are obained
|
|
20
|
+
during solving (see `Control.solve`). Furthermore, the lifetime of a model
|
|
21
|
+
object is limited to the scope of the callback it was passed to or until
|
|
22
|
+
the search for the next model is started. They must not be stored for later
|
|
23
|
+
use.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def __init__(self, model: solve.Model, prefix: str = "F"):
|
|
27
|
+
self.clingo_model = model
|
|
28
|
+
self.prefix = prefix
|
|
29
|
+
|
|
30
|
+
def predicate_symbols(
|
|
31
|
+
self,
|
|
32
|
+
shown: bool = False,
|
|
33
|
+
atoms: bool = False,
|
|
34
|
+
terms: bool = False,
|
|
35
|
+
theory: bool = False,
|
|
36
|
+
) -> Sequence[Symbol]:
|
|
37
|
+
"""
|
|
38
|
+
Return the list of atoms, terms, or CSP assignments in the model.
|
|
39
|
+
|
|
40
|
+
Parameters
|
|
41
|
+
----------
|
|
42
|
+
atoms
|
|
43
|
+
Select all atoms in the model (independent of `#show` statements).
|
|
44
|
+
terms
|
|
45
|
+
Select all terms displayed with `#show` statements in the model.
|
|
46
|
+
shown
|
|
47
|
+
Select all atoms and terms as outputted by clingo.
|
|
48
|
+
theory
|
|
49
|
+
Select atoms added with `Model.extend`.
|
|
50
|
+
complement
|
|
51
|
+
Return the complement of the answer set w.r.t. to the atoms known
|
|
52
|
+
to the grounder.
|
|
53
|
+
|
|
54
|
+
Returns
|
|
55
|
+
-------
|
|
56
|
+
The selected symbols.
|
|
57
|
+
"""
|
|
58
|
+
return [
|
|
59
|
+
symbol
|
|
60
|
+
for symbol in self.clingo_model.symbols(shown, atoms, terms, theory)
|
|
61
|
+
if symbol.type != SymbolType.Function
|
|
62
|
+
or not symbol.name.startswith(self.prefix)
|
|
63
|
+
]
|
|
64
|
+
|
|
65
|
+
def function_symbols(
|
|
66
|
+
self,
|
|
67
|
+
shown: bool = False,
|
|
68
|
+
atoms: bool = False,
|
|
69
|
+
terms: bool = False,
|
|
70
|
+
theory: bool = False,
|
|
71
|
+
) -> Sequence[FunctionSymbol]:
|
|
72
|
+
return [
|
|
73
|
+
FunctionSymbol.from_symbol(symbol)
|
|
74
|
+
for symbol in self.clingo_model.symbols(shown, atoms, terms, theory)
|
|
75
|
+
if symbol.type == SymbolType.Function
|
|
76
|
+
and symbol.name.startswith(self.prefix)
|
|
77
|
+
]
|
|
78
|
+
|
|
79
|
+
def to_str(self, *, ordered: bool = False) -> str:
|
|
80
|
+
"""
|
|
81
|
+
Return a string representation of the model.
|
|
82
|
+
|
|
83
|
+
Parameters
|
|
84
|
+
----------
|
|
85
|
+
ordered
|
|
86
|
+
If True, the atoms in the model are sorted before printing.
|
|
87
|
+
|
|
88
|
+
Returns
|
|
89
|
+
-------
|
|
90
|
+
A string representation of the model.
|
|
91
|
+
"""
|
|
92
|
+
predicate_atoms = [str(atom) for atom in self.predicate_symbols(shown=True)]
|
|
93
|
+
function_atoms = [str(atom) for atom in self.function_symbols(shown=True)]
|
|
94
|
+
if ordered:
|
|
95
|
+
predicate_atoms.sort()
|
|
96
|
+
function_atoms.sort()
|
|
97
|
+
predicate_str = " ".join(predicate_atoms)
|
|
98
|
+
function_str = " ".join(function_atoms)
|
|
99
|
+
if not predicate_str:
|
|
100
|
+
return function_str
|
|
101
|
+
if not function_str:
|
|
102
|
+
return predicate_str
|
|
103
|
+
return f"{predicate_str}\n{function_str}"
|
|
104
|
+
|
|
105
|
+
def __repr__(self) -> str:
|
|
106
|
+
return self.to_str(ordered=True)
|
funasp/symbol.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from typing import Self, Sequence
|
|
3
|
+
|
|
4
|
+
from clingo.symbol import Symbol, SymbolType
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass(frozen=True, slots=True, order=True)
|
|
8
|
+
class FunctionSymbol:
|
|
9
|
+
|
|
10
|
+
name: str
|
|
11
|
+
value: Symbol
|
|
12
|
+
arguments: Sequence[Symbol] = ()
|
|
13
|
+
|
|
14
|
+
def __repr__(self) -> str:
|
|
15
|
+
"""
|
|
16
|
+
Return the string representation of the function symbol.
|
|
17
|
+
"""
|
|
18
|
+
args = ",".join(map(str, self.arguments))
|
|
19
|
+
if args:
|
|
20
|
+
args = f"({args})"
|
|
21
|
+
return f"{self.name}{args}={str(self.value)}"
|
|
22
|
+
|
|
23
|
+
@classmethod
|
|
24
|
+
def from_symbol(cls, symbol: Symbol, prefix_len: int = 1) -> Self:
|
|
25
|
+
"""
|
|
26
|
+
Convert a clingo symbol to a function symbol.
|
|
27
|
+
|
|
28
|
+
Parameters
|
|
29
|
+
----------
|
|
30
|
+
symbol : clingo.Symbol
|
|
31
|
+
The clingo symbol to convert.
|
|
32
|
+
|
|
33
|
+
Returns
|
|
34
|
+
-------
|
|
35
|
+
FunctionSymbol
|
|
36
|
+
The converted function symbol.
|
|
37
|
+
"""
|
|
38
|
+
assert len(symbol.name) > prefix_len
|
|
39
|
+
assert symbol.type == SymbolType.Function
|
|
40
|
+
assert len(symbol.arguments) >= 1
|
|
41
|
+
|
|
42
|
+
name = symbol.name[prefix_len:]
|
|
43
|
+
args = symbol.arguments[:-1]
|
|
44
|
+
return_value = symbol.arguments[-1]
|
|
45
|
+
return cls(name, return_value, args)
|
|
46
|
+
# return cls(
|
|
47
|
+
# symbol.arguments[0].name, symbol.arguments[1], symbol.arguments[0].arguments
|
|
48
|
+
# )
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
from typing import Iterable
|
|
2
|
+
|
|
3
|
+
from clingo import ast
|
|
4
|
+
|
|
5
|
+
from funasp.syntax_tree.rewritings.integration import (
|
|
6
|
+
transform_to_clingo_statements,
|
|
7
|
+
)
|
|
8
|
+
|
|
9
|
+
from ._context import RewriteContext
|
|
10
|
+
from ._nodes import (
|
|
11
|
+
FASP_AST,
|
|
12
|
+
FASP_AST_T,
|
|
13
|
+
AssignmentAggregateElement,
|
|
14
|
+
AssignmentAST,
|
|
15
|
+
AssignmentRule,
|
|
16
|
+
ChoiceAssignment,
|
|
17
|
+
FASP_Statement,
|
|
18
|
+
HeadAssignment,
|
|
19
|
+
HeadAssignmentAggregate,
|
|
20
|
+
HeadSimpleAssignment,
|
|
21
|
+
ShowFDirective,
|
|
22
|
+
)
|
|
23
|
+
from .types import SymbolSignature
|
|
24
|
+
|
|
25
|
+
_ALL__ = [
|
|
26
|
+
FASP_AST,
|
|
27
|
+
FASP_AST_T,
|
|
28
|
+
AssignmentAggregateElement,
|
|
29
|
+
AssignmentAST,
|
|
30
|
+
AssignmentRule,
|
|
31
|
+
ChoiceAssignment,
|
|
32
|
+
FASP_Statement,
|
|
33
|
+
HeadAssignmentAggregate,
|
|
34
|
+
HeadAssignment,
|
|
35
|
+
HeadSimpleAssignment,
|
|
36
|
+
SymbolSignature,
|
|
37
|
+
ShowFDirective,
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
### Please change to
|
|
42
|
+
|
|
43
|
+
# def rewrite_statement(
|
|
44
|
+
# ctx: fasp.syntax_tree._context.RewriteContext,
|
|
45
|
+
# statement: FASP_Statement,
|
|
46
|
+
# ) -> Iterable[ast.Statement]:
|
|
47
|
+
|
|
48
|
+
# ELibrary and prefix are part of RewriteContext
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def rewrite_statement(
|
|
52
|
+
ctx: RewriteContext,
|
|
53
|
+
statement: FASP_Statement,
|
|
54
|
+
) -> Iterable[ast.Statement]:
|
|
55
|
+
"""
|
|
56
|
+
Rewrite a statement in the FASP AST to a list of statements in the clingo
|
|
57
|
+
AST.
|
|
58
|
+
|
|
59
|
+
Parameters
|
|
60
|
+
----------
|
|
61
|
+
ctx
|
|
62
|
+
The rewrite context.
|
|
63
|
+
statement
|
|
64
|
+
The statement to rewrite.
|
|
65
|
+
"""
|
|
66
|
+
rewritten_statements = transform_to_clingo_statements(ctx, [statement])
|
|
67
|
+
return rewritten_statements
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def rewrite_statements(
|
|
71
|
+
ctx: RewriteContext,
|
|
72
|
+
statements: Iterable[FASP_Statement],
|
|
73
|
+
) -> Iterable[ast.Statement]:
|
|
74
|
+
"""Rewrite an iterable of FASP statements to clingo AST statements.
|
|
75
|
+
|
|
76
|
+
Parameters
|
|
77
|
+
----------
|
|
78
|
+
ctx
|
|
79
|
+
The rewrite context.
|
|
80
|
+
statements
|
|
81
|
+
Iterable of FASP_Statement to rewrite.
|
|
82
|
+
library
|
|
83
|
+
The ELibrary to use. If None, a new ELibrary() is created.
|
|
84
|
+
prefix
|
|
85
|
+
Prefix to use for generated predicate names.
|
|
86
|
+
"""
|
|
87
|
+
# for stmt in statements:
|
|
88
|
+
# ctx.elib.add_original_statement(stmt)
|
|
89
|
+
return transform_to_clingo_statements(ctx, statements)
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
from clingo.ast import RewriteContext as ClingoRewriteContext
|
|
2
|
+
|
|
3
|
+
from funasp.syntax_tree.types import SymbolSignature
|
|
4
|
+
from funasp.util.ast import ELibrary
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class RewriteContext:
|
|
8
|
+
"""
|
|
9
|
+
A class for FASP Rewrite Context.
|
|
10
|
+
|
|
11
|
+
The ELibrary instance and the prefix string are encapsulated within the RewriteContext.
|
|
12
|
+
When rewriting statements or parsing files, these parameters should be accessed via
|
|
13
|
+
the RewriteContext rather than passed separately.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
lib: ELibrary = ELibrary(),
|
|
19
|
+
prefix_function: str = "F",
|
|
20
|
+
*,
|
|
21
|
+
prefix_variable: str = "FUN",
|
|
22
|
+
prefix_variable_agg: str = "AGG",
|
|
23
|
+
prefix_protect_comparison: str = "CMP",
|
|
24
|
+
prefix_protect_guard: str = "GRD",
|
|
25
|
+
prefix_protect_assignment: str = "ASS",
|
|
26
|
+
prefix_protect_operation: str = "OP",
|
|
27
|
+
evaluable_functions: set[SymbolSignature] | None = None,
|
|
28
|
+
):
|
|
29
|
+
self.lib = lib
|
|
30
|
+
self.prefix_function = prefix_function
|
|
31
|
+
self.prefix_variable = prefix_variable
|
|
32
|
+
self.prefix_variable_agg = prefix_variable_agg
|
|
33
|
+
self.prefix_protect_comparison = prefix_protect_comparison
|
|
34
|
+
self.prefix_protect_guard = prefix_protect_guard
|
|
35
|
+
self.prefix_protect_assignment = prefix_protect_assignment
|
|
36
|
+
self.prefix_protect_operation = prefix_protect_operation
|
|
37
|
+
self.ctx = ClingoRewriteContext(self.lib.library)
|
|
38
|
+
self.evaluable_functions: set[SymbolSignature] = (
|
|
39
|
+
set(evaluable_functions) if evaluable_functions is not None else set()
|
|
40
|
+
)
|