From 5ce873e545ecd77710c63dfa3f3bbb3d41fe3aa0 Mon Sep 17 00:00:00 2001 From: Timotej Lazar Date: Thu, 23 Feb 2017 16:06:46 +0100 Subject: Modify Prolog parser to produce ASTs instead of parse trees --- prolog/util.py | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) (limited to 'prolog/util.py') diff --git a/prolog/util.py b/prolog/util.py index 402b920..d5c5050 100644 --- a/prolog/util.py +++ b/prolog/util.py @@ -1,5 +1,5 @@ # CodeQ: an online programming tutor. -# Copyright (C) 2015 UL FRI +# Copyright (C) 2015-2017 UL FRI # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free @@ -75,9 +75,34 @@ def stringify(obj): if obj.type in operators.values(): return ' ' + str(obj) + ' ' return str(obj) + + if isinstance(obj, Tree): + label = obj.label() + children = [stringify(child) for child in obj] + if label == 'text': + return ' '.join(children) + elif label == 'clause': + if len(children) == 1: + return children[0] + '.' + elif len(children) == 2: + return children[0] + ' :- ' + children[1] + '.' + elif label == 'directive': + return ':- ' + children[0] + '.' + elif label == 'or': + return ' ; '.join(children) + elif label == 'if': + return ' -> '.join(children) + elif label == 'and': + return ', '.join(children) + elif label == 'compound': + return children[0] + '(' + (children[1] if len(children) > 1 else '') + ')' + elif label == 'args': + return ','.join(children) + elif label == 'list': + # TODO pretty print + return '[' + '|'.join(children) + ']' + if isinstance(obj, Iterable): - if isinstance(obj, Tree) and obj.label() == 'clause': - return ''.join([stringify(child) for child in obj]) + '\n' return ''.join([stringify(child) for child in obj]) # Return a canonical name for the [n]th variable in scope. -- cgit v1.2.1