1#!/usr/bin/env python
2# A tool to parse the FormatStyle struct from Format.h and update the
3# documentation in ../ClangFormatStyleOptions.rst automatically.
4# Run from the directory in which this file is located to update the docs.
5
6import collections
7import os
8import re
9
10CLANG_DIR = os.path.join(os.path.dirname(__file__), '../..')
11FORMAT_STYLE_FILE = os.path.join(CLANG_DIR, 'include/clang/Format/Format.h')
12INCLUDE_STYLE_FILE = os.path.join(CLANG_DIR, 'include/clang/Tooling/Inclusions/IncludeStyle.h')
13DOC_FILE = os.path.join(CLANG_DIR, 'docs/ClangFormatStyleOptions.rst')
14
15
16def substitute(text, tag, contents):
17  replacement = '\n.. START_%s\n\n%s\n\n.. END_%s\n' % (tag, contents, tag)
18  pattern = r'\n\.\. START_%s\n.*\n\.\. END_%s\n' % (tag, tag)
19  return re.sub(pattern, '%s', text, flags=re.S) % replacement
20
21def doxygen2rst(text):
22  text = re.sub(r'<tt>\s*(.*?)\s*<\/tt>', r'``\1``', text)
23  text = re.sub(r'\\c ([^ ,;\.]+)', r'``\1``', text)
24  text = re.sub(r'\\\w+ ', '', text)
25  return text
26
27def indent(text, columns, indent_first_line=True):
28  indent = ' ' * columns
29  s = re.sub(r'\n([^\n])', '\n' + indent + '\\1', text, flags=re.S)
30  if not indent_first_line or s.startswith('\n'):
31    return s
32  return indent + s
33
34class Option(object):
35  def __init__(self, name, type, comment):
36    self.name = name
37    self.type = type
38    self.comment = comment.strip()
39    self.enum = None
40    self.nested_struct = None
41
42  def __str__(self):
43    s = '**%s** (``%s``)\n%s' % (self.name, self.type,
44                                 doxygen2rst(indent(self.comment, 2)))
45    if self.enum:
46      s += indent('\n\nPossible values:\n\n%s\n' % self.enum, 2)
47    if self.nested_struct:
48      s += indent('\n\nNested configuration flags:\n\n%s\n' %self.nested_struct,
49                  2)
50    return s
51
52class NestedStruct(object):
53  def __init__(self, name, comment):
54    self.name = name
55    self.comment = comment.strip()
56    self.values = []
57
58  def __str__(self):
59    return '\n'.join(map(str, self.values))
60
61class NestedField(object):
62  def __init__(self, name, comment):
63    self.name = name
64    self.comment = comment.strip()
65
66  def __str__(self):
67    return '\n* ``%s`` %s' % (
68        self.name,
69        doxygen2rst(indent(self.comment, 2, indent_first_line=False)))
70
71class Enum(object):
72  def __init__(self, name, comment):
73    self.name = name
74    self.comment = comment.strip()
75    self.values = []
76
77  def __str__(self):
78    return '\n'.join(map(str, self.values))
79
80class EnumValue(object):
81  def __init__(self, name, comment, config):
82    self.name = name
83    self.comment = comment
84    self.config = config
85
86  def __str__(self):
87    return '* ``%s`` (in configuration: ``%s``)\n%s' % (
88        self.name,
89        re.sub('.*_', '', self.config),
90        doxygen2rst(indent(self.comment, 2)))
91
92def clean_comment_line(line):
93  match = re.match(r'^/// \\code(\{.(\w+)\})?$', line)
94  if match:
95    lang = match.groups()[1]
96    if not lang:
97      lang = 'c++'
98    return '\n.. code-block:: %s\n\n' % lang
99  if line == '/// \\endcode':
100    return ''
101  return line[4:] + '\n'
102
103def read_options(header):
104  class State(object):
105    BeforeStruct, Finished, InStruct, InNestedStruct, InNestedFieldComent, \
106    InFieldComment, InEnum, InEnumMemberComment = range(8)
107  state = State.BeforeStruct
108
109  options = []
110  enums = {}
111  nested_structs = {}
112  comment = ''
113  enum = None
114  nested_struct = None
115
116  for line in header:
117    line = line.strip()
118    if state == State.BeforeStruct:
119      if line == 'struct FormatStyle {' or line == 'struct IncludeStyle {':
120        state = State.InStruct
121    elif state == State.InStruct:
122      if line.startswith('///'):
123        state = State.InFieldComment
124        comment = clean_comment_line(line)
125      elif line == '};':
126        state = State.Finished
127        break
128    elif state == State.InFieldComment:
129      if line.startswith('///'):
130        comment += clean_comment_line(line)
131      elif line.startswith('enum'):
132        state = State.InEnum
133        name = re.sub(r'enum\s+(\w+)\s*\{', '\\1', line)
134        enum = Enum(name, comment)
135      elif line.startswith('struct'):
136        state = State.InNestedStruct
137        name = re.sub(r'struct\s+(\w+)\s*\{', '\\1', line)
138        nested_struct = NestedStruct(name, comment)
139      elif line.endswith(';'):
140        state = State.InStruct
141        field_type, field_name = re.match(r'([<>:\w(,\s)]+)\s+(\w+);',
142                                          line).groups()
143        option = Option(str(field_name), str(field_type), comment)
144        options.append(option)
145      else:
146        raise Exception('Invalid format, expected comment, field or enum')
147    elif state == State.InNestedStruct:
148      if line.startswith('///'):
149        state = State.InNestedFieldComent
150        comment = clean_comment_line(line)
151      elif line == '};':
152        state = State.InStruct
153        nested_structs[nested_struct.name] = nested_struct
154    elif state == State.InNestedFieldComent:
155      if line.startswith('///'):
156        comment += clean_comment_line(line)
157      else:
158        state = State.InNestedStruct
159        nested_struct.values.append(NestedField(line.replace(';', ''), comment))
160    elif state == State.InEnum:
161      if line.startswith('///'):
162        state = State.InEnumMemberComment
163        comment = clean_comment_line(line)
164      elif line == '};':
165        state = State.InStruct
166        enums[enum.name] = enum
167      else:
168        raise Exception('Invalid format, expected enum field comment or };')
169    elif state == State.InEnumMemberComment:
170      if line.startswith('///'):
171        comment += clean_comment_line(line)
172      else:
173        state = State.InEnum
174        val = line.replace(',', '')
175        pos = val.find(" // ")
176        if (pos != -1):
177            config = val[pos+4:]
178            val = val[:pos]
179        else:
180            config = val;
181        enum.values.append(EnumValue(val, comment,config))
182  if state != State.Finished:
183    raise Exception('Not finished by the end of file')
184
185  for option in options:
186    if not option.type in ['bool', 'unsigned', 'int', 'std::string',
187                           'std::vector<std::string>',
188                           'std::vector<IncludeCategory>',
189                           'std::vector<RawStringFormat>']:
190      if option.type in enums:
191        option.enum = enums[option.type]
192      elif option.type in nested_structs:
193        option.nested_struct = nested_structs[option.type]
194      else:
195        raise Exception('Unknown type: %s' % option.type)
196  return options
197
198options = read_options(open(FORMAT_STYLE_FILE))
199options += read_options(open(INCLUDE_STYLE_FILE))
200
201options = sorted(options, key=lambda x: x.name)
202options_text = '\n\n'.join(map(str, options))
203
204contents = open(DOC_FILE).read()
205
206contents = substitute(contents, 'FORMAT_STYLE_OPTIONS', options_text)
207
208with open(DOC_FILE, 'wb') as output:
209  output.write(contents)
210