From 81734ed3a12dec92cd918d01e73150c4c0ce6cb2 Mon Sep 17 00:00:00 2001 From: gregorni Date: Thu, 20 Jul 2023 18:43:01 +0200 Subject: [PATCH] Moved formatting logic to separate file Also updated branch --- blueprintcompiler/formatter.py | 51 ++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 blueprintcompiler/formatter.py diff --git a/blueprintcompiler/formatter.py b/blueprintcompiler/formatter.py new file mode 100644 index 0000000..03c82a8 --- /dev/null +++ b/blueprintcompiler/formatter.py @@ -0,0 +1,51 @@ +# decompiler.py +# +# Copyright 2021 James Westman +# +# This file is free software; you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This file is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this program. If not, see . +# +# SPDX-License-Identifier: LGPL-3.0-or-later + +from . import tokenizer + +newline_after = [";", "]"] +opening_tokens = ["{"] +closing_tokens = ["}"] + + +class Format: + def format(data): + indent_levels = 0 + tokens = tokenizer.tokenize(data) + + tokenized_str = "" + for index, item in enumerate(tokens): + if item.type != tokenizer.TokenType.WHITESPACE: + tokenized_str += str(item) + if str(item) in opening_tokens: + indent_levels += 1 + + try: + if str(tokens[index + 1]) in closing_tokens: + indent_levels -= 1 + except: + pass + + if str(item) in newline_after + closing_tokens + opening_tokens: + tokenized_str += "\n" + tokenized_str += indent_levels * " " + else: + tokenized_str += " " + + return tokenized_str