DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (409f3966645a)

VCS Links

Line Code
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
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import re
import sys


def read_reserved_word_list(filename):
    macro_pat = re.compile(r"^\s*macro\(([^,]+), *[^,]+, *[^\)]+\)\s*\\?$")

    reserved_word_list = []
    index = 0
    with open(filename, 'r') as f:
        for line in f:
            m = macro_pat.search(line)
            if m:
                reserved_word_list.append((index, m.group(1)))
                index += 1

    assert(len(reserved_word_list) != 0)

    return reserved_word_list


def line(opt, s):
    opt['output'].write('{}{}\n'.format('    ' * opt['indent_level'], s))


def indent(opt):
    opt['indent_level'] += 1


def dedent(opt):
    opt['indent_level'] -= 1


def span_and_count_at(reserved_word_list, column):
    assert(len(reserved_word_list) != 0)

    chars_dict = {}
    for index, word in reserved_word_list:
        chars_dict[ord(word[column])] = True

    chars = sorted(chars_dict.keys())
    return chars[-1] - chars[0] + 1, len(chars)


def optimal_switch_column(opt, reserved_word_list, columns, unprocessed_columns):
    assert(len(reserved_word_list) != 0)
    assert(unprocessed_columns != 0)

    min_count = 0
    min_span = 0
    min_count_index = 0
    min_span_index = 0

    for index in range(0, unprocessed_columns):
        span, count = span_and_count_at(reserved_word_list, columns[index])
        assert(span != 0)

        if span == 1:
            assert(count == 1)
            return 1, True

        assert(count != 1)
        if index == 0 or min_span > span:
            min_span = span
            min_span_index = index

        if index == 0 or min_count > count:
            min_count = count
            min_count_index = index

    if min_count <= opt['use_if_threshold']:
        return min_count_index, True

    return min_span_index, False


def split_list_per_column(reserved_word_list, column):
    assert(len(reserved_word_list) != 0)

    column_dict = {}
    for item in reserved_word_list:
        index, word = item
        per_column = column_dict.setdefault(word[column], [])
        per_column.append(item)

    return sorted(column_dict.items(), key=lambda (char, word): ord(char))


def generate_letter_switch(opt, unprocessed_columns, reserved_word_list,
                           columns=None):
    assert(len(reserved_word_list) != 0)

    if not columns:
        columns = range(0, unprocessed_columns)

    if len(reserved_word_list) == 1:
        index, word = reserved_word_list[0]

        if unprocessed_columns == 0:
            line(opt, 'JSRW_GOT_MATCH({}) /* {} */'.format(index, word))
            return

        if unprocessed_columns > opt['char_tail_test_threshold']:
            line(opt, 'JSRW_TEST_GUESS({}) /* {} */'.format(index, word))
            return

        conds = []
        for column in columns[0:unprocessed_columns]:
            quoted = repr(word[column])
            conds.append('JSRW_AT({})=={}'.format(column, quoted))

        line(opt, 'if ({}) {{'.format(' && '.join(conds)))

        indent(opt)
        line(opt, 'JSRW_GOT_MATCH({}) /* {} */'.format(index, word))
        dedent(opt)

        line(opt, '}')
        line(opt, 'JSRW_NO_MATCH()')
        return

    assert(unprocessed_columns != 0)

    optimal_column_index, use_if = optimal_switch_column(opt, reserved_word_list,
                                                         columns,
                                                         unprocessed_columns)
    optimal_column = columns[optimal_column_index]

    # Make a copy to avoid breaking passed list.
    columns = columns[:]
    columns[optimal_column_index] = columns[unprocessed_columns - 1]

    list_per_column = split_list_per_column(reserved_word_list, optimal_column)

    if not use_if:
        line(opt, 'switch (JSRW_AT({})) {{'.format(optimal_column))

    for char, reserved_word_list_per_column in list_per_column:
        quoted = repr(char)
        if use_if:
            line(opt, 'if (JSRW_AT({}) == {}) {{'.format(optimal_column,
                                                         quoted))
        else:
            line(opt, '  case {}:'.format(quoted))

        indent(opt)
        generate_letter_switch(opt, unprocessed_columns - 1,
                               reserved_word_list_per_column, columns)
        dedent(opt)

        if use_if:
            line(opt, '}')

    if not use_if:
        line(opt, '}')

    line(opt, 'JSRW_NO_MATCH()')


def split_list_per_length(reserved_word_list):
    assert(len(reserved_word_list) != 0)

    length_dict = {}
    for item in reserved_word_list:
        index, word = item
        per_length = length_dict.setdefault(len(word), [])
        per_length.append(item)

    return sorted(length_dict.items(), key=lambda (length, word): length)


def generate_switch(opt, reserved_word_list):
    assert(len(reserved_word_list) != 0)

    line(opt, '/*')
    line(opt, ' * Generating switch for the list of {} entries:'.format(len(reserved_word_list)))
    for index, word in reserved_word_list:
        line(opt, ' * {}'.format(word))
    line(opt, ' */')

    list_per_length = split_list_per_length(reserved_word_list)

    use_if = False
    if len(list_per_length) < opt['use_if_threshold']:
        use_if = True

    if not use_if:
        line(opt, 'switch (JSRW_LENGTH()) {')

    for length, reserved_word_list_per_length in list_per_length:
        if use_if:
            line(opt, 'if (JSRW_LENGTH() == {}) {{'.format(length))
        else:
            line(opt, '  case {}:'.format(length))

        indent(opt)
        generate_letter_switch(opt, length, reserved_word_list_per_length)
        dedent(opt)

        if use_if:
            line(opt, '}')

    if not use_if:
        line(opt, '}')
    line(opt, 'JSRW_NO_MATCH()')


def main(output, reserved_words_h):
    reserved_word_list = read_reserved_word_list(reserved_words_h)

    opt = {
        'indent_level': 1,
        'use_if_threshold': 3,
        'char_tail_test_threshold': 4,
        'output': output
    }
    generate_switch(opt, reserved_word_list)


if __name__ == '__main__':
    main(sys.stdout, *sys.argv[1:])