зеркало из https://github.com/mozilla/gecko-dev.git
Bug 1380154 - Part 1: Add the Chromium DAFSA generator. r=njn
This imports Chromium's `make_dafsa.py` script [1]. It takes in a gperf formatted file (note: gperf is *not* required) and converts that to a compact binary representation of the string data in the form of a deterministic acyclic finite state automaton (DAFSA) [2]. The only change made to the script was to make it handle the arguments our file generation script passes in to the `main` function. It also imports the logic for traversing the DAFSA [3] almost verbatim in `Dafsa.cpp`. A thin wrapper was added so that we can reuse the DAFSA structure for multiple tables. The only change made to the original logic was to swap in mozilla style assertions and rename the not found constant from `kNotFound` to `Dafsa::kKeyNotFound` in order to avoid a collision with `kNotFound` defined in our nsString code. [1]6ba04a9056/tools/dafsa/make_dafsa.py
[2] https://en.wikipedia.org/wiki/Deterministic_acyclic_finite_state_automaton [3]a2a90a35aa/net/base/registry_controlled_domains/registry_controlled_domain.cc (72)
MozReview-Commit-ID: Eion9POHZm5
This commit is contained in:
Родитель
1b252764d3
Коммит
09ade48fd7
|
@ -0,0 +1,159 @@
|
||||||
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
|
||||||
|
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
|
||||||
|
/* 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/. */
|
||||||
|
|
||||||
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style license that can be
|
||||||
|
// found in the LICENSE file.
|
||||||
|
|
||||||
|
#include "Dafsa.h"
|
||||||
|
|
||||||
|
#include "mozilla/Assertions.h"
|
||||||
|
#include "nsAString.h"
|
||||||
|
|
||||||
|
const int mozilla::Dafsa::kKeyNotFound = -1;
|
||||||
|
|
||||||
|
// Note the DAFSA implementation was lifted from eTLD code in Chromium that was
|
||||||
|
// originally lifted from Firefox.
|
||||||
|
|
||||||
|
// Read next offset from pos.
|
||||||
|
// Returns true if an offset could be read, false otherwise.
|
||||||
|
bool GetNextOffset(const unsigned char** pos, const unsigned char* end,
|
||||||
|
const unsigned char** offset) {
|
||||||
|
if (*pos == end)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
// When reading an offset the byte array must always contain at least
|
||||||
|
// three more bytes to consume. First the offset to read, then a node
|
||||||
|
// to skip over and finally a destination node. No object can be smaller
|
||||||
|
// than one byte.
|
||||||
|
MOZ_ASSERT(*pos + 2 < end);
|
||||||
|
size_t bytes_consumed;
|
||||||
|
switch (**pos & 0x60) {
|
||||||
|
case 0x60: // Read three byte offset
|
||||||
|
*offset += (((*pos)[0] & 0x1F) << 16) | ((*pos)[1] << 8) | (*pos)[2];
|
||||||
|
bytes_consumed = 3;
|
||||||
|
break;
|
||||||
|
case 0x40: // Read two byte offset
|
||||||
|
*offset += (((*pos)[0] & 0x1F) << 8) | (*pos)[1];
|
||||||
|
bytes_consumed = 2;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
*offset += (*pos)[0] & 0x3F;
|
||||||
|
bytes_consumed = 1;
|
||||||
|
}
|
||||||
|
if ((**pos & 0x80) != 0) {
|
||||||
|
*pos = end;
|
||||||
|
} else {
|
||||||
|
*pos += bytes_consumed;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if byte at offset is last in label.
|
||||||
|
bool IsEOL(const unsigned char* offset, const unsigned char* end) {
|
||||||
|
MOZ_ASSERT(offset < end);
|
||||||
|
return (*offset & 0x80) != 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if byte at offset matches first character in key.
|
||||||
|
// This version matches characters not last in label.
|
||||||
|
bool IsMatch(const unsigned char* offset, const unsigned char* end,
|
||||||
|
const char* key) {
|
||||||
|
MOZ_ASSERT(offset < end);
|
||||||
|
return *offset == *key;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if byte at offset matches first character in key.
|
||||||
|
// This version matches characters last in label.
|
||||||
|
bool IsEndCharMatch(const unsigned char* offset, const unsigned char* end,
|
||||||
|
const char* key) {
|
||||||
|
MOZ_ASSERT(offset < end);
|
||||||
|
return *offset == (*key | 0x80);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read return value at offset.
|
||||||
|
// Returns true if a return value could be read, false otherwise.
|
||||||
|
bool GetReturnValue(const unsigned char* offset, const unsigned char* end,
|
||||||
|
int* return_value) {
|
||||||
|
MOZ_ASSERT(offset < end);
|
||||||
|
if ((*offset & 0xE0) == 0x80) {
|
||||||
|
*return_value = *offset & 0x0F;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lookup a domain key in a byte array generated by make_dafsa.py.
|
||||||
|
// The rule type is returned if key is found, otherwise kKeyNotFound is returned.
|
||||||
|
int LookupString(const unsigned char* graph, size_t length, const char* key,
|
||||||
|
size_t key_length) {
|
||||||
|
const unsigned char* pos = graph;
|
||||||
|
const unsigned char* end = graph + length;
|
||||||
|
const unsigned char* offset = pos;
|
||||||
|
const char* key_end = key + key_length;
|
||||||
|
while (GetNextOffset(&pos, end, &offset)) {
|
||||||
|
// char <char>+ end_char offsets
|
||||||
|
// char <char>+ return value
|
||||||
|
// char end_char offsets
|
||||||
|
// char return value
|
||||||
|
// end_char offsets
|
||||||
|
// return_value
|
||||||
|
bool did_consume = false;
|
||||||
|
if (key != key_end && !IsEOL(offset, end)) {
|
||||||
|
// Leading <char> is not a match. Don't dive into this child
|
||||||
|
if (!IsMatch(offset, end, key))
|
||||||
|
continue;
|
||||||
|
did_consume = true;
|
||||||
|
++offset;
|
||||||
|
++key;
|
||||||
|
// Possible matches at this point:
|
||||||
|
// <char>+ end_char offsets
|
||||||
|
// <char>+ return value
|
||||||
|
// end_char offsets
|
||||||
|
// return value
|
||||||
|
// Remove all remaining <char> nodes possible
|
||||||
|
while (!IsEOL(offset, end) && key != key_end) {
|
||||||
|
if (!IsMatch(offset, end, key))
|
||||||
|
return mozilla::Dafsa::kKeyNotFound;
|
||||||
|
++key;
|
||||||
|
++offset;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Possible matches at this point:
|
||||||
|
// end_char offsets
|
||||||
|
// return_value
|
||||||
|
// If one or more <char> elements were consumed, a failure
|
||||||
|
// to match is terminal. Otherwise, try the next node.
|
||||||
|
if (key == key_end) {
|
||||||
|
int return_value;
|
||||||
|
if (GetReturnValue(offset, end, &return_value))
|
||||||
|
return return_value;
|
||||||
|
// The DAFSA guarantees that if the first char is a match, all
|
||||||
|
// remaining char elements MUST match if the key is truly present.
|
||||||
|
if (did_consume)
|
||||||
|
return mozilla::Dafsa::kKeyNotFound;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!IsEndCharMatch(offset, end, key)) {
|
||||||
|
if (did_consume)
|
||||||
|
return mozilla::Dafsa::kKeyNotFound; // Unexpected
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
++key;
|
||||||
|
pos = ++offset; // Dive into child
|
||||||
|
}
|
||||||
|
return mozilla::Dafsa::kKeyNotFound; // No match
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace mozilla {
|
||||||
|
|
||||||
|
int Dafsa::Lookup(const nsACString& aKey) const
|
||||||
|
{
|
||||||
|
return LookupString(mData.Elements(), mData.Length(),
|
||||||
|
aKey.BeginReading(), aKey.Length());
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace mozilla
|
|
@ -0,0 +1,55 @@
|
||||||
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
|
||||||
|
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
|
||||||
|
/* 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/. */
|
||||||
|
|
||||||
|
#ifndef mozilla_Dafsa_h
|
||||||
|
#define mozilla_Dafsa_h
|
||||||
|
|
||||||
|
#include "stdint.h"
|
||||||
|
|
||||||
|
#include "mozilla/Span.h"
|
||||||
|
#include "nsStringFwd.h"
|
||||||
|
|
||||||
|
namespace mozilla {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A deterministic acyclic finite state automaton suitable for storing static
|
||||||
|
* dictionaries of tagged ascii strings. Consider using this if you have a very
|
||||||
|
* large set of strings that need an associated enum value.
|
||||||
|
*
|
||||||
|
* Currently the string tag is limited by `make_dafsa.py` to a value of [0-4].
|
||||||
|
* In theory [0-15] can easily be supported.
|
||||||
|
*
|
||||||
|
* See `make_dafsa.py` for more details.
|
||||||
|
*/
|
||||||
|
class Dafsa
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
using Graph = Span<const uint8_t>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initializes the DAFSA with a binary encoding generated by `make_dafsa.py`.
|
||||||
|
*/
|
||||||
|
explicit constexpr Dafsa(const Graph& aData) : mData(aData) {}
|
||||||
|
|
||||||
|
~Dafsa() = default;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Searches for the given string in the DAFSA.
|
||||||
|
*
|
||||||
|
* @param aKey The string to search for.
|
||||||
|
* @returns kKeyNotFound if not found, otherwise the associated tag.
|
||||||
|
*/
|
||||||
|
int Lookup(const nsACString& aKey) const;
|
||||||
|
|
||||||
|
static const int kKeyNotFound;
|
||||||
|
|
||||||
|
private:
|
||||||
|
const Graph mData;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace mozilla
|
||||||
|
|
||||||
|
#endif // mozilla_Dafsa_h
|
|
@ -0,0 +1,471 @@
|
||||||
|
#!/usr/bin/env python
|
||||||
|
# Copyright 2014 The Chromium Authors. All rights reserved.
|
||||||
|
# Use of this source code is governed by a BSD-style license that can be
|
||||||
|
# found in the LICENSE file.
|
||||||
|
|
||||||
|
"""
|
||||||
|
A Deterministic acyclic finite state automaton (DAFSA) is a compact
|
||||||
|
representation of an unordered word list (dictionary).
|
||||||
|
|
||||||
|
http://en.wikipedia.org/wiki/Deterministic_acyclic_finite_state_automaton
|
||||||
|
|
||||||
|
This python program converts a list of strings to a byte array in C++.
|
||||||
|
This python program fetches strings and return values from a gperf file
|
||||||
|
and generates a C++ file with a byte array representing graph that can be
|
||||||
|
used as a memory efficient replacement for the perfect hash table.
|
||||||
|
|
||||||
|
The input strings are assumed to consist of printable 7-bit ASCII characters
|
||||||
|
and the return values are assumed to be one digit integers.
|
||||||
|
|
||||||
|
In this program a DAFSA is a diamond shaped graph starting at a common
|
||||||
|
source node and ending at a common sink node. All internal nodes contain
|
||||||
|
a label and each word is represented by the labels in one path from
|
||||||
|
the source node to the sink node.
|
||||||
|
|
||||||
|
The following python represention is used for nodes:
|
||||||
|
|
||||||
|
Source node: [ children ]
|
||||||
|
Internal node: (label, [ children ])
|
||||||
|
Sink node: None
|
||||||
|
|
||||||
|
The graph is first compressed by prefixes like a trie. In the next step
|
||||||
|
suffixes are compressed so that the graph gets diamond shaped. Finally
|
||||||
|
one to one linked nodes are replaced by nodes with the labels joined.
|
||||||
|
|
||||||
|
The order of the operations is crucial since lookups will be performed
|
||||||
|
starting from the source with no backtracking. Thus a node must have at
|
||||||
|
most one child with a label starting by the same character. The output
|
||||||
|
is also arranged so that all jumps are to increasing addresses, thus forward
|
||||||
|
in memory.
|
||||||
|
|
||||||
|
The generated output has suffix free decoding so that the sign of leading
|
||||||
|
bits in a link (a reference to a child node) indicate if it has a size of one,
|
||||||
|
two or three bytes and if it is the last outgoing link from the actual node.
|
||||||
|
A node label is terminated by a byte with the leading bit set.
|
||||||
|
|
||||||
|
The generated byte array can described by the following BNF:
|
||||||
|
|
||||||
|
<byte> ::= < 8-bit value in range [0x00-0xFF] >
|
||||||
|
|
||||||
|
<char> ::= < printable 7-bit ASCII character, byte in range [0x20-0x7F] >
|
||||||
|
<end_char> ::= < char + 0x80, byte in range [0xA0-0xFF] >
|
||||||
|
<return value> ::= < value + 0x80, byte in range [0x80-0x8F] >
|
||||||
|
|
||||||
|
<offset1> ::= < byte in range [0x00-0x3F] >
|
||||||
|
<offset2> ::= < byte in range [0x40-0x5F] >
|
||||||
|
<offset3> ::= < byte in range [0x60-0x7F] >
|
||||||
|
|
||||||
|
<end_offset1> ::= < byte in range [0x80-0xBF] >
|
||||||
|
<end_offset2> ::= < byte in range [0xC0-0xDF] >
|
||||||
|
<end_offset3> ::= < byte in range [0xE0-0xFF] >
|
||||||
|
|
||||||
|
<prefix> ::= <char>
|
||||||
|
|
||||||
|
<label> ::= <end_char>
|
||||||
|
| <char> <label>
|
||||||
|
|
||||||
|
<end_label> ::= <return_value>
|
||||||
|
| <char> <end_label>
|
||||||
|
|
||||||
|
<offset> ::= <offset1>
|
||||||
|
| <offset2> <byte>
|
||||||
|
| <offset3> <byte> <byte>
|
||||||
|
|
||||||
|
<end_offset> ::= <end_offset1>
|
||||||
|
| <end_offset2> <byte>
|
||||||
|
| <end_offset3> <byte> <byte>
|
||||||
|
|
||||||
|
<offsets> ::= <end_offset>
|
||||||
|
| <offset> <offsets>
|
||||||
|
|
||||||
|
<source> ::= <offsets>
|
||||||
|
|
||||||
|
<node> ::= <label> <offsets>
|
||||||
|
| <prefix> <node>
|
||||||
|
| <end_label>
|
||||||
|
|
||||||
|
<dafsa> ::= <source>
|
||||||
|
| <dafsa> <node>
|
||||||
|
|
||||||
|
Decoding:
|
||||||
|
|
||||||
|
<char> -> printable 7-bit ASCII character
|
||||||
|
<end_char> & 0x7F -> printable 7-bit ASCII character
|
||||||
|
<return value> & 0x0F -> integer
|
||||||
|
<offset1 & 0x3F> -> integer
|
||||||
|
((<offset2> & 0x1F>) << 8) + <byte> -> integer
|
||||||
|
((<offset3> & 0x1F>) << 16) + (<byte> << 8) + <byte> -> integer
|
||||||
|
|
||||||
|
end_offset1, end_offset2 and and_offset3 are decoded same as offset1,
|
||||||
|
offset2 and offset3 respectively.
|
||||||
|
|
||||||
|
The first offset in a list of offsets is the distance in bytes between the
|
||||||
|
offset itself and the first child node. Subsequent offsets are the distance
|
||||||
|
between previous child node and next child node. Thus each offset links a node
|
||||||
|
to a child node. The distance is always counted between start addresses, i.e.
|
||||||
|
first byte in decoded offset or first byte in child node.
|
||||||
|
|
||||||
|
Example 1:
|
||||||
|
|
||||||
|
%%
|
||||||
|
aa, 1
|
||||||
|
a, 2
|
||||||
|
%%
|
||||||
|
|
||||||
|
The input is first parsed to a list of words:
|
||||||
|
["aa1", "a2"]
|
||||||
|
|
||||||
|
A fully expanded graph is created from the words:
|
||||||
|
source = [node1, node4]
|
||||||
|
node1 = ("a", [node2])
|
||||||
|
node2 = ("a", [node3])
|
||||||
|
node3 = ("\x01", [sink])
|
||||||
|
node4 = ("a", [node5])
|
||||||
|
node5 = ("\x02", [sink])
|
||||||
|
sink = None
|
||||||
|
|
||||||
|
Compression results in the following graph:
|
||||||
|
source = [node1]
|
||||||
|
node1 = ("a", [node2, node3])
|
||||||
|
node2 = ("\x02", [sink])
|
||||||
|
node3 = ("a\x01", [sink])
|
||||||
|
sink = None
|
||||||
|
|
||||||
|
A C++ representation of the compressed graph is generated:
|
||||||
|
|
||||||
|
const unsigned char dafsa[7] = {
|
||||||
|
0x81, 0xE1, 0x02, 0x81, 0x82, 0x61, 0x81,
|
||||||
|
};
|
||||||
|
|
||||||
|
The bytes in the generated array has the following meaning:
|
||||||
|
|
||||||
|
0: 0x81 <end_offset1> child at position 0 + (0x81 & 0x3F) -> jump to 1
|
||||||
|
|
||||||
|
1: 0xE1 <end_char> label character (0xE1 & 0x7F) -> match "a"
|
||||||
|
2: 0x02 <offset1> child at position 2 + (0x02 & 0x3F) -> jump to 4
|
||||||
|
|
||||||
|
3: 0x81 <end_offset1> child at position 4 + (0x81 & 0x3F) -> jump to 5
|
||||||
|
4: 0x82 <return_value> 0x82 & 0x0F -> return 2
|
||||||
|
|
||||||
|
5: 0x61 <char> label character 0x61 -> match "a"
|
||||||
|
6: 0x81 <return_value> 0x81 & 0x0F -> return 1
|
||||||
|
|
||||||
|
Example 2:
|
||||||
|
|
||||||
|
%%
|
||||||
|
aa, 1
|
||||||
|
bbb, 2
|
||||||
|
baa, 1
|
||||||
|
%%
|
||||||
|
|
||||||
|
The input is first parsed to a list of words:
|
||||||
|
["aa1", "bbb2", "baa1"]
|
||||||
|
|
||||||
|
Compression results in the following graph:
|
||||||
|
source = [node1, node2]
|
||||||
|
node1 = ("b", [node2, node3])
|
||||||
|
node2 = ("aa\x01", [sink])
|
||||||
|
node3 = ("bb\x02", [sink])
|
||||||
|
sink = None
|
||||||
|
|
||||||
|
A C++ representation of the compressed graph is generated:
|
||||||
|
|
||||||
|
const unsigned char dafsa[11] = {
|
||||||
|
0x02, 0x83, 0xE2, 0x02, 0x83, 0x61, 0x61, 0x81, 0x62, 0x62, 0x82,
|
||||||
|
};
|
||||||
|
|
||||||
|
The bytes in the generated array has the following meaning:
|
||||||
|
|
||||||
|
0: 0x02 <offset1> child at position 0 + (0x02 & 0x3F) -> jump to 2
|
||||||
|
1: 0x83 <end_offset1> child at position 2 + (0x83 & 0x3F) -> jump to 5
|
||||||
|
|
||||||
|
2: 0xE2 <end_char> label character (0xE2 & 0x7F) -> match "b"
|
||||||
|
3: 0x02 <offset1> child at position 3 + (0x02 & 0x3F) -> jump to 5
|
||||||
|
4: 0x83 <end_offset1> child at position 5 + (0x83 & 0x3F) -> jump to 8
|
||||||
|
|
||||||
|
5: 0x61 <char> label character 0x61 -> match "a"
|
||||||
|
6: 0x61 <char> label character 0x61 -> match "a"
|
||||||
|
7: 0x81 <return_value> 0x81 & 0x0F -> return 1
|
||||||
|
|
||||||
|
8: 0x62 <char> label character 0x62 -> match "b"
|
||||||
|
9: 0x62 <char> label character 0x62 -> match "b"
|
||||||
|
10: 0x82 <return_value> 0x82 & 0x0F -> return 2
|
||||||
|
"""
|
||||||
|
|
||||||
|
import sys
|
||||||
|
|
||||||
|
class InputError(Exception):
|
||||||
|
"""Exception raised for errors in the input file."""
|
||||||
|
|
||||||
|
|
||||||
|
def to_dafsa(words):
|
||||||
|
"""Generates a DAFSA from a word list and returns the source node.
|
||||||
|
|
||||||
|
Each word is split into characters so that each character is represented by
|
||||||
|
a unique node. It is assumed the word list is not empty.
|
||||||
|
"""
|
||||||
|
if not words:
|
||||||
|
raise InputError('The domain list must not be empty')
|
||||||
|
def ToNodes(word):
|
||||||
|
"""Split words into characters"""
|
||||||
|
if not 0x1F < ord(word[0]) < 0x80:
|
||||||
|
raise InputError('Domain names must be printable 7-bit ASCII')
|
||||||
|
if len(word) == 1:
|
||||||
|
return chr(ord(word[0]) & 0x0F), [None]
|
||||||
|
return word[0], [ToNodes(word[1:])]
|
||||||
|
return [ToNodes(word) for word in words]
|
||||||
|
|
||||||
|
|
||||||
|
def to_words(node):
|
||||||
|
"""Generates a word list from all paths starting from an internal node."""
|
||||||
|
if not node:
|
||||||
|
return ['']
|
||||||
|
return [(node[0] + word) for child in node[1] for word in to_words(child)]
|
||||||
|
|
||||||
|
|
||||||
|
def reverse(dafsa):
|
||||||
|
"""Generates a new DAFSA that is reversed, so that the old sink node becomes
|
||||||
|
the new source node.
|
||||||
|
"""
|
||||||
|
sink = []
|
||||||
|
nodemap = {}
|
||||||
|
|
||||||
|
def dfs(node, parent):
|
||||||
|
"""Creates reverse nodes.
|
||||||
|
|
||||||
|
A new reverse node will be created for each old node. The new node will
|
||||||
|
get a reversed label and the parents of the old node as children.
|
||||||
|
"""
|
||||||
|
if not node:
|
||||||
|
sink.append(parent)
|
||||||
|
elif id(node) not in nodemap:
|
||||||
|
nodemap[id(node)] = (node[0][::-1], [parent])
|
||||||
|
for child in node[1]:
|
||||||
|
dfs(child, nodemap[id(node)])
|
||||||
|
else:
|
||||||
|
nodemap[id(node)][1].append(parent)
|
||||||
|
|
||||||
|
for node in dafsa:
|
||||||
|
dfs(node, None)
|
||||||
|
return sink
|
||||||
|
|
||||||
|
|
||||||
|
def join_labels(dafsa):
|
||||||
|
"""Generates a new DAFSA where internal nodes are merged if there is a one to
|
||||||
|
one connection.
|
||||||
|
"""
|
||||||
|
parentcount = { id(None): 2 }
|
||||||
|
nodemap = { id(None): None }
|
||||||
|
|
||||||
|
def count_parents(node):
|
||||||
|
"""Count incoming references"""
|
||||||
|
if id(node) in parentcount:
|
||||||
|
parentcount[id(node)] += 1
|
||||||
|
else:
|
||||||
|
parentcount[id(node)] = 1
|
||||||
|
for child in node[1]:
|
||||||
|
count_parents(child)
|
||||||
|
|
||||||
|
def join(node):
|
||||||
|
"""Create new nodes"""
|
||||||
|
if id(node) not in nodemap:
|
||||||
|
children = [join(child) for child in node[1]]
|
||||||
|
if len(children) == 1 and parentcount[id(node[1][0])] == 1:
|
||||||
|
child = children[0]
|
||||||
|
nodemap[id(node)] = (node[0] + child[0], child[1])
|
||||||
|
else:
|
||||||
|
nodemap[id(node)] = (node[0], children)
|
||||||
|
return nodemap[id(node)]
|
||||||
|
|
||||||
|
for node in dafsa:
|
||||||
|
count_parents(node)
|
||||||
|
return [join(node) for node in dafsa]
|
||||||
|
|
||||||
|
|
||||||
|
def join_suffixes(dafsa):
|
||||||
|
"""Generates a new DAFSA where nodes that represent the same word lists
|
||||||
|
towards the sink are merged.
|
||||||
|
"""
|
||||||
|
nodemap = { frozenset(('',)): None }
|
||||||
|
|
||||||
|
def join(node):
|
||||||
|
"""Returns a macthing node. A new node is created if no matching node
|
||||||
|
exists. The graph is accessed in dfs order.
|
||||||
|
"""
|
||||||
|
suffixes = frozenset(to_words(node))
|
||||||
|
if suffixes not in nodemap:
|
||||||
|
nodemap[suffixes] = (node[0], [join(child) for child in node[1]])
|
||||||
|
return nodemap[suffixes]
|
||||||
|
|
||||||
|
return [join(node) for node in dafsa]
|
||||||
|
|
||||||
|
|
||||||
|
def top_sort(dafsa):
|
||||||
|
"""Generates list of nodes in topological sort order."""
|
||||||
|
incoming = {}
|
||||||
|
|
||||||
|
def count_incoming(node):
|
||||||
|
"""Counts incoming references."""
|
||||||
|
if node:
|
||||||
|
if id(node) not in incoming:
|
||||||
|
incoming[id(node)] = 1
|
||||||
|
for child in node[1]:
|
||||||
|
count_incoming(child)
|
||||||
|
else:
|
||||||
|
incoming[id(node)] += 1
|
||||||
|
|
||||||
|
for node in dafsa:
|
||||||
|
count_incoming(node)
|
||||||
|
|
||||||
|
for node in dafsa:
|
||||||
|
incoming[id(node)] -= 1
|
||||||
|
|
||||||
|
waiting = [node for node in dafsa if incoming[id(node)] == 0]
|
||||||
|
nodes = []
|
||||||
|
|
||||||
|
while waiting:
|
||||||
|
node = waiting.pop()
|
||||||
|
assert incoming[id(node)] == 0
|
||||||
|
nodes.append(node)
|
||||||
|
for child in node[1]:
|
||||||
|
if child:
|
||||||
|
incoming[id(child)] -= 1
|
||||||
|
if incoming[id(child)] == 0:
|
||||||
|
waiting.append(child)
|
||||||
|
return nodes
|
||||||
|
|
||||||
|
|
||||||
|
def encode_links(children, offsets, current):
|
||||||
|
"""Encodes a list of children as one, two or three byte offsets."""
|
||||||
|
if not children[0]:
|
||||||
|
# This is an <end_label> node and no links follow such nodes
|
||||||
|
assert len(children) == 1
|
||||||
|
return []
|
||||||
|
guess = 3 * len(children)
|
||||||
|
assert children
|
||||||
|
children = sorted(children, key = lambda x: -offsets[id(x)])
|
||||||
|
while True:
|
||||||
|
offset = current + guess
|
||||||
|
buf = []
|
||||||
|
for child in children:
|
||||||
|
last = len(buf)
|
||||||
|
distance = offset - offsets[id(child)]
|
||||||
|
assert distance > 0 and distance < (1 << 21)
|
||||||
|
|
||||||
|
if distance < (1 << 6):
|
||||||
|
# A 6-bit offset: "s0xxxxxx"
|
||||||
|
buf.append(distance)
|
||||||
|
elif distance < (1 << 13):
|
||||||
|
# A 13-bit offset: "s10xxxxxxxxxxxxx"
|
||||||
|
buf.append(0x40 | (distance >> 8))
|
||||||
|
buf.append(distance & 0xFF)
|
||||||
|
else:
|
||||||
|
# A 21-bit offset: "s11xxxxxxxxxxxxxxxxxxxxx"
|
||||||
|
buf.append(0x60 | (distance >> 16))
|
||||||
|
buf.append((distance >> 8) & 0xFF)
|
||||||
|
buf.append(distance & 0xFF)
|
||||||
|
# Distance in first link is relative to following record.
|
||||||
|
# Distance in other links are relative to previous link.
|
||||||
|
offset -= distance
|
||||||
|
if len(buf) == guess:
|
||||||
|
break
|
||||||
|
guess = len(buf)
|
||||||
|
# Set most significant bit to mark end of links in this node.
|
||||||
|
buf[last] |= (1 << 7)
|
||||||
|
buf.reverse()
|
||||||
|
return buf
|
||||||
|
|
||||||
|
|
||||||
|
def encode_prefix(label):
|
||||||
|
"""Encodes a node label as a list of bytes without a trailing high byte.
|
||||||
|
|
||||||
|
This method encodes a node if there is exactly one child and the
|
||||||
|
child follows immidiately after so that no jump is needed. This label
|
||||||
|
will then be a prefix to the label in the child node.
|
||||||
|
"""
|
||||||
|
assert label
|
||||||
|
return [ord(c) for c in reversed(label)]
|
||||||
|
|
||||||
|
|
||||||
|
def encode_label(label):
|
||||||
|
"""Encodes a node label as a list of bytes with a trailing high byte >0x80.
|
||||||
|
"""
|
||||||
|
buf = encode_prefix(label)
|
||||||
|
# Set most significant bit to mark end of label in this node.
|
||||||
|
buf[0] |= (1 << 7)
|
||||||
|
return buf
|
||||||
|
|
||||||
|
|
||||||
|
def encode(dafsa):
|
||||||
|
"""Encodes a DAFSA to a list of bytes"""
|
||||||
|
output = []
|
||||||
|
offsets = {}
|
||||||
|
|
||||||
|
for node in reversed(top_sort(dafsa)):
|
||||||
|
if (len(node[1]) == 1 and node[1][0] and
|
||||||
|
(offsets[id(node[1][0])] == len(output))):
|
||||||
|
output.extend(encode_prefix(node[0]))
|
||||||
|
else:
|
||||||
|
output.extend(encode_links(node[1], offsets, len(output)))
|
||||||
|
output.extend(encode_label(node[0]))
|
||||||
|
offsets[id(node)] = len(output)
|
||||||
|
|
||||||
|
output.extend(encode_links(dafsa, offsets, len(output)))
|
||||||
|
output.reverse()
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
def to_cxx(data):
|
||||||
|
"""Generates C++ code from a list of encoded bytes."""
|
||||||
|
text = '/* This file is generated. DO NOT EDIT!\n\n'
|
||||||
|
text += 'The byte array encodes effective tld names. See make_dafsa.py for'
|
||||||
|
text += ' documentation.'
|
||||||
|
text += '*/\n\n'
|
||||||
|
text += 'const unsigned char kDafsa[%s] = {\n' % len(data)
|
||||||
|
for i in range(0, len(data), 12):
|
||||||
|
text += ' '
|
||||||
|
text += ', '.join('0x%02x' % byte for byte in data[i:i + 12])
|
||||||
|
text += ',\n'
|
||||||
|
text += '};\n'
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def words_to_cxx(words):
|
||||||
|
"""Generates C++ code from a word list"""
|
||||||
|
dafsa = to_dafsa(words)
|
||||||
|
for fun in (reverse, join_suffixes, reverse, join_suffixes, join_labels):
|
||||||
|
dafsa = fun(dafsa)
|
||||||
|
return to_cxx(encode(dafsa))
|
||||||
|
|
||||||
|
|
||||||
|
def parse_gperf(infile):
|
||||||
|
"""Parses gperf file and extract strings and return code"""
|
||||||
|
lines = [line.strip() for line in infile]
|
||||||
|
# Extract strings after the first '%%' and before the second '%%'.
|
||||||
|
begin = lines.index('%%') + 1
|
||||||
|
end = lines.index('%%', begin)
|
||||||
|
lines = lines[begin:end]
|
||||||
|
for line in lines:
|
||||||
|
if line[-3:-1] != ', ':
|
||||||
|
raise InputError('Expected "domainname, <digit>", found "%s"' % line)
|
||||||
|
# Technically the DAFSA format could support return values in range [0-31],
|
||||||
|
# but the values below are the only with a defined meaning.
|
||||||
|
if line[-1] not in '0124':
|
||||||
|
raise InputError('Expected value to be one of {0,1,2,4}, found "%s"' %
|
||||||
|
line[-1])
|
||||||
|
return [line[:-3] + line[-1] for line in lines]
|
||||||
|
|
||||||
|
|
||||||
|
def main(outfile, infile):
|
||||||
|
with open(infile, 'r') as infile:
|
||||||
|
outfile.write(words_to_cxx(parse_gperf(infile)))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
if len(sys.argv) != 3:
|
||||||
|
print('usage: %s infile outfile' % sys.argv[0])
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
with open(sys.argv[2], 'w') as outfile:
|
||||||
|
sys.exit(main(outfile, sys.argv[1]))
|
|
@ -82,6 +82,7 @@ EXPORTS.mozilla += [
|
||||||
'ArenaAllocator.h',
|
'ArenaAllocator.h',
|
||||||
'ArenaAllocatorExtensions.h',
|
'ArenaAllocatorExtensions.h',
|
||||||
'ArrayIterator.h',
|
'ArrayIterator.h',
|
||||||
|
'Dafsa.h',
|
||||||
'IncrementalTokenizer.h',
|
'IncrementalTokenizer.h',
|
||||||
'Observer.h',
|
'Observer.h',
|
||||||
'StickyTimeDuration.h',
|
'StickyTimeDuration.h',
|
||||||
|
@ -89,6 +90,7 @@ EXPORTS.mozilla += [
|
||||||
]
|
]
|
||||||
|
|
||||||
UNIFIED_SOURCES += [
|
UNIFIED_SOURCES += [
|
||||||
|
'Dafsa.cpp',
|
||||||
'IncrementalTokenizer.cpp',
|
'IncrementalTokenizer.cpp',
|
||||||
'nsArray.cpp',
|
'nsArray.cpp',
|
||||||
'nsArrayEnumerator.cpp',
|
'nsArrayEnumerator.cpp',
|
||||||
|
|
|
@ -0,0 +1,85 @@
|
||||||
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
|
||||||
|
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
|
||||||
|
/* 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/. */
|
||||||
|
|
||||||
|
#include "mozilla/Dafsa.h"
|
||||||
|
#include "gtest/gtest.h"
|
||||||
|
|
||||||
|
#include "nsString.h"
|
||||||
|
|
||||||
|
using mozilla::Dafsa;
|
||||||
|
|
||||||
|
namespace dafsa_test_1 {
|
||||||
|
#include "dafsa_test_1.inc" // kDafsa
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Dafsa, Constructor)
|
||||||
|
{
|
||||||
|
Dafsa d(dafsa_test_1::kDafsa);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Dafsa, StringsFound)
|
||||||
|
{
|
||||||
|
Dafsa d(dafsa_test_1::kDafsa);
|
||||||
|
|
||||||
|
int tag = d.Lookup(NS_LITERAL_CSTRING("foo.bar.baz"));
|
||||||
|
EXPECT_EQ(tag, 1);
|
||||||
|
|
||||||
|
tag = d.Lookup(NS_LITERAL_CSTRING("a.test.string"));
|
||||||
|
EXPECT_EQ(tag, 0);
|
||||||
|
|
||||||
|
tag = d.Lookup(NS_LITERAL_CSTRING("a.test.string2"));
|
||||||
|
EXPECT_EQ(tag, 2);
|
||||||
|
|
||||||
|
tag = d.Lookup(NS_LITERAL_CSTRING("aaaa"));
|
||||||
|
EXPECT_EQ(tag, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Dafsa, StringsNotFound)
|
||||||
|
{
|
||||||
|
Dafsa d(dafsa_test_1::kDafsa);
|
||||||
|
|
||||||
|
// Matches all but last letter.
|
||||||
|
int tag = d.Lookup(NS_LITERAL_CSTRING("foo.bar.ba"));
|
||||||
|
EXPECT_EQ(tag, Dafsa::kKeyNotFound);
|
||||||
|
|
||||||
|
// Matches prefix with extra letter.
|
||||||
|
tag = d.Lookup(NS_LITERAL_CSTRING("a.test.strings"));
|
||||||
|
EXPECT_EQ(tag, Dafsa::kKeyNotFound);
|
||||||
|
|
||||||
|
// Matches small portion.
|
||||||
|
tag = d.Lookup(NS_LITERAL_CSTRING("a.test"));
|
||||||
|
EXPECT_EQ(tag, Dafsa::kKeyNotFound);
|
||||||
|
|
||||||
|
// Matches repeating pattern with extra letters.
|
||||||
|
tag = d.Lookup(NS_LITERAL_CSTRING("aaaaa"));
|
||||||
|
EXPECT_EQ(tag, Dafsa::kKeyNotFound);
|
||||||
|
|
||||||
|
// Empty string.
|
||||||
|
tag = d.Lookup(NS_LITERAL_CSTRING(""));
|
||||||
|
EXPECT_EQ(tag, Dafsa::kKeyNotFound);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Dafsa, HugeString)
|
||||||
|
{
|
||||||
|
Dafsa d(dafsa_test_1::kDafsa);
|
||||||
|
|
||||||
|
int tag = d.Lookup(NS_LITERAL_CSTRING(
|
||||||
|
"This is a very long string that is larger than the dafsa itself. "
|
||||||
|
"This is a very long string that is larger than the dafsa itself. "
|
||||||
|
"This is a very long string that is larger than the dafsa itself. "
|
||||||
|
"This is a very long string that is larger than the dafsa itself. "
|
||||||
|
"This is a very long string that is larger than the dafsa itself. "
|
||||||
|
"This is a very long string that is larger than the dafsa itself. "
|
||||||
|
"This is a very long string that is larger than the dafsa itself. "
|
||||||
|
"This is a very long string that is larger than the dafsa itself. "
|
||||||
|
"This is a very long string that is larger than the dafsa itself. "
|
||||||
|
"This is a very long string that is larger than the dafsa itself. "
|
||||||
|
"This is a very long string that is larger than the dafsa itself. "
|
||||||
|
"This is a very long string that is larger than the dafsa itself. "
|
||||||
|
"This is a very long string that is larger than the dafsa itself. "
|
||||||
|
));
|
||||||
|
EXPECT_EQ(tag, Dafsa::kKeyNotFound);
|
||||||
|
}
|
|
@ -60,6 +60,8 @@ public:
|
||||||
}
|
}
|
||||||
|
|
||||||
void DoRandomOperation() {
|
void DoRandomOperation() {
|
||||||
|
using mozilla::UniquePtr;
|
||||||
|
|
||||||
Object* obj;
|
Object* obj;
|
||||||
switch (rand() & 0x7) {
|
switch (rand() & 0x7) {
|
||||||
case 0: {
|
case 0: {
|
||||||
|
|
|
@ -29,6 +29,7 @@
|
||||||
# define CATCH(e) if (0)
|
# define CATCH(e) if (0)
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#include "gtest/gtest.h"
|
||||||
|
|
||||||
#if defined(XP_UNIX)
|
#if defined(XP_UNIX)
|
||||||
extern unsigned int _gdb_sleep_duration;
|
extern unsigned int _gdb_sleep_duration;
|
||||||
|
|
|
@ -0,0 +1,6 @@
|
||||||
|
%%
|
||||||
|
foo.bar.baz, 1
|
||||||
|
a.test.string, 0
|
||||||
|
a.test.string2, 2
|
||||||
|
aaaa, 4
|
||||||
|
%%
|
|
@ -15,6 +15,7 @@ UNIFIED_SOURCES += [
|
||||||
'TestCloneInputStream.cpp',
|
'TestCloneInputStream.cpp',
|
||||||
'TestCOMPtrEq.cpp',
|
'TestCOMPtrEq.cpp',
|
||||||
'TestCRT.cpp',
|
'TestCRT.cpp',
|
||||||
|
'TestDafsa.cpp',
|
||||||
'TestEncoding.cpp',
|
'TestEncoding.cpp',
|
||||||
'TestEscapeURL.cpp',
|
'TestEscapeURL.cpp',
|
||||||
'TestEventTargetQI.cpp',
|
'TestEventTargetQI.cpp',
|
||||||
|
@ -84,6 +85,13 @@ LOCAL_INCLUDES += [
|
||||||
'../../base',
|
'../../base',
|
||||||
]
|
]
|
||||||
|
|
||||||
|
GENERATED_FILES = [
|
||||||
|
'dafsa_test_1.inc',
|
||||||
|
]
|
||||||
|
dafsa_data = GENERATED_FILES['dafsa_test_1.inc']
|
||||||
|
dafsa_data.script = '../../ds/make_dafsa.py'
|
||||||
|
dafsa_data.inputs = ['dafsa_test_1.dat']
|
||||||
|
|
||||||
FINAL_LIBRARY = 'xul-gtest'
|
FINAL_LIBRARY = 'xul-gtest'
|
||||||
|
|
||||||
include('/ipc/chromium/chromium-config.mozbuild')
|
include('/ipc/chromium/chromium-config.mozbuild')
|
||||||
|
|
Загрузка…
Ссылка в новой задаче