Improved auto-generated source code readability

This commit is contained in:
Lonami 2016-09-05 19:12:14 +02:00
parent 251c1830a5
commit 7802fe5487
4 changed files with 44 additions and 8 deletions

View File

@ -7,6 +7,9 @@ class SourceBuilder:
self.indent_size = indent_size
self.out_stream = out_stream
# Was a new line added automatically before? If so, avoid it
self.auto_added_line = False
def indent(self):
"""Indents the current source code line by the current indentation level"""
self.write(' ' * (self.current_indent * self.indent_size))
@ -29,10 +32,17 @@ class SourceBuilder:
if string and string[-1] == ':':
self.current_indent += 1
# Clear state after the user adds a new line
self.auto_added_line = False
def end_block(self):
"""Ends an indentation block, leaving an empty line afterwards"""
self.current_indent -= 1
# If we did not add a new line automatically yet, now it's the time!
if not self.auto_added_line:
self.writeln()
self.auto_added_line = True
def __str__(self):
self.out_stream.seek(0)

View File

@ -73,7 +73,7 @@ class TLObject:
result=match.group(3),
is_function=is_function)
def __str__(self):
def __repr__(self):
fullname = ('{}.{}'.format(self.namespace, self.name) if self.namespace is not None
else self.name)
@ -84,6 +84,23 @@ class TLObject:
' '.join([str(arg) for arg in self.args]),
self.result)
def __str__(self):
fullname = ('{}.{}'.format(self.namespace, self.name) if self.namespace is not None
else self.name)
# Some arguments are not valid for being represented, such as the flag indicator or generic definition
# (these have no explicit values until used)
valid_args = [arg for arg in self.args
if not arg.flag_indicator and not arg.generic_definition]
args = ', '.join(['{} = {{}}'.format(arg.name) for arg in valid_args])
args_format = ', '.join(['self.{}'.format(arg.name) for arg in valid_args])
return ("'({} (ID: {}) = ({}))'.format({})"
.format(fullname, hex(self.id), args, args_format))
class TLArg:
def __init__(self, name, type, generic_definition):

View File

@ -137,6 +137,15 @@ def generate_tlobjects(scheme_file):
builder.writeln('pass')
builder.end_block()
# Write the __repr__(self) and __str__(self) functions
builder.writeln('def __repr__(self):')
builder.writeln("return '{}'".format(repr(tlobject)))
builder.end_block()
builder.writeln('def __str__(self):')
builder.writeln("return {}".format(str(tlobject)))
# builder.end_block() # There is no need to end the last block
# Once all the objects have been generated, we can now group them in a single file
filename = os.path.join('tl', 'all_tlobjects.py')
with open(filename, 'w', encoding='utf-8') as file: