summaryrefslogtreecommitdiff
path: root/python/util.py
blob: 3101edfb47257465a6a362e0a12b5fe71cad128c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/usr/bin/python

import io
from tokenize import tokenize

# Check if code contains a sequence of tokens (given as a list of strings).
def has_token_sequence(code, sequence):
    stream = io.BytesIO(code.encode('utf-8'))
    tokens = [t.string for t in tokenize(stream.readline) if t.string]
    for i in range(len(tokens)-len(sequence)+1):
        if tokens[i:i+len(sequence)] == sequence:
            return True
    return False

if __name__ == '__main__':
    print(has_token_sequence('x + y >= 0', ['>=', '0']))
    print(has_token_sequence('x + y > 0', ['>=', '0']))