-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgocd.go
379 lines (330 loc) · 11 KB
/
gocd.go
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
/*
gocd is a go library for matching and parsing company designators
(like `Limited`, `LLC`, `Incorporée`) in company names.
*/
//go:generate cp -p ../company_designator/company_designator.yml data
//go:generate cp -p ../../cpan/Business-CompanyDesignator/t/t10/data.yml data/tests.yml
//go:generate go run assets_generate.go
package gocd
import (
"io/ioutil"
"regexp"
"strings"
"golang.org/x/text/unicode/norm"
"gopkg.in/yaml.v2"
)
// In languages with continuous scripts, we don't require a word
// break ([\pZ\pP] before/after designators
var LangContinua = map[string]bool{
"zh": true,
"ja": true,
"ko": true,
}
// The standard/perl RE engine in Go doesn't use POSIX-style
// longest match semantics, which bites us where we have proper
// subset alternates e.g. `Vennootschap` vs `Vennootschap Onder Firma`.
// We can workaround this by blacklisting the shorter variant and
// doing a second pass match if the first one fails.
var EndDesignatorBlacklist = map[string]bool{
"Vennootschap": true, // vs. `Vennootschap Onder Firma`
"L.L.C.": true, // vs. `Co. L.L.C.`
"L.C.": true, // vs. `L.L.C.`
"Co.": true, // vs. `& Co.` (ampersand matched as punct)
"Co. L.L.C.": true, // vs. `& Co. L.L.C.` (ampersand matched as punct)
}
const (
DefaultDataset = "/company_designator.yml"
StrBeginBefore = `^\pZ*`
StrBeginAfter = `[\pZ\pP]\pZ*(.+?)\pZ*$`
StrEndBefore = `^\pZ*(.+?)\pZ*([\pZ\pP])\pZ*`
StrEndAfter = `\pZ*$`
StrEndContBefore = `^\pZ*(.+?)\pZ*`
StrEndContAfter = `\pZ*$`
)
type PositionType int
const (
None PositionType = iota
End
EndFallback
EndCont
Begin
BeginFallback
)
func (p PositionType) String() string {
return [...]string{
"none", "end", "end_fallback", "end_cont", "begin", "begin_fallback",
}[p]
}
type entry struct {
LongName string
AbbrStd string `yaml:"abbr_std"`
Abbr []string `yaml:"abbr"`
Lang string `yaml:"lang"`
Lead bool `yaml:"lead"`
Doc string `yaml:"doc"`
}
type Remap map[string]*regexp.Regexp
type dataset map[string]entry
type Parser struct {
re Remap
ds *dataset
reEnd *regexp.Regexp
reEndFallback *regexp.Regexp
reEndCont *regexp.Regexp
reBegin *regexp.Regexp
reBeginFallback *regexp.Regexp
}
type Context struct {
in []byte
from uint64
to uint64
before []byte
match []byte
after []byte
}
type Result struct {
Input string // Initial input string
Matched bool // True if a Designator was found
ShortName string // Input with any matched Designator removed
Designator string // The Designator found in input, if any (verbatim)
Position PositionType // The Designator position, if found
}
func loadDataset() (*dataset, error) {
fh, err := assets.Open(DefaultDataset)
if err != nil {
return nil, err
}
data, err := ioutil.ReadAll(fh)
if err != nil {
return nil, err
}
ds := make(dataset)
err = yaml.Unmarshal(data, ds)
if err != nil {
return nil, err
}
//fmt.Fprintf(os.Stderr, "+ loaded %d entries from dataset %q\n", len(ds), filepath)
return &ds, nil
}
// escapeDes does some standard escaping of designators
func escapeDes(des string, re Remap) string {
// Allow ampersands to match more broadly
des = re["Ampersand"].ReplaceAllString(des, `\s*[&+]\s*`)
// Escape parentheses in the designator itself
des = re["Paren"].ReplaceAllString(des, `\$1`)
// Periods are treated as optional literals, with optional trailing stff
des = re["PeriodSpace"].ReplaceAllString(des, `\.*[\pZ,()-]*`)
// Interpret embedded spaces in designators pretty liberally
des = re["Space"].ReplaceAllString(des, `[\pZ,()-]+`)
return des
}
func addPattern(patterns []string, s string, t PositionType, re Remap) []string {
// Skip Begin/End strings if they are blacklisted
if (t == End || t == Begin) && EndDesignatorBlacklist[s] {
return patterns
}
// Skip BeginFallback/EndFallback strings *unless* they are blacklisted
if (t == EndFallback || t == BeginFallback) && !EndDesignatorBlacklist[s] {
return patterns
}
// Normalise s to NFD before adding
s = norm.NFD.String(s)
// Do our standard designator escaping
s = escapeDes(s, re)
// Add s to patterns
patterns = append(patterns, s)
// If s contains unicode diacritics, also add a stripped version
s2 := re["UnicodeMarks"].ReplaceAllString(s, "")
if s2 != s {
patterns = append(patterns, s2)
}
return patterns
}
func compileREPatterns(ds *dataset, t PositionType, re Remap) string {
var patterns []string
for long, e := range *ds {
// FIXME: dev
/*
if long != "Company" {
continue
}
*/
// If t is Begin or BeginFallback, restrict to entries with 'Lead' set
if (t == Begin || t == BeginFallback) && !e.Lead {
continue
}
// If t is EndCont, restrict to languages in LangContinua
if t == EndCont && !LangContinua[e.Lang] {
continue
}
// Add long to patterns
patterns = addPattern(patterns, long, t, re)
// Add AbbrStd to patterns
/*
if e.AbbrStd != "" {
patterns = addPattern(patterns, e.AbbrStd, t, re)
}
*/
// Add Abbrs to patterns
for _, a := range e.Abbr {
// Only add non-ASCII abbreviations as continuous
if t == EndCont && re["ASCII"].MatchString(a) {
continue
}
patterns = addPattern(patterns, a, t, re)
}
}
if len(patterns) == 0 {
return ""
}
// Join patterns as alternates, and always allow outer parentheses
pattern := `\(?` + `(?:` + strings.Join(patterns, "|") + `)` + `\)?`
//fmt.Fprintf(os.Stderr, "+ compiled %d %q patterns from dataset\n", len(patterns), t.String())
//fmt.Fprintf(os.Stderr, "++ %s\n", pattern)
return pattern
}
// New returns a new Parser using the default company designator dataset
func New() (*Parser, error) {
p := Parser{}
re := make(Remap)
re["PeriodSpace"] = regexp.MustCompile(`\.\pZ*`)
re["Space"] = regexp.MustCompile(`\pZ+`)
re["SpaceDotSpace"] = regexp.MustCompile(`\pZ+\.\pZ*`)
re["Ampersand"] = regexp.MustCompile(`\pZ*&\pZ*`)
re["Paren"] = regexp.MustCompile("([()\uff08\uff09])")
re["ParenSpace"] = regexp.MustCompile("\\pZ*[()\uff08\uff09]\\pZ*")
re["UnicodeMarks"] = regexp.MustCompile(`\pM`)
re["ASCII"] = regexp.MustCompile("^[[:ascii:]]+$")
p.re = re
ds, err := loadDataset()
if err != nil {
return nil, err
}
p.ds = ds
// Compile End patterns
endPattern := compileREPatterns(ds, End, re)
//fmt.Fprintf(os.Stderr, "+ endPattern: %s\n", endPattern)
endFallbackPattern := compileREPatterns(ds, EndFallback, re)
//fmt.Fprintf(os.Stderr, "+ endFallbackPattern: %s\n", endFallbackPattern)
endContPattern := compileREPatterns(ds, EndCont, re)
//fmt.Fprintf(os.Stderr, "+ endContPattern: %s\n", endContPattern)
beginPattern := compileREPatterns(ds, Begin, re)
//fmt.Fprintf(os.Stderr, "+ beginPattern: %s\n", beginPattern)
beginFallbackPattern := compileREPatterns(ds, BeginFallback, re)
//fmt.Fprintf(os.Stderr, "+ beginFallbackPattern: %s\n", beginFallbackPattern)
if endPattern != "" {
p.reEnd = regexp.MustCompile(`(?i)` +
StrEndBefore + `(` + endPattern + `)` + StrEndAfter)
//fmt.Fprintf(os.Stderr, "+ reEnd: %s\n", p.reEnd)
}
if endFallbackPattern != "" {
p.reEndFallback = regexp.MustCompile(`(?i)` +
StrEndBefore + `(` + endFallbackPattern + `)` + StrEndAfter)
//fmt.Fprintf(os.Stderr, "+ reEndFallback: %s\n", p.reEndFallback)
}
if endContPattern != "" {
p.reEndCont = regexp.MustCompile(`(?i)` +
StrEndContBefore + `(` + endContPattern + `)` + StrEndContAfter)
//fmt.Fprintf(os.Stderr, "+ reEndCont: %s\n", p.reEndCont)
}
if beginPattern != "" {
p.reBegin = regexp.MustCompile(`(?i)` +
StrBeginBefore + `(` + beginPattern + `)` + StrBeginAfter)
}
//fmt.Fprintf(os.Stderr, "+ reBegin: %s\n", p.reBegin)
if beginFallbackPattern != "" {
p.reBeginFallback = regexp.MustCompile(`(?i)` +
StrBeginBefore + `(` + beginFallbackPattern + `)` + StrBeginAfter)
//fmt.Fprintf(os.Stderr, "+ reBeginFallback: %s\n", p.reBeginFallback)
}
return &p, nil
}
// checkDesPunct handles the reEnd situation where our breaking
// punctuation character before the designator might be something
// we should include in the designator e.g. '&' or '('
func (p *Parser) checkDesPunct(punct, des string) string {
if punct != "(" {
return des
}
return punct + des
}
// Parse matches an input company name string against the company
// designator dataset and returns a Result object containing match
// results and any parsed components
func (p *Parser) Parse(input string) (*Result, error) {
inputNFD := norm.NFD.String(input)
inputNFC := norm.NFC.String(input)
res := Result{Input: inputNFC, ShortName: inputNFC}
ctx := Context{}
ctx.in = []byte(inputNFD)
// Minimal preprocessing
// Try and normalise strange dot-space pattern with initials e.g. P .J . S . C
inputNFD = p.re["SpaceDotSpace"].ReplaceAllString(inputNFD, ". ")
// Designators are usually final, so try end matching first
var matches []string
if p.reEnd != nil {
matches = p.reEnd.FindStringSubmatch(inputNFD)
if matches != nil {
//fmt.Printf("+ reEnd matches: %q %q %q\n", matches[1], matches[2], matches[3])
res.Matched = true
res.ShortName = norm.NFC.String(matches[1])
res.Designator = norm.NFC.String(p.checkDesPunct(matches[2], matches[3]))
res.Position = End
return &res, nil
}
}
// No final designator - retry using the fallback endings we blacklisted
// for the previous run
if p.reEndFallback != nil {
matches = p.reEndFallback.FindStringSubmatch(inputNFD)
if matches != nil {
//fmt.Printf("+ reEndFallback matches: %q %q %q\n", matches[1], matches[2], matches[3])
res.Matched = true
res.ShortName = norm.NFC.String(matches[1])
res.Designator = norm.NFC.String(p.checkDesPunct(matches[2], matches[3]))
// Note we use End here rather than EndFallback
res.Position = End
return &res, nil
}
}
// No final designator - retry without a word break for the subset of
// languages that use continuous scripts (see LangContinua above)
// Strip all parentheses for continuous script matches
if p.reEndCont != nil {
inputNFDStripped := p.re["ParenSpace"].ReplaceAllString(inputNFD, "")
matches = p.reEndCont.FindStringSubmatch(inputNFDStripped)
if matches != nil {
res.Matched = true
res.ShortName = norm.NFC.String(matches[1])
res.Designator = norm.NFC.String(matches[2])
// Note we use End here rather than EndCont
res.Position = End
return &res, nil
}
}
// No final designator - check for a lead designator instead (e.g. ru, nl, etc.)
if p.reBegin != nil {
matches = p.reBegin.FindStringSubmatch(inputNFD)
if matches != nil {
res.Matched = true
res.ShortName = norm.NFC.String(matches[2])
res.Designator = norm.NFC.String(matches[1])
res.Position = Begin
return &res, nil
}
}
// No lead designator either - retry using the fallback endings we
// blacklisted for the previous run
if p.reBeginFallback != nil {
matches = p.reBeginFallback.FindStringSubmatch(inputNFD)
if matches != nil {
res.Matched = true
res.ShortName = norm.NFC.String(matches[2])
res.Designator = norm.NFC.String(matches[1])
// Note we use Begin here rather than BeginFallback
res.Position = Begin
return &res, nil
}
}
return &res, nil
}