#!/usr/bin/env python
# Copyright (c) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""This python script creates the raw data that is our entity
database. The representation is one string database containing all
strings we could need, and then a mapping from offset+length -> entity
data. That is compact, easy to use and efficient."""
import csv
import os.path
import sys
ENTITY = 0
VALUE = 1
def convert_value_to_int(value):
if not value:
return "0"
assert value[0] == "U"
assert value[1] == "+"
return "0x" + value[2:]
def offset_table_entry(offset):
return " &staticEntityTable[%s]," % offset
def check_ascii(entity_string):
for ch in entity_string:
code = ord(ch)
assert 0 <= code <= 127, (
ch + " is not ASCII. Need to change type " +
"of storage from LChar to UChar to support " + "this entity.")
def main():
program_name = os.path.basename(__file__)
if len(sys.argv) < 4 or sys.argv[1] != "-o":
# Python 3, change to:
# print(
# "Usage: %s -o OUTPUT_FILE INPUT_FILE" % program_name,
# file=sys.stderr)
sys.stderr.write(
"Usage: %s -o OUTPUT_FILE INPUT_FILE\n" % program_name)
exit(1)
output_path = sys.argv[2]
input_path = sys.argv[3]
with open(input_path) as html_entity_names_file:
entries = list(csv.reader(html_entity_names_file))
entries.sort(key=lambda entry: entry[ENTITY])
entity_count = len(entries)
output_file = open(output_path, "w")
output_file.write("""/*
* Copyright (C) 2010 Google, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// THIS FILE IS GENERATED BY build/scripts/make_html_entity_table.py.
// DO NOT EDIT (unless you are a ninja)!
#include "third_party/blink/renderer/core/html/parser/html_entity_table.h"
namespace blink {
namespace {
""")
assert len(entries) > 0, "Code assumes a non-empty entity array."
output_file.write("static const LChar staticEntityStringStorage[] = {\n")
output_file.write("'")
all_data = ""
entity_offset = 0
first_output = True
for entry in entries:
check_ascii(entry[ENTITY])
# Reuse substrings from earlier entries. This saves 1-2000
# characters, but it's O(n^2) and not very smart. The optimal
# solution has to solve the "Shortest Common Superstring" problem
# and that is NP-Complete or worse.
#
# This would be even more efficient if we didn't store the
# semi-colon in the array but as a bit in the entry.
entity = entry[ENTITY]
already_existing_offset = all_data.find(entity)
if already_existing_offset != -1:
# Reusing space.
this_offset = already_existing_offset
else:
if not first_output:
output_file.write(",\n'")
first_output = False
# Try the end of the string and see if we can reuse that to
# fit the start of the new entity.
data_to_add = entity
this_offset = entity_offset
for truncated_len in range(len(entity) - 1, 0, -1):
if all_data.endswith(entity[:truncated_len]):
data_to_add = entity[truncated_len:]
this_offset = entity_offset - truncated_len
break
output_file.write("', '".join(data_to_add))
all_data += data_to_add
output_file.write("'")
entity_offset += len(data_to_add)
assert len(
entry) == 2, "We will use slot [2] in the list for the offset."
assert this_offset < 32768 # Stored in a 16 bit short.
entry.append(this_offset)
output_file.write("};\n")
index = {}
for offset, entry in enumerate(entries):
starting_letter = entry[ENTITY][0]
if starting_letter not in index:
index[starting_letter] = offset
output_file.write("""
static const HTMLEntityTableEntry staticEntityTable[%s] = {\n""" %
entity_count)
for entry in entries:
values = entry[VALUE].split(' ')
assert len(values) <= 2, values
output_file.write(' { %s, %s, %s, %s }, // &%s\n' % (
convert_value_to_int(values[0]),
convert_value_to_int(values[1] if len(values) >= 2 else ""),
entry[2],
len(entry[ENTITY]),
entry[ENTITY],
))
output_file.write("};\n\n")
output_file.write("\n}\n")
output_file.write("static const int16_t uppercaseOffset[] = {\n")
for letter in range(ord('A'), ord('Z') + 1):
output_file.write("%d,\n" % index[chr(letter)])
output_file.write("%d\n" % index['a'])
output_file.write("};\n\nstatic const int16_t lowercaseOffset[] = {\n")
for letter in range(ord('a'), ord('z') + 1):
output_file.write("%d,\n" % index[chr(letter)])
output_file.write("%d\n" % entity_count)
output_file.write("""};
const LChar* HTMLEntityTable::EntityString(const HTMLEntityTableEntry& entry)
{
return staticEntityStringStorage + entry.entity_offset;
}
LChar HTMLEntityTableEntry::LastCharacter() const
{
return HTMLEntityTable::EntityString(*this)[length - 1];
}
const HTMLEntityTableEntry* HTMLEntityTable::FirstEntryStartingWith(UChar c)
{
if (c >= 'A' && c <= 'Z')
return &staticEntityTable[uppercaseOffset[c - 'A']];
if (c >= 'a' && c <= 'z')
return &staticEntityTable[lowercaseOffset[c - 'a']];
return 0;
}
const HTMLEntityTableEntry* HTMLEntityTable::LastEntryStartingWith(UChar c)
{
if (c >= 'A' && c <= 'Z')
return &staticEntityTable[uppercaseOffset[c - 'A' + 1]] - 1;
if (c >= 'a' && c <= 'z')
return &staticEntityTable[lowercaseOffset[c - 'a' + 1]] - 1;
return 0;
}
const HTMLEntityTableEntry* HTMLEntityTable::FirstEntry()
{
return &staticEntityTable[0];
}
const HTMLEntityTableEntry* HTMLEntityTable::LastEntry()
{
return &staticEntityTable[%s - 1];
}
}
""" % entity_count)
if __name__ == "__main__":
main()