提交 ef801a9b 编写于 作者: M Markus Armbruster

qapi: Prefer single-quoted strings more consistently

PEP 8 advises:

    In Python, single-quoted strings and double-quoted strings are the
    same.  This PEP does not make a recommendation for this.  Pick a
    rule and stick to it.  When a string contains single or double
    quote characters, however, use the other one to avoid backslashes
    in the string.  It improves readability.

The QAPI generators succeed at picking a rule, but fail at sticking to
it.  Convert a bunch of double-quoted strings to single-quoted ones.
Signed-off-by: NMarkus Armbruster <armbru@redhat.com>
Reviewed-by: NEric Blake <eblake@redhat.com>
Message-Id: <1489582656-31133-20-git-send-email-armbru@redhat.com>
上级 0fe675af
...@@ -223,7 +223,7 @@ fdecl.write(mcgen(''' ...@@ -223,7 +223,7 @@ fdecl.write(mcgen('''
''', ''',
prefix=prefix)) prefix=prefix))
event_enum_name = c_name(prefix + "QAPIEvent", protect=False) event_enum_name = c_name(prefix + 'QAPIEvent', protect=False)
schema = QAPISchema(input_file) schema = QAPISchema(input_file)
gen = QAPISchemaGenEventVisitor() gen = QAPISchemaGenEventVisitor()
......
...@@ -170,10 +170,10 @@ const char %(c_name)s[] = %(c_string)s; ...@@ -170,10 +170,10 @@ const char %(c_name)s[] = %(c_string)s;
opt_unmask = False opt_unmask = False
(input_file, output_dir, do_c, do_h, prefix, opts) = \ (input_file, output_dir, do_c, do_h, prefix, opts) = \
parse_command_line("u", ["unmask-non-abi-names"]) parse_command_line('u', ['unmask-non-abi-names'])
for o, a in opts: for o, a in opts:
if o in ("-u", "--unmask-non-abi-names"): if o in ('-u', '--unmask-non-abi-names'):
opt_unmask = True opt_unmask = True
c_comment = ''' c_comment = '''
......
...@@ -244,10 +244,10 @@ class QAPISchemaGenTypeVisitor(QAPISchemaVisitor): ...@@ -244,10 +244,10 @@ class QAPISchemaGenTypeVisitor(QAPISchemaVisitor):
do_builtins = False do_builtins = False
(input_file, output_dir, do_c, do_h, prefix, opts) = \ (input_file, output_dir, do_c, do_h, prefix, opts) = \
parse_command_line("b", ["builtins"]) parse_command_line('b', ['builtins'])
for o, a in opts: for o, a in opts:
if o in ("-b", "--builtins"): if o in ('-b', '--builtins'):
do_builtins = True do_builtins = True
c_comment = ''' c_comment = '''
......
...@@ -335,10 +335,10 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor): ...@@ -335,10 +335,10 @@ class QAPISchemaGenVisitVisitor(QAPISchemaVisitor):
do_builtins = False do_builtins = False
(input_file, output_dir, do_c, do_h, prefix, opts) = \ (input_file, output_dir, do_c, do_h, prefix, opts) = \
parse_command_line("b", ["builtins"]) parse_command_line('b', ['builtins'])
for o, a in opts: for o, a in opts:
if o in ("-b", "--builtins"): if o in ('-b', '--builtins'):
do_builtins = True do_builtins = True
c_comment = ''' c_comment = '''
......
...@@ -58,9 +58,9 @@ all_names = {} ...@@ -58,9 +58,9 @@ all_names = {}
def error_path(parent): def error_path(parent):
res = "" res = ''
while parent: while parent:
res = ("In file included from %s:%d:\n" % (parent['file'], res = ('In file included from %s:%d:\n' % (parent['file'],
parent['line'])) + res parent['line'])) + res
parent = parent['parent'] parent = parent['parent']
return res return res
...@@ -76,10 +76,10 @@ class QAPIError(Exception): ...@@ -76,10 +76,10 @@ class QAPIError(Exception):
self.msg = msg self.msg = msg
def __str__(self): def __str__(self):
loc = "%s:%d" % (self.fname, self.line) loc = '%s:%d' % (self.fname, self.line)
if self.col is not None: if self.col is not None:
loc += ":%s" % self.col loc += ':%s' % self.col
return error_path(self.info) + "%s: %s" % (loc, self.msg) return error_path(self.info) + '%s: %s' % (loc, self.msg)
class QAPIParseError(QAPIError): class QAPIParseError(QAPIError):
...@@ -113,7 +113,7 @@ class QAPIDoc(object): ...@@ -113,7 +113,7 @@ class QAPIDoc(object):
self.content.append(line) self.content.append(line)
def __repr__(self): def __repr__(self):
return "\n".join(self.content).strip() return '\n'.join(self.content).strip()
class ArgSection(Section): class ArgSection(Section):
def __init__(self, name): def __init__(self, name):
...@@ -163,8 +163,8 @@ class QAPIDoc(object): ...@@ -163,8 +163,8 @@ class QAPIDoc(object):
# recognized, and get silently treated as ordinary text # recognized, and get silently treated as ordinary text
if self.symbol: if self.symbol:
self._append_symbol_line(line) self._append_symbol_line(line)
elif not self.body.content and line.startswith("@"): elif not self.body.content and line.startswith('@'):
if not line.endswith(":"): if not line.endswith(':'):
raise QAPIParseError(self.parser, "Line should end with :") raise QAPIParseError(self.parser, "Line should end with :")
self.symbol = line[1:-1] self.symbol = line[1:-1]
# FIXME invalid names other than the empty string aren't flagged # FIXME invalid names other than the empty string aren't flagged
...@@ -176,14 +176,14 @@ class QAPIDoc(object): ...@@ -176,14 +176,14 @@ class QAPIDoc(object):
def _append_symbol_line(self, line): def _append_symbol_line(self, line):
name = line.split(' ', 1)[0] name = line.split(' ', 1)[0]
if name.startswith("@") and name.endswith(":"): if name.startswith('@') and name.endswith(':'):
line = line[len(name)+1:] line = line[len(name)+1:]
self._start_args_section(name[1:-1]) self._start_args_section(name[1:-1])
elif name in ("Returns:", "Since:", elif name in ('Returns:', 'Since:',
# those are often singular or plural # those are often singular or plural
"Note:", "Notes:", 'Note:', 'Notes:',
"Example:", "Examples:", 'Example:', 'Examples:',
"TODO:"): 'TODO:'):
line = line[len(name)+1:] line = line[len(name)+1:]
self._start_section(name[:-1]) self._start_section(name[:-1])
...@@ -203,8 +203,8 @@ class QAPIDoc(object): ...@@ -203,8 +203,8 @@ class QAPIDoc(object):
self.section = QAPIDoc.ArgSection(name) self.section = QAPIDoc.ArgSection(name)
self.args[name] = self.section self.args[name] = self.section
def _start_section(self, name=""): def _start_section(self, name=''):
if name in ("Returns", "Since") and self.has_section(name): if name in ('Returns', 'Since') and self.has_section(name):
raise QAPIParseError(self.parser, raise QAPIParseError(self.parser,
"Duplicated '%s' section" % name) "Duplicated '%s' section" % name)
self.section = QAPIDoc.Section(name) self.section = QAPIDoc.Section(name)
...@@ -217,7 +217,7 @@ class QAPIDoc(object): ...@@ -217,7 +217,7 @@ class QAPIDoc(object):
and line and not line[0].isspace()): and line and not line[0].isspace()):
self._start_section() self._start_section()
if (in_arg or not self.section.name if (in_arg or not self.section.name
or not self.section.name.startswith("Example")): or not self.section.name.startswith('Example')):
line = line.strip() line = line.strip()
# TODO Drop this once the dust has settled # TODO Drop this once the dust has settled
if (isinstance(self.section, QAPIDoc.ArgSection) if (isinstance(self.section, QAPIDoc.ArgSection)
...@@ -262,7 +262,7 @@ class QAPISchemaParser(object): ...@@ -262,7 +262,7 @@ class QAPISchemaParser(object):
if 'include' in expr: if 'include' in expr:
if len(expr) != 1: if len(expr) != 1:
raise QAPISemError(info, "Invalid 'include' directive") raise QAPISemError(info, "Invalid 'include' directive")
include = expr["include"] include = expr['include']
if not isinstance(include, str): if not isinstance(include, str):
raise QAPISemError(info, raise QAPISemError(info,
"Value of 'include' must be a string") "Value of 'include' must be a string")
...@@ -347,7 +347,7 @@ class QAPISchemaParser(object): ...@@ -347,7 +347,7 @@ class QAPISchemaParser(object):
if not skip_comment: if not skip_comment:
self.val = self.src[self.pos:self.cursor] self.val = self.src[self.pos:self.cursor]
return return
elif self.tok in "{}:,[]": elif self.tok in '{}:,[]':
return return
elif self.tok == "'": elif self.tok == "'":
string = '' string = ''
...@@ -373,7 +373,7 @@ class QAPISchemaParser(object): ...@@ -373,7 +373,7 @@ class QAPISchemaParser(object):
for _ in range(0, 4): for _ in range(0, 4):
ch = self.src[self.cursor] ch = self.src[self.cursor]
self.cursor += 1 self.cursor += 1
if ch not in "0123456789abcdefABCDEF": if ch not in '0123456789abcdefABCDEF':
raise QAPIParseError(self, raise QAPIParseError(self,
'\\u escape needs 4 ' '\\u escape needs 4 '
'hex digits') 'hex digits')
...@@ -388,28 +388,28 @@ class QAPISchemaParser(object): ...@@ -388,28 +388,28 @@ class QAPISchemaParser(object):
'only supports non-zero ' 'only supports non-zero '
'values up to \\u007f') 'values up to \\u007f')
string += chr(value) string += chr(value)
elif ch in "\\/'\"": elif ch in '\\/\'"':
string += ch string += ch
else: else:
raise QAPIParseError(self, raise QAPIParseError(self,
"Unknown escape \\%s" % ch) "Unknown escape \\%s" % ch)
esc = False esc = False
elif ch == "\\": elif ch == '\\':
esc = True esc = True
elif ch == "'": elif ch == "'":
self.val = string self.val = string
return return
else: else:
string += ch string += ch
elif self.src.startswith("true", self.pos): elif self.src.startswith('true', self.pos):
self.val = True self.val = True
self.cursor += 3 self.cursor += 3
return return
elif self.src.startswith("false", self.pos): elif self.src.startswith('false', self.pos):
self.val = False self.val = False
self.cursor += 4 self.cursor += 4
return return
elif self.src.startswith("null", self.pos): elif self.src.startswith('null', self.pos):
self.val = None self.val = None
self.cursor += 3 self.cursor += 3
return return
...@@ -523,11 +523,11 @@ def find_alternate_member_qtype(qapi_type): ...@@ -523,11 +523,11 @@ def find_alternate_member_qtype(qapi_type):
if qapi_type in builtin_types: if qapi_type in builtin_types:
return builtin_types[qapi_type] return builtin_types[qapi_type]
elif find_struct(qapi_type): elif find_struct(qapi_type):
return "QTYPE_QDICT" return 'QTYPE_QDICT'
elif find_enum(qapi_type): elif find_enum(qapi_type):
return "QTYPE_QSTRING" return 'QTYPE_QSTRING'
elif find_union(qapi_type): elif find_union(qapi_type):
return "QTYPE_QDICT" return 'QTYPE_QDICT'
return None return None
...@@ -628,7 +628,7 @@ def find_union(name): ...@@ -628,7 +628,7 @@ def find_union(name):
def add_enum(name, info, enum_values=None, implicit=False): def add_enum(name, info, enum_values=None, implicit=False):
global enum_types global enum_types
add_name(name, info, 'enum', implicit) add_name(name, info, 'enum', implicit)
enum_types.append({"enum_name": name, "enum_values": enum_values}) enum_types.append({'enum_name': name, 'enum_values': enum_values})
def find_enum(name): def find_enum(name):
...@@ -788,7 +788,7 @@ def check_union(expr, info): ...@@ -788,7 +788,7 @@ def check_union(expr, info):
raise QAPISemError(info, raise QAPISemError(info,
"Discriminator value '%s' is not found in " "Discriminator value '%s' is not found in "
"enum '%s'" "enum '%s'"
% (key, enum_define["enum_name"])) % (key, enum_define['enum_name']))
# If discriminator is user-defined, ensure all values are covered # If discriminator is user-defined, ensure all values are covered
if enum_define: if enum_define:
...@@ -993,7 +993,7 @@ def check_definition_doc(doc, expr, info): ...@@ -993,7 +993,7 @@ def check_definition_doc(doc, expr, info):
args = set([name.strip('*') for name in args]) args = set([name.strip('*') for name in args])
if not doc_args.issubset(args): if not doc_args.issubset(args):
raise QAPISemError(info, "The following documented members are not in " raise QAPISemError(info, "The following documented members are not in "
"the declaration: %s" % ", ".join(doc_args - args)) "the declaration: %s" % ', '.join(doc_args - args))
def check_docs(docs): def check_docs(docs):
...@@ -1487,7 +1487,7 @@ class QAPISchemaEvent(QAPISchemaEntity): ...@@ -1487,7 +1487,7 @@ class QAPISchemaEvent(QAPISchemaEntity):
class QAPISchema(object): class QAPISchema(object):
def __init__(self, fname): def __init__(self, fname):
try: try:
parser = QAPISchemaParser(open(fname, "r")) parser = QAPISchemaParser(open(fname, 'r'))
self.exprs = check_exprs(parser.exprs) self.exprs = check_exprs(parser.exprs)
self.docs = check_docs(parser.docs) self.docs = check_docs(parser.docs)
self._entity_dict = {} self._entity_dict = {}
...@@ -1740,8 +1740,8 @@ def camel_to_upper(value): ...@@ -1740,8 +1740,8 @@ def camel_to_upper(value):
l = len(c_fun_str) l = len(c_fun_str)
for i in range(l): for i in range(l):
c = c_fun_str[i] c = c_fun_str[i]
# When c is upper and no "_" appears before, do more checks # When c is upper and no '_' appears before, do more checks
if c.isupper() and (i > 0) and c_fun_str[i - 1] != "_": if c.isupper() and (i > 0) and c_fun_str[i - 1] != '_':
if i < l - 1 and c_fun_str[i + 1].islower(): if i < l - 1 and c_fun_str[i + 1].islower():
new_name += '_' new_name += '_'
elif c_fun_str[i - 1].isdigit(): elif c_fun_str[i - 1].isdigit():
...@@ -1760,7 +1760,7 @@ c_name_trans = string.maketrans('.-', '__') ...@@ -1760,7 +1760,7 @@ c_name_trans = string.maketrans('.-', '__')
# Map @name to a valid C identifier. # Map @name to a valid C identifier.
# If @protect, avoid returning certain ticklish identifiers (like # If @protect, avoid returning certain ticklish identifiers (like
# C keywords) by prepending "q_". # C keywords) by prepending 'q_'.
# #
# Used for converting 'name' from a 'name':'type' qapi definition # Used for converting 'name' from a 'name':'type' qapi definition
# into a generated struct member, as well as converting type names # into a generated struct member, as well as converting type names
...@@ -1798,7 +1798,7 @@ def c_name(name, protect=True): ...@@ -1798,7 +1798,7 @@ def c_name(name, protect=True):
name = name.translate(c_name_trans) name = name.translate(c_name_trans)
if protect and (name in c89_words | c99_words | c11_words | gcc_words if protect and (name in c89_words | c99_words | c11_words | gcc_words
| cpp_words | polluted_words): | cpp_words | polluted_words):
return "q_" + name return 'q_' + name
return name return name
eatspace = '\033EATSPACE.' eatspace = '\033EATSPACE.'
...@@ -1806,9 +1806,9 @@ pointer_suffix = ' *' + eatspace ...@@ -1806,9 +1806,9 @@ pointer_suffix = ' *' + eatspace
def genindent(count): def genindent(count):
ret = "" ret = ''
for _ in range(count): for _ in range(count):
ret += " " ret += ' '
return ret return ret
indent_level = 0 indent_level = 0
...@@ -1948,26 +1948,26 @@ def gen_params(arg_type, boxed, extra): ...@@ -1948,26 +1948,26 @@ def gen_params(arg_type, boxed, extra):
# #
def parse_command_line(extra_options="", extra_long_options=[]): def parse_command_line(extra_options='', extra_long_options=[]):
try: try:
opts, args = getopt.gnu_getopt(sys.argv[1:], opts, args = getopt.gnu_getopt(sys.argv[1:],
"chp:o:" + extra_options, 'chp:o:' + extra_options,
["source", "header", "prefix=", ['source', 'header', 'prefix=',
"output-dir="] + extra_long_options) 'output-dir='] + extra_long_options)
except getopt.GetoptError as err: except getopt.GetoptError as err:
print >>sys.stderr, "%s: %s" % (sys.argv[0], str(err)) print >>sys.stderr, "%s: %s" % (sys.argv[0], str(err))
sys.exit(1) sys.exit(1)
output_dir = "" output_dir = ''
prefix = "" prefix = ''
do_c = False do_c = False
do_h = False do_h = False
extra_opts = [] extra_opts = []
for oa in opts: for oa in opts:
o, a = oa o, a = oa
if o in ("-p", "--prefix"): if o in ('-p', '--prefix'):
match = re.match(r'([A-Za-z_.-][A-Za-z0-9_.-]*)?', a) match = re.match(r'([A-Za-z_.-][A-Za-z0-9_.-]*)?', a)
if match.end() != len(a): if match.end() != len(a):
print >>sys.stderr, \ print >>sys.stderr, \
...@@ -1975,11 +1975,11 @@ def parse_command_line(extra_options="", extra_long_options=[]): ...@@ -1975,11 +1975,11 @@ def parse_command_line(extra_options="", extra_long_options=[]):
% (sys.argv[0], a[match.end()]) % (sys.argv[0], a[match.end()])
sys.exit(1) sys.exit(1)
prefix = a prefix = a
elif o in ("-o", "--output-dir"): elif o in ('-o', '--output-dir'):
output_dir = a + "/" output_dir = a + '/'
elif o in ("-c", "--source"): elif o in ('-c', '--source'):
do_c = True do_c = True
elif o in ("-h", "--header"): elif o in ('-h', '--header'):
do_h = True do_h = True
else: else:
extra_opts.append(oa) extra_opts.append(oa)
......
...@@ -50,7 +50,7 @@ def subst_vars(doc): ...@@ -50,7 +50,7 @@ def subst_vars(doc):
def subst_braces(doc): def subst_braces(doc):
"""Replaces {} with @{ @}""" """Replaces {} with @{ @}"""
return doc.replace("{", "@{").replace("}", "@}") return doc.replace('{', '@{').replace('}', '@}')
def texi_example(doc): def texi_example(doc):
...@@ -79,10 +79,10 @@ def texi_format(doc): ...@@ -79,10 +79,10 @@ def texi_format(doc):
doc = subst_vars(doc) doc = subst_vars(doc)
doc = subst_emph(doc) doc = subst_emph(doc)
doc = subst_strong(doc) doc = subst_strong(doc)
inlist = "" inlist = ''
lastempty = False lastempty = False
for line in doc.split('\n'): for line in doc.split('\n'):
empty = line == "" empty = line == ''
# FIXME: Doing this in a single if / elif chain is # FIXME: Doing this in a single if / elif chain is
# problematic. For instance, a line without markup terminates # problematic. For instance, a line without markup terminates
...@@ -92,35 +92,35 @@ def texi_format(doc): ...@@ -92,35 +92,35 @@ def texi_format(doc):
# #
# Make sure to update section "Documentation markup" in # Make sure to update section "Documentation markup" in
# docs/qapi-code-gen.txt when fixing this. # docs/qapi-code-gen.txt when fixing this.
if line.startswith("| "): if line.startswith('| '):
line = EXAMPLE_FMT(code=line[2:]) line = EXAMPLE_FMT(code=line[2:])
elif line.startswith("= "): elif line.startswith('= '):
line = "@section " + line[2:] line = '@section ' + line[2:]
elif line.startswith("== "): elif line.startswith('== '):
line = "@subsection " + line[3:] line = '@subsection ' + line[3:]
elif re.match(r'^([0-9]*\.) ', line): elif re.match(r'^([0-9]*\.) ', line):
if not inlist: if not inlist:
lines.append("@enumerate") lines.append('@enumerate')
inlist = "enumerate" inlist = 'enumerate'
line = line[line.find(" ")+1:] line = line[line.find(' ')+1:]
lines.append("@item") lines.append('@item')
elif re.match(r'^[*-] ', line): elif re.match(r'^[*-] ', line):
if not inlist: if not inlist:
lines.append("@itemize %s" % {'*': "@bullet", lines.append('@itemize %s' % {'*': '@bullet',
'-': "@minus"}[line[0]]) '-': '@minus'}[line[0]])
inlist = "itemize" inlist = 'itemize'
lines.append("@item") lines.append('@item')
line = line[2:] line = line[2:]
elif lastempty and inlist: elif lastempty and inlist:
lines.append("@end %s\n" % inlist) lines.append('@end %s\n' % inlist)
inlist = "" inlist = ''
lastempty = empty lastempty = empty
lines.append(line) lines.append(line)
if inlist: if inlist:
lines.append("@end %s\n" % inlist) lines.append('@end %s\n' % inlist)
return "\n".join(lines) return '\n'.join(lines)
def texi_body(doc): def texi_body(doc):
...@@ -158,12 +158,12 @@ def texi_sections(doc): ...@@ -158,12 +158,12 @@ def texi_sections(doc):
for section in doc.sections: for section in doc.sections:
name, doc = (section.name, str(section)) name, doc = (section.name, str(section))
func = texi_format func = texi_format
if name.startswith("Example"): if name.startswith('Example'):
func = texi_example func = texi_example
if name: if name:
# prefer @b over @strong, so txt doesn't translate it to *Foo:* # prefer @b over @strong, so txt doesn't translate it to *Foo:*
body += "\n\n@b{%s:}\n" % name body += '\n\n@b{%s:}\n' % name
body += func(doc) body += func(doc)
return body return body
...@@ -269,5 +269,5 @@ def main(argv): ...@@ -269,5 +269,5 @@ def main(argv):
print texi_schema(schema) print texi_schema(schema)
if __name__ == "__main__": if __name__ == '__main__':
main(sys.argv) main(sys.argv)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册