From 5893afdacd1b8f37c5d8aee8ade71064747dda27 Mon Sep 17 00:00:00 2001 From: Lars Wirzenius Date: Fri, 17 May 2019 09:36:19 +0300 Subject: Add: example proof-of-concept code generation --- bindings.yaml | 8 ++++++++ codegen.py | 40 ++++++++++++++++++++++++++++++++++++++++ funcs.py | 8 ++++++++ prelude.py | 1 + scenario.txt | 3 +++ 5 files changed, 60 insertions(+) create mode 100644 bindings.yaml create mode 100644 codegen.py create mode 100644 funcs.py create mode 100644 prelude.py create mode 100644 scenario.txt diff --git a/bindings.yaml b/bindings.yaml new file mode 100644 index 0000000..7dbe4cc --- /dev/null +++ b/bindings.yaml @@ -0,0 +1,8 @@ +- pattern: given some precondition + function: given_precondition + +- pattern: when (?P\S+) does something + function: do + +- pattern: then all if fine + function: is_fine diff --git a/codegen.py b/codegen.py new file mode 100644 index 0000000..6e8aac2 --- /dev/null +++ b/codegen.py @@ -0,0 +1,40 @@ +import json +import re +import sys +import yaml + + +def find_binding(binds, step): + for bind in binds: + m = re.match(bind['pattern'], step, re.I | re.M) + if m is not None: + return new_match(bind, m) + return None + + +def new_match(bind, match): + return { + 'function': bind['function'], + 'args': match.groupdict(), + } + + +def codegen(f, match): + f.write('args = {}\n'.format(json.dumps(match['args']))) + f.write('{}(**args)\n'.format(match['function'])) + + + +with open('bindings.yaml') as f: + binds = yaml.safe_load(f) + + +with open('prelude.py') as f: + sys.stdout.write(f.read()) + + +with open('scenario.txt') as scenario: + for step in scenario: + match = find_binding(binds, step) + if match is not None: + codegen(sys.stdout, match) diff --git a/funcs.py b/funcs.py new file mode 100644 index 0000000..73b11a0 --- /dev/null +++ b/funcs.py @@ -0,0 +1,8 @@ +def given_precondition(**kwargs): + print('precondition:', kwargs) + +def do(**kwargs): + print('do:', kwargs) + +def is_fine(**kwargs): + print('is_fine:', kwargs) diff --git a/prelude.py b/prelude.py new file mode 100644 index 0000000..30204a4 --- /dev/null +++ b/prelude.py @@ -0,0 +1 @@ +from funcs import * diff --git a/scenario.txt b/scenario.txt new file mode 100644 index 0000000..6d2fc1d --- /dev/null +++ b/scenario.txt @@ -0,0 +1,3 @@ +given some precondition +when Tomjon does something +then all if fine -- cgit v1.2.1