├── .gitignore ├── LICENSE ├── README.md ├── bin └── hatlog ├── examples ├── fib.py ├── fib.py.pl ├── join.py ├── join.py.pl ├── map.py └── map.py.pl ├── hatlog ├── __init__.py ├── env.py ├── flattener.py └── prolog.py ├── prettyTypes.pl └── pythonTypeSystem.pl /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | *txt 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2016 Alexander Ivanov 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # hatlog 2 | 3 | a proof of concept of a type inference tool for Python written in Prolog. Idea described in [blog](http://code.alehander42.me/prolog_type_systems) 4 | 5 | # how? 6 | 7 | currently it works for simple one-function python files 8 | 9 | ```bash 10 | bin/hatlog examples/map.py 11 | # A,B::Callable[[A],B] -> List[A] -> List[B] 12 | ``` 13 | 14 | * hatlog flattens the python ast and annotates the types: constants for literals and variables otherwise 15 | * it generates a prolog program with the flattened ast: each node is represented as a prolog rule applied on its element types 16 | * the program imports the specified type system, infers the types of the function based on it and saves it 17 | * hatlog prints it 18 | 19 | the type system is described as a simple file with prolog rules: 20 | 21 | they describe the type rules for python nodes, e.g. 22 | 23 | ```prolog 24 | z_cmp(A, A, bool) :- comparable(A). 25 | 26 | z_index([list, X], int, X). 27 | z_index([dict, X, Y], X, Y). 28 | z_index(str, int, str). 29 | 30 | ``` 31 | 32 | and some builtin methods, e.g. 33 | 34 | ```prolog 35 | m([list, A], index, [A], int). 36 | ``` 37 | 38 | You can easily define your custom type systems just by tweaking those definitions. 39 | 40 | 41 | # Author 42 | 43 | [Alexander Ivanov](http://code.alehander42.me), 2016 44 | -------------------------------------------------------------------------------- /bin/hatlog: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import sys 4 | import os 5 | import subprocess 6 | sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) 7 | import re 8 | import hatlog 9 | import ast 10 | 11 | 12 | 13 | 14 | def infer_file(filename): 15 | with open(filename, 'r') as f: 16 | source = f.read() 17 | return infer(source, filename) 18 | 19 | def infer(source, filename): 20 | output = hatlog.generate_prolog(*(hatlog.flatten(ast.parse(source)) + [filename])) 21 | child = subprocess.Popen(['swipl', '-s', output], stdout=subprocess.PIPE, stderr=subprocess.PIPE) 22 | s = child.communicate()[0] 23 | q = child.returncode 24 | if q == 0: 25 | with open('%s.txt' % filename, 'r') as f: 26 | z = f.read() 27 | 28 | print(z) 29 | else: 30 | print('error: %s' % s) 31 | 32 | def main(): 33 | if len(sys.argv) == 1: 34 | print('python3 ') 35 | else: 36 | infer_file(sys.argv[1]) 37 | 38 | if __name__ == '__main__': 39 | main() 40 | -------------------------------------------------------------------------------- /examples/fib.py: -------------------------------------------------------------------------------- 1 | def fib(x): 2 | if x < 2: 3 | return 1 4 | else: 5 | return fib(x - 1) * fib(x - 2) 6 | -------------------------------------------------------------------------------- /examples/fib.py.pl: -------------------------------------------------------------------------------- 1 | :- initialization main. 2 | 3 | :- use_module(pythonTypeSystem). 4 | :- use_module(prettyTypes). 5 | 6 | f(fib, [Z0], X) :- 7 | z_cmp(Z0, int, Z1), 8 | =(int, X), 9 | z_bin_op(Z0, int, Z2), 10 | =(Z2, Z0), 11 | z_bin_op(Z0, int, Z3), 12 | =(Z3, Z0), 13 | z_bin_op(X, X, Z4), 14 | =(Z4, X), 15 | z_if(Z1, [int], [Z4], Z5). 16 | 17 | main :- 18 | open('examples/fib.py.txt', write, Stream), 19 | ( 20 | f(fib, Z0, Z1), 21 | unvar(Z0, Z1, Z2, Z3, Z4), % replace free vars with names 22 | pretty_args(Z2, Y), 23 | pretty_type(Z3, Z), 24 | pretty_generic(Z4, X), 25 | format(Stream, '~a::', [X]), 26 | write(Stream, Y), 27 | write(Stream, ' -> '), 28 | write(Stream, Z), 29 | write(Stream, '\n'), 30 | 31 | true 32 | ), 33 | 34 | close(Stream), 35 | halt. 36 | main :- 37 | halt(1). 38 | -------------------------------------------------------------------------------- /examples/join.py: -------------------------------------------------------------------------------- 1 | def join(sequence, sep): 2 | result = '' 3 | for e in sequence[:-1]: 4 | result += e + sep 5 | result += sequence[-1] 6 | return result 7 | -------------------------------------------------------------------------------- /examples/join.py.pl: -------------------------------------------------------------------------------- 1 | :- initialization main. 2 | 3 | :- use_module(pythonTypeSystem). 4 | :- use_module(prettyTypes). 5 | 6 | f(join, [Z0, Z1], X) :- 7 | z_assign(Z2, str, Z3), 8 | z_unary_op(int, Z6), 9 | z_slice(Z0, Z6, Z6, Z5), 10 | z_bin_op(Z4, Z1, Z7), 11 | z_aug_assign(Z2, Z7, Z8), 12 | z_for(Z4, Z5, [Z8], Z9), 13 | z_unary_op(int, Z11), 14 | z_index(Z0, Z11, Z10), 15 | z_aug_assign(Z2, Z10, Z12), 16 | =(Z2, X). 17 | 18 | main :- 19 | open('examples/join.py.txt', write, Stream), 20 | ( 21 | f(join, Z0, Z1), 22 | unvar(Z0, Z1, Z2, Z3, Z4), % replace free vars with names 23 | pretty_args(Z2, Y), 24 | pretty_type(Z3, Z), 25 | pretty_generic(Z4, X), 26 | format(Stream, '~a::', [X]), 27 | write(Stream, Y), 28 | write(Stream, ' -> '), 29 | write(Stream, Z), 30 | write(Stream, '\n'), 31 | 32 | true 33 | ), 34 | 35 | close(Stream), 36 | halt. 37 | main :- 38 | halt(1). 39 | -------------------------------------------------------------------------------- /examples/map.py: -------------------------------------------------------------------------------- 1 | def map(f, sequence): 2 | out = [] 3 | for e in sequence: 4 | out.append(f(e)) 5 | return out 6 | -------------------------------------------------------------------------------- /examples/map.py.pl: -------------------------------------------------------------------------------- 1 | :- initialization main. 2 | 3 | :- use_module(pythonTypeSystem). 4 | :- use_module(prettyTypes). 5 | 6 | f(map, [Z0, Z1], X) :- 7 | z_list(Z3, Z4), 8 | z_assign(Z2, Z4, Z5), 9 | z_fcall(Z0, [Z6], Z7), 10 | z_method_call(Z2, append, [Z7], Z8), 11 | z_for(Z6, Z1, [Z8], Z9), 12 | =(Z2, X). 13 | 14 | main :- 15 | open('examples/map.py.txt', write, Stream), 16 | ( 17 | f(map, Z0, Z1), 18 | unvar(Z0, Z1, Z2, Z3, Z4), % replace free vars with names 19 | pretty_args(Z2, Y), 20 | pretty_type(Z3, Z), 21 | pretty_generic(Z4, X), 22 | format(Stream, '~a::', [X]), 23 | write(Stream, Y), 24 | write(Stream, ' -> '), 25 | write(Stream, Z), 26 | write(Stream, '\n'), 27 | 28 | true 29 | ), 30 | 31 | close(Stream), 32 | halt. 33 | main :- 34 | halt(1). 35 | -------------------------------------------------------------------------------- /hatlog/__init__.py: -------------------------------------------------------------------------------- 1 | from hatlog.flattener import flatten 2 | from hatlog.prolog import generate_prolog 3 | -------------------------------------------------------------------------------- /hatlog/env.py: -------------------------------------------------------------------------------- 1 | class Env: 2 | def __init__(self, values=None, parent=None): 3 | self.values = values or {} 4 | self.parent = parent 5 | 6 | def __getitem__(self, label): 7 | current = self 8 | while current is not None: 9 | if label in current.values: 10 | return current.values[label] 11 | current = current.parent 12 | 13 | def __setitem__(self, label, value): 14 | self.values[label] = value 15 | 16 | -------------------------------------------------------------------------------- /hatlog/flattener.py: -------------------------------------------------------------------------------- 1 | import ast 2 | import re 3 | from collections import defaultdict 4 | from hatlog.env import Env 5 | 6 | def flatten(root): 7 | if len(root.body) != 1 or not isinstance(root.body[0], ast.FunctionDef): 8 | raise ValueError("hatlog supports expects a function") 9 | x = Flattener() 10 | x.flatten(root.body[0]) 11 | return [x.nodes, root.body[0].name] 12 | 13 | NOT_SUPPORTED = defaultdict(set, 14 | FunctionDef={'keywords', 'starargs', 'kwargs'}, 15 | BinOp={'op'}, 16 | UnaryOp={'op'}, 17 | AugAssign={'op'}, 18 | Call={'keywords', 'starargs', 'kwargs'}, 19 | For={'orelse'}, 20 | Attribute={'ctx'}) 21 | 22 | class Flattener: 23 | def __init__(self): 24 | self.env = {} 25 | self.nodes = [] 26 | self.type_index = -1 27 | self.env = Env() 28 | self.args = [] 29 | self.return_type = None 30 | self.function = '' 31 | 32 | def flatten(self, node): 33 | if isinstance(node, list): 34 | f = [self.flatten(e) for e in node] 35 | return f 36 | elif node is None: 37 | return 'v' 38 | else: 39 | sub = getattr( 40 | self, 41 | 'flatten_%s' % type(node).__name__.lower(), 42 | self.default) 43 | return sub(node) 44 | 45 | def default(self, node): 46 | f = [self.flatten(getattr(node, f)) for f in node._fields if f not in NOT_SUPPORTED[type(node).__name__]] 47 | node_type = self.new_type() 48 | self.nodes.append(('z_%s' % self.to_snake_case(type(node).__name__), f, node_type)) 49 | return node_type 50 | 51 | def flatten_call(self, node): 52 | if isinstance(node.func, ast.Name) and node.func.id == self.function: 53 | return self.flatten_rec(node) 54 | elif isinstance(node.func, ast.Attribute): 55 | return self.flatten_method_call(node) 56 | else: 57 | function = self.flatten(node.func) 58 | args = [self.flatten(e) for e in node.args] 59 | return_type = self.new_type() 60 | 61 | if isinstance(node.func, ast.Name) and node.func.id not in self.env.values: # named 62 | self.nodes.append(('z_call', [node.func.id, args], return_type)) 63 | else: 64 | self.nodes.append(('z_fcall', [function, args], return_type)) 65 | 66 | return return_type 67 | 68 | def flatten_subscript(self, node): 69 | value = self.flatten(node.value) 70 | node_type = self.new_type() 71 | if isinstance(node.slice, ast.Index): 72 | index = self.flatten(node.slice.value) 73 | self.nodes.append(('z_index', [value, index], node_type)) 74 | else: 75 | lower = self.flatten(node.slice.lower) if node.slice.lower else None 76 | upper = self.flatten(node.slice.upper) if node.slice.upper else None 77 | if lower and upper is None: 78 | upper = lower 79 | elif lower is None and upper: 80 | lower = upper 81 | else: 82 | raise ValueError('hatlog expects only slice like [:x], [x:] or [x:y]') 83 | self.nodes.append(('z_slice', [value, lower, upper], node_type)) 84 | return node_type 85 | 86 | def flatten_num(self, node): 87 | if isinstance(node.n, int): 88 | return 'int' 89 | else: 90 | return 'float' 91 | 92 | def flatten_rec(self, node): 93 | ''' 94 | we know that functions return the same value 95 | prolog terms cant be rec so we = 96 | ''' 97 | if len(node.args) != len(self.args): 98 | raise ValueError("%s expected %d args" % (len(self.args))) 99 | for a, (_, b) in zip(node.args, self.args): 100 | c = self.flatten(a) 101 | self.nodes.append(('=', [c], b)) 102 | return self.return_type 103 | 104 | def flatten_str(self, node): 105 | return 'str' 106 | 107 | def flatten_compare(self, node): 108 | if len(node.comparators) != 1: 109 | raise ValueError("hatlog supports only 1 comparator") 110 | if isinstance(node.ops[0], ast.Eq): 111 | op = 'z_eq' 112 | else: 113 | op = 'z_cmp' 114 | a = self.flatten(node.left) 115 | b = self.flatten(node.comparators[0]) 116 | node_type = self.new_type() 117 | self.nodes.append((op, [a, b], node_type)) 118 | return node_type 119 | 120 | def flatten_list(self, node): 121 | if len(node.elts) == 0: 122 | sub_types = [self.new_type()] 123 | else: 124 | sub_types = [self.flatten(a) for a in node.elts] 125 | node_type = self.new_type() 126 | self.nodes.append(('z_list', sub_types, node_type)) 127 | return node_type 128 | 129 | def flatten_method_call(self, node): 130 | ''' 131 | A call with an 132 | attribute as func 133 | ''' 134 | receiver = self.flatten(node.func.value) 135 | args = list(map(self.flatten, node.args)) 136 | node_type = self.new_type() 137 | self.nodes.append(('z_method_call', [receiver, node.func.attr, args], node_type)) 138 | return node_type 139 | 140 | 141 | def flatten_dict(self, node): 142 | if len(node.keys) == 0: 143 | sub_types = [self.new_type(), self.new_type()] 144 | else: 145 | sub_types = zip([self.flatten(a) for a in node.keys], [self.flatten(b) for b in node.values]) 146 | node_type = self.new_type() 147 | self.nodes.append(('z_dict', sub_types, node_type)) 148 | return node_type 149 | 150 | def flatten_assign(self, node): 151 | if len(node.targets) != 1: 152 | raise ValueError("assignment normal") 153 | node.targets = node.targets[0] 154 | return self.default(node) 155 | 156 | def flatten_name(self, node): 157 | if node.id == 'True' or node.id == 'False': 158 | return 'bool' 159 | elif node.id == 'None': 160 | return 'void' 161 | else: 162 | name_type = self.env[node.id] 163 | if not name_type: 164 | name_type = self.new_type() 165 | self.env[node.id] = name_type 166 | return name_type 167 | 168 | def flatten_functiondef(self, node): 169 | self.args = [(arg.arg, self.new_type()) for arg in node.args.args] 170 | self.return_type = 'X' 171 | self.function = node.name 172 | self.env[node.name] = node.name 173 | self.env = Env(dict(self.args), self.env) 174 | [self.flatten(child) for child in node.body] 175 | self.env = self.env.parent 176 | self.nodes.append(('z_function', [a[1] for a in self.args], self.return_type)) 177 | return self.env[node.name] 178 | 179 | def flatten_expr(self, node): 180 | return self.flatten(node.value) 181 | 182 | def flatten_return(self, node): 183 | v = self.flatten(node.value) 184 | self.nodes.append(('=', [v], self.return_type)) 185 | return v 186 | 187 | def new_type(self): 188 | self.type_index += 1 189 | return 'Z%d' % self.type_index 190 | 191 | def to_snake_case(self, label): 192 | return re.sub(r'([a-z])([A-Z])', r'\1_\2', label).lower() 193 | 194 | # BinOp(2, BinOp(b, a)) 195 | 196 | # bin_op(X1, X2, X3) 197 | # bin_op(int, X3, X4) -------------------------------------------------------------------------------- /hatlog/prolog.py: -------------------------------------------------------------------------------- 1 | def generate_prolog(x, name, file): 2 | 3 | header = '''\ 4 | :- initialization main. 5 | 6 | :- use_module(pythonTypeSystem). 7 | :- use_module(prettyTypes). 8 | ''' 9 | fun = generate_fun(x, name) 10 | 11 | m = '''main :- 12 | open('%s.txt', write, Stream), 13 | ( 14 | f(%s, Z0, Z1), 15 | unvar(Z0, Z1, Z2, Z3, Z4), %% replace free vars with names 16 | pretty_args(Z2, Y), 17 | pretty_type(Z3, Z), 18 | pretty_generic(Z4, X), 19 | format(Stream, '~a::', [X]), 20 | write(Stream, Y), 21 | write(Stream, ' -> '), 22 | write(Stream, Z), 23 | write(Stream, '\\n'), 24 | 25 | true 26 | ), 27 | 28 | close(Stream), 29 | halt. 30 | main :- 31 | halt(1). 32 | ''' %(file, name) 33 | program = '%s\n%s\n%s' % (header, fun, m) 34 | with open('%s.pl' % file, 'w') as f: 35 | f.write(program) 36 | return '%s.pl' % file 37 | 38 | def generate_fun(x, name): 39 | head = 'f(%s, [%s], %s) :-' % (name, ', '.join(x[-1][1]), x[-1][-1]) 40 | # print(x[:-1]) 41 | block = ',\n '.join(['%s(%s)' % (a, ', '.join(map(generate_arg, args + [b]))) for a, args, b in x[:-1]]) 42 | return '%s\n %s.\n' % (head, block) 43 | 44 | def generate_arg(a): 45 | if isinstance(a, str): 46 | return a 47 | else: 48 | return '[%s]' % ', '.join(map(generate_arg, a)) 49 | 50 | -------------------------------------------------------------------------------- /prettyTypes.pl: -------------------------------------------------------------------------------- 1 | :- module(prettyTypes, [pretty_type/2, pretty_args/2, unvar/5, join/3, pretty_generic/2]). 2 | 3 | :- use_module(library(assoc)). 4 | :- use_module(library(pairs)). 5 | 6 | join(A, S, R) :- join_(A, S, '', R). 7 | join_([], _, S, S). 8 | join_([A], _, B, C) :- concat(B, A, C). 9 | join_([A | B], S, Input, Result) :- concat(Input, A, C), concat(C, S, Z), join_(B, S, Z, Result). 10 | pretty_args(A, Z) :- pretty_args_(A, Y), 11 | join(Y, ' -> ', Z). 12 | 13 | pretty_args_([], []). 14 | pretty_args_([A | T], [X | Y]) :- 15 | pretty_type(A, X), 16 | pretty_args_(T, Y). 17 | 18 | pretty_inner(A, Z) :- 19 | pretty_args_(A, Y), 20 | join(Y, ',', Z). 21 | 22 | pretty_type(Type, Z) :- 23 | var(Type), 24 | format(atom(Z), '~p', [Type]); 25 | pretty_z(Type, Z). 26 | 27 | pretty_z([list | Z], X) :- 28 | pretty_inner(Z, Args), 29 | format(atom(X), 'List[~p]', [Args]). 30 | 31 | pretty_z([dict | Z], X) :- 32 | pretty_inner(Z, Args), 33 | format(atom(X), 'Dict[~p]', [Args]). 34 | 35 | pretty_z([function, Argz, Ret], X) :- 36 | pretty_inner(Argz, Args), 37 | pretty_type(Ret, Return), 38 | format(atom(X), 'Callable[[~p],~p]', [Args, Return]). 39 | 40 | pretty_z(void, 'None'). 41 | 42 | pretty_z(Type, Z) :- 43 | atom(Type), 44 | format(atom(Z), "~a", [Type]). 45 | 46 | 47 | 48 | unvar(Args, Return, UArgs, UReturn, GenericId) :- 49 | assoc:list_to_assoc([], Vars1), 50 | replace_vars(Args, UArgs, Vars1, Vars2, 1, L), 51 | replace_vars(Return, UReturn, Vars2, _, L, GenericId). 52 | 53 | replace_vars(Val, UVal, Vars, NewVars, L, Z) :- 54 | var(Val), 55 | replace_var(Val, UVal, Vars, NewVars, L, Z); 56 | 57 | replace_vars_(Val, UVal, Vars, NewVars, L, Z). 58 | 59 | replace_var(Value, UValue, Vars, NewVars, L, Z) :- 60 | format(atom(A0), '~p', Value), 61 | writeln(A0), 62 | ( get_assoc(A0, Vars, A1) -> 63 | Vars = NewVars, % var exists 64 | UValue = A1, 65 | Z = L 66 | ; format(atom(A0), '~p', Value), 67 | Z is L + 1, M is L - 1, 68 | format("~w~w\n", [M,L]), 69 | sub_atom('ABCDEF', M, 1, _, UValue), 70 | put_assoc(A0, Vars, UValue, NewVars) 71 | ). 72 | 73 | replace_vars_([], [], Vars, Vars, L, L). 74 | replace_vars_([A | B], [UA | UB], Vars, NewVars, L, Z) :- 75 | replace_vars(A, UA, Vars, Vars1, L, L1), 76 | replace_vars_(B, UB, Vars1, NewVars, L1, Z). 77 | 78 | replace_vars_(Value, Value, Vars, Vars, L, L). 79 | 80 | pretty_generic(GenericId, Generics) :- 81 | Index is GenericId - 1, 82 | sub_atom('ABCDEF', 0, Index, _, Sub), 83 | atom_chars(Sub, Vars), 84 | join(Vars, ',', Generics). 85 | 86 | %% prettyTypes:unvar([A0], [e], A1, A2). -------------------------------------------------------------------------------- /pythonTypeSystem.pl: -------------------------------------------------------------------------------- 1 | :- module(pythonTypeSystem, [z_list/2, 2 | is_number/1, z_assign/3, z_call/3, z_method_call/4, z_bin_op/3, 3 | z_cmp/3, z_eq/3, 4 | z_fcall/3, z_unary_op/2, z_aug_assign/3, z_slice/4, z_index/3, 5 | z_if/4, z_for/4, m/4, sequence/1, f/3]). 6 | 7 | z_list([], _). 8 | z_list([H], [list, H]). 9 | z_list_([H, H | T], [list, H]) :- z_list(T, [list, H]). % hom list 10 | 11 | z_dict([], _). 12 | z_dict([Y, Z], [dict, Y, Z]) :- hashable(Y). 13 | z_dict([Y, Z, Y, Z | T], [dict, Y, Z]) :- hashable(Y), z_dict(T, [dict, Y, Z]). % hom dict 14 | 15 | comparable(int). 16 | comparable(float). 17 | 18 | is_number(int). 19 | is_number(float). 20 | 21 | sequence([list, _]). 22 | sequence([dict, _, _]). 23 | 24 | hashable(int). 25 | hashable(float). 26 | hashable(string). 27 | hashable(bool). 28 | 29 | 30 | element_of(A, [list, A]). 31 | element_of(A, [dict, A, _]). 32 | 33 | z_assign(A, A, void). 34 | z_aug_assign(A, A, void). 35 | z_call(Function, Args, Result) :- f(Function, Args, Result). 36 | z_method_call(Receiver, Message, Args, Result) :- m(Receiver, Message, Args, Result). 37 | z_fcall([function, Args, Res], Args, Res). 38 | 39 | z_bin_op(int, int, int). 40 | z_bin_op(str, str, str). 41 | z_bin_op(A, B, float) :- is_number(A), is_number(B). 42 | % union([union | T], T). 43 | z_cmp(A, A, bool) :- comparable(A). 44 | z_eq(A, A, bool). 45 | 46 | z_if(bool, _, _, _). % test if_true if_false result 47 | z_for(Element, Sequence, _, void) :- sequence(Sequence), element_of(Element, Sequence). 48 | 49 | z_unary_op(int, int). 50 | z_unary_op(float, float). 51 | 52 | z_index([list, X], int, X). 53 | z_index([dict, X, Y], X, Y). 54 | z_index(str, int, str). 55 | 56 | z_slice([list, X], int, int, [list, X]). 57 | z_slice(str, int, int, str). 58 | 59 | 60 | m([list, A], append, [A], void). 61 | m([list, A], pop, [], A). 62 | m([list, A], extend, [[list, A]], void). 63 | m([list, A], index, [A], int). 64 | m([list, A], index, [A, int], int). 65 | m([list, A], index, [A, int, int], int). 66 | 67 | 68 | m([dict, A, B], get, [A, B], B). 69 | m([dict, A, _], keys, [list, A]). 70 | m([dict, _, A], values, [list, A]). 71 | m(string, join, [[list, string]], string). 72 | m(string, split, [string], [list, string]). 73 | 74 | f(len, [[list, _]], int). 75 | f(sorted, [[list, A]], [list, A]). 76 | 77 | --------------------------------------------------------------------------------