summaryrefslogtreecommitdiffstats
path: root/formal/promela/src/src/modules/comment_filter/comment_filter/rfc.py
blob: 86b7deaa21d261b534c12218a854b72633b9935e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
import re

class State:
    """Parser State"""
    def __init__(self, line='', multi_end_stack=None, in_literal=None):
        # The remaining input.
        self.line = line

        # A stack of end tokens for multi-line comments.  The token on the
        # top of the stack is the expected end token for the most nested
        # multi-line comment.
        self.multi_end_stack = multi_end_stack or []

        # If the parser is waiting on the end quote, in_literal will be
        # string the parser is waiting for.
        self.in_literal = in_literal

    def __eq__(self, x):
        # Return True if all members are equal.
        return self.line == x.line and self.multi_end_stack == x.multi_end_stack \
            and self.in_literal == x.in_literal


def parse_file(lang, file_obj, code_only=False, keep_tokens=True):
    """
    Return a generator that yields a filtered line for
    each line in file_obj.

    Args:
      lang (dictionary):
        Syntax description for the language being parsed.
      file_obj (iterator<string>):
        An iterater that yields lines.
      code_only (bool, default: False):
        If False, each non-comment character is replaced with a space.
        If True, each comment character is replaced with a space.
      keep_tokens (bool, default: True):
        If False, comment tokens are filtered out.
        If True, comment tokens are preserved.

    Returns:
      iterator<string>
    """
    state = State()
    for line in file_obj:
        state.line = line
        line, state = parse_line(lang, state, code_only, keep_tokens)
        yield line


def parse_line(lang, state, code_only=False, keep_tokens=True):
    """
    Return the comments or code of state.line.

    The output string will be the same length as the input string.
    Filtered out characters are represented as spaces.

    Args:
      lang (Language):
        Syntax description for the language being parsed.
      state (State):
        Parser state.
      code_only (bool, default: False):
        If False, each non-comment character is replaced with a space.
        If True, each comment character is replaced with a space.
      keep_tokens (bool, default: True):
        If False, comment tokens are filtered out.
        If True, comment tokens are preserved.

    Returns:
      (string, State)
    """
    # If currently within a string literal or multi-line comment, first
    # complete parsing that declaration.  Store the result in 'rest_of_decl'.
    rest_of_decl = ''
    if state.in_literal:
        # Parsing a string literal.
        cnts, state = finish_string_literal(state.in_literal, state)
        if code_only:
            rest_of_decl = cnts
        else:
            rest_of_decl = clear_line(cnts)
    elif state.multi_end_stack:
        # If there is state, we assume it is because we have parsed
        # the start of a multiline comment, but haven't found the end.
        cmt, state = finish_multiline_comment(lang, state, keep_tokens)
        if code_only:
            rest_of_decl = clear_line(cmt)
        else:
            rest_of_decl = cmt

    if state.in_literal or state.multi_end_stack:
        return rest_of_decl, state

    decls, state = parse_declarations(lang, state, code_only, keep_tokens)
    return rest_of_decl + decls, state


def parse_declarations(lang, state, code_only=False, keep_tokens=True):
    """
    Return the comments or code of state.line.

    Unlike parse_line, this function assumes the parser is *not*
    in the context of a multi-line comment.

    Args:
      lang (Language):
        Syntax description for the language being parsed.
      state (State):
        Parser state.
      code_only (bool, default: False):
        If False, each non-comment character is replaced with a space.
        If True, each comment character is replaced with a space.
      keep_tokens (bool, default: True):
        If False, comment tokens are filtered out.
        If True, comment tokens are preserved.

    Returns:
      (string, State)
    """
    code, state = parse_code(lang, state)
    comment, state = parse_line_comment(lang, state, keep_tokens)
    comment2, state = parse_multiline_comment(lang, state, keep_tokens)

    if comment or comment2:
        line = state.line
        if not state.multi_end_stack:
            # Continue looking for declarations.
            line, state = parse_declarations(lang, state, code_only, keep_tokens)
        if code_only:
            line = code + clear_line(comment) + clear_line(comment2) + line
        else:
            line = clear_line(code) + comment + comment2 + line
        return line, state
    else:
        state.line = ''
        if code_only:
            return code, state
        else:
            return clear_line(code), state


def parse_code(lang, state):
    """
    Returns all characters up to the first comment.

    Args:
      lang (Language):
        Syntax description for the language being parsed.
      state (State):
        Parser state.

    Returns:
      (string, State)
    """
    code = ''
    while True:
        line = state.line
        multi_start_tokens = [start for start, end in lang.comment_bookends]
        tokens = multi_start_tokens + [
            lang.line_comment,
            lang.string_literal_start,
            lang.string_literal2_start]
        i = index_of_first_found(line, tokens)
        if i != -1:
            state.line = line[i:]
            code += line[:i]
            if line.startswith(lang.line_comment, i) or \
                    index_of_first_found(line, multi_start_tokens) == i:
                return code, state
            elif line.startswith(lang.string_literal_start, i):
                lit, state = parse_string_literal(
                    lang.string_literal_start, state)
                code += lit
                continue
            else:
                lit, state = parse_string_literal(
                    lang.string_literal2_start, state)
                code += lit
                continue
        else:
            state.line = ''
            return code + line, state


def parse_string_literal(quote, state):
    """
    Returns the string literal at the beginning of state.line,
    otherwise the empty string.

    Args:
      quote (string):
        The syntax for the start and end quote.
      state (State):
        Parser state.

    Returns:
      (string, State)
    """
    if state.line.startswith(quote):
        state.line = state.line[len(quote):]
        line, state = finish_string_literal(quote, state)
        return quote + line, state
    else:
        return '', state


def finish_string_literal(quote, state):
    cnts, state = parse_string_literal_contents(quote, state)
    if state.line.startswith(quote):
        state.line = state.line[len(quote):]
        state.in_literal = None
        return cnts + quote, state
    else:
        # No end-quote yet.
        state.in_literal = quote
        return cnts, state


def parse_string_literal_contents(quote, state):
    """
    Returns the string literal contents at the beginning of state.line.
    The end quote is not included.

    Args:
      quote (string):
        The syntax for the end quote.
      state (State):
        Parser state.

    Returns:
      (string, State)
    """
    contents = ''
    escaped_quote = '\\' + quote
    while True:
        i = index_of_first_found(state.line, [quote, escaped_quote])
        if i != -1:
            if state.line.startswith(quote, i):
                contents += state.line[:i]
                state.line = state.line[i:]
                return contents, state
            else:
                # Escaped quote.
                i += len(escaped_quote)
                contents += state.line[:i]
                state.line = state.line[i:]
                continue
        else:
            # No end-quote.  Chew up the whole line.
            contents += state.line
            state.line = ''
            return contents, state


def parse_line_comment(lang, state, keep_tokens=True):
    """
    Returns the single-line comment at the beginning of state.line,
    otherwise the empty string.

    Args:
      lang (Language):
        Syntax description for the language being parsed.
      state (State):
        Parser state
      keep_tokens (bool, default: True):
        If False, comment tokens are filtered out.
        If True, comment tokens are preserved.

    Returns:
      (string, State)
    """
    line = state.line
    line_comment = lang.line_comment
    if line.startswith(line_comment):
        state.line = ''
        i = len(line_comment)
        if not keep_tokens:
            line_comment = ' ' * i
        return line_comment + line[i:], state
    else:
        return '', state


def parse_multiline_comment(lang, state, keep_tokens=True):
    """
    Returns the multi-line comment at the beginning of state.line,
    otherwise the empty string.

    Args:
      lang (Language):
        Syntax description for the language being parsed.
      state (State):
        Parser state
      keep_tokens (bool, default: True):
        If False, comment tokens are filtered out.
        If True, comment tokens are preserved.

    Returns:
      (string, State)
    """
    line = state.line
    for multi_start, multi_end in lang.comment_bookends:
        if line.startswith(multi_start):
            state.multi_end_stack.append(multi_end)
            state.line = line[len(multi_start):]
            cnts, state = finish_multiline_comment(lang, state, keep_tokens)
            if not keep_tokens:
                multi_start = ' ' * len(multi_start)
            return multi_start + cnts, state
    return '', state


def finish_multiline_comment(lang, state, keep_tokens=True):
    """
    Returns the rest of a multi-line comment at the beginning of state.line.

    Args:
      lang (Language):
        Syntax description for the language being parsed.
      state (State):
        Parser state
      keep_tokens (bool, default: True):
        If False, comment tokens are filtered out.
        If True, comment tokens are preserved.

    Returns:
      (string, State)
    """
    cnts, state = parse_multiline_contents(lang, state)
    multi_end = state.multi_end_stack[-1]

    # Handle language supports nested comments.
    if lang.nested_comments:
        cmt, state = parse_multiline_comment(lang, state, keep_tokens)
    else:
        cmt = ''

    line = state.line
    if line:
        if line.startswith(multi_end):
            i = len(multi_end)
            state.multi_end_stack.pop()
            state.line = line[i:]
            if not keep_tokens:
                multi_end = ' ' * len(multi_end)
            return cnts + cmt + multi_end, state
        else:
            more_cnts, state = finish_multiline_comment(lang, state, keep_tokens)
            return cnts + cmt + more_cnts, state
    else:
        return cnts + cmt, state


def parse_multiline_contents(lang, state):
    """
    Returns the multi-line comment contents at the beginning of state.line.

    Args:
      lang (Language):
        Syntax description for the language being parsed.
      state (State):
        Parser state

    Returns:
      (string, State)
    """
    line = state.line
    tokens = [start for start, end in lang.comment_bookends]
    multi_end = state.multi_end_stack[-1]
    tokens.append(multi_end)

    if lang.nested_comments:
        i = index_of_first_found(line, tokens)
    else:
        try:
            i = line.index(multi_end)
        except ValueError:
            i = -1

    if i != -1:
        state.line = line[i:]
        return line[:i], state
    else:
        # Reached the end of line before the end of comment.
        state.line = ''
        return line, state


def index_of_first_found(s, xs):
    """
    Return the index of the first string from xs found in s.
    """
    regex = '|'.join(map(re.escape, xs))
    m = re.search(regex, s)
    if m:
        return m.start()
    else:
        return -1


def clear_line(line):
    """
    Return a string where each non-newline character is replaced with a space.
    """
    sep = get_linesep(line)
    if sep:
        return ' ' * (len(line) - len(sep)) + sep
    else:
        return ' ' * len(line)


def get_linesep(line):
    """
    Returns the line separator if it exists, otherwise the empty string."
    """
    n = len(line)
    if n >= 2 and line[-2:] == '\r\n':
        return '\r\n'
    elif n >= 1 and line[-1] == '\n':
        return '\n'
    else:
        return ''