-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathc_like_utils.py
More file actions
82 lines (62 loc) · 2.32 KB
/
c_like_utils.py
File metadata and controls
82 lines (62 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
"""
utilities for C-like languages
"""
import typing
from . import core
from . import utils
def escape_special_char(in_atom: core.Atom) -> str:
"""
if in_char is a special_character function returns its escape sequences
otherwise it returns in_char
"""
special_chars = {
r'"': r"\"",
r"'": r"\'",
"\\": "\\\\",
"\n": "\\n",
"\t": "\\t",
}
return special_chars.get(in_atom.atom_char, in_atom.atom_char)
def get_atom_to_code(
in_printer_function_name: str,
in_escape_special_char_fun: typing.Callable[[core.Atom], str],
) -> typing.Callable[[core.Atom], str]:
"""returns the atom_to_code type function"""
def _inner(in_atom: core.Atom) -> str:
res_char = in_escape_special_char_fun(in_atom)
return f"{in_printer_function_name}('{res_char}');"
return _inner
def get_function_call_str_fun(get_function_name):
"""returns a function returning a string calling a function with given id"""
return utils.get_function_call_str_fun(get_function_name, "", "();")
def get_body_to_str(
in_call_function_or_atom: typing.Callable[[core.CalledListEntry], str],
) -> typing.Callable[[core.SimpleFunction], str]:
"""returns body_to_str-like function for c-like languages"""
return utils.get_body_to_str("\n", " ", in_call_function_or_atom, "", "")
def get_merge_to_full_function(
in_function_prefix: str,
) -> typing.Callable[[str, str], str]:
"""returns merge_to_full_function-like function for c-like languages"""
def _merge_to_full_function(in_function_name: str, in_function_body: str) -> str:
body_str = "\n" + in_function_body + "\n" if in_function_body else ""
return "\n".join(
[
f"{in_function_prefix}{in_function_name}()",
"{" + body_str + "}\n",
]
)
return _merge_to_full_function
def get_main_call_fun(in_call_function_or_atom):
"""returns function returning code of main C or C++ function"""
def _main_call(in_initial_call: str | None, **kwargs) -> str:
initial_call_str = (
" " + in_call_function_or_atom(in_initial_call, **kwargs) + "\n "
if in_initial_call is not None
else " "
)
return f"""int main()
{{
{initial_call_str}return 0;
}}"""
return _main_call