File Coverage

File:lib/CheckSpelling/UnknownWordSplitter.pm
Coverage:85.1%

linestmtbrancondsubtimecode
1#! -*-perl-*-
2
3# ~/bin/w
4# Search for potentially misspelled words
5# Output is:
6# misspellled
7# woord (WOORD, Woord, woord, woord's)
8package CheckSpelling::UnknownWordSplitter;
9
10
1
1
111565
1
use 5.022;
11
1
1
1
2
0
50
use feature 'unicode_strings';
12
1
1
1
3
1
7
use strict;
13
1
1
1
1
1
18
use warnings;
14
1
1
1
1
0
19
no warnings qw(experimental::vlb);
15
1
1
1
1
0
3
use utf8;
16
1
1
1
12
1
25
use Encode qw/decode_utf8 encode FB_DEFAULT/;
17
1
1
1
2
0
32
use File::Basename;
18
1
1
1
1
1
16
use Cwd 'abs_path';
19
1
1
1
4
3
26
use File::Spec;
20
1
1
1
1
1
14
use File::Temp qw/ tempfile tempdir /;
21
1
1
1
287
1
3450
use CheckSpelling::Util;
22our $VERSION='0.1.0';
23
24my ($longest_word, $shortest_word, $word_match, $forbidden_re, $patterns_re, $candidates_re, $disable_word_collating, $check_file_names);
25my ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
26my ($shortest, $longest) = (255, 0);
27my @forbidden_re_list;
28my %forbidden_re_descriptions;
29my @candidates_re_list;
30my $hunspell_dictionary_path;
31my @hunspell_dictionaries;
32my %dictionary = ();
33my $base_dict;
34my %unique;
35my %unique_unrecognized;
36my ($last_file, $words, $unrecognized) = ('', 0, 0);
37my ($ignore_next_line_pattern);
38my ($check_images);
39
40my $disable_flags;
41
42sub test_re {
43
14
10
  my ($expression) = @_;
44
14
14
8
101
  return eval { qr /$expression/ };
45}
46
47sub quote_re {
48
14
11
  my ($expression) = @_;
49
14
13
  return $expression if $expression =~ /\?\{/;
50
14
31
  $expression =~ s/
51   \G
52   (
53      (?:[^\\]|\\[^Q])*
54   )
55   (?:
56      \\Q
57      (?:[^\\]|\\[^E])*
58      (?:\\E)?
59   )?
60/
61
28
46
   $1 . (defined($2) ? quotemeta($2) : '')
62/xge;
63
14
15
  return $expression;
64}
65
66sub file_to_lists {
67
3
4
  my ($re) = @_;
68
3
3
  my @patterns;
69  my %hints;
70
3
0
  my $fh;
71
3
32
  if (open($fh, '<:utf8', $re)) {
72
3
4
    local $/=undef;
73
3
31
    my $file=<$fh>;
74
3
13
    close $fh;
75
3
2
    my $line_number = 0;
76
3
3
    my $hint = '';
77
3
14
    for (split /\R/, $file) {
78
17
6
      ++$line_number;
79
17
10
      chomp;
80
17
18
      if (/^#(?:\s(.+)|)/) {
81
6
13
        $hint = $1 if ($hint eq '' && defined $1);
82
6
7
        next;
83      }
84
11
12
      $hint = '' unless $_ ne '';
85
11
12
      next if $_ eq '$^';
86
11
8
      my $pattern = $_;
87
11
28
      next unless s/^(.+)/(?:$1)/;
88
7
7
      my $quoted = quote_re($1);
89
7
6
      unless (test_re $quoted) {
90
1
1
        my $error = $@;
91
1
49
        my $home = dirname(__FILE__);
92
1
21
        $error =~ s/$home.*?\.pm line \d+\./$re line $line_number (bad-regex)/;
93
1
12
        print STDERR $error;
94
1
1
        $_ = '(?:\$^ - skipped because bad-regex)';
95
1
1
        $hint = '';
96      }
97
7
11
      if (defined $hints{$_}) {
98
1
1
        my $pattern_length = length $pattern;
99
1
1
        my $wrapped = CheckSpelling::Util::wrap_in_backticks($pattern);
100
1
15
        print STDERR "$re:$line_number:1 ... $pattern_length, Warning - duplicate pattern: $wrapped (duplicate-pattern)\n";
101
1
2
        $_ = '(?:\$^ - skipped because duplicate-pattern on $line_number)';
102      } else {
103
6
6
        push @patterns, $_;
104
6
9
        $hints{$_} = $hint;
105      }
106
7
10
      $hint = '';
107    }
108  }
109
110  return {
111
3
14
    patterns => \@patterns,
112    hints => \%hints,
113  };
114}
115
116sub file_to_list {
117
2
1304
  my ($re) = @_;
118
2
5
  my $lists = file_to_lists($re);
119
120
2
2
2
6
  return @{$lists->{'patterns'}};
121}
122
123sub list_to_re {
124
2
1
  my (@list) = @_;
125
2
5
5
2
4
6
  @list = map { my $quoted = quote_re($_); test_re($quoted) ? $quoted : '' } @list;
126
2
5
2
5
  @list = grep { $_ ne '' } @list;
127
2
2
  return '$^' unless scalar @list;
128
2
6
  return join "|", (@list);
129}
130
131sub not_empty {
132
73
62
  my ($thing) = @_;
133
73
313
  return defined $thing && $thing ne '' && $thing =~ /^\d+$/;
134}
135
136sub valid_word {
137  # shortest_word is an absolute
138
22
30
  our ($shortest, $longest, $shortest_word, $longest_word);
139
22
20
  $shortest = $shortest_word if $shortest_word;
140
22
22
  if ($longest_word) {
141    # longest_word is an absolute
142
20
21
    $longest = $longest_word;
143  } elsif (not_empty($longest)) {
144    # we allow for some sloppiness (a couple of stuck keys per word)
145    # it's possible that this should scale with word length
146
1
1
    $longest += 2;
147  }
148
22
14
  our ($upper_pattern, $lower_pattern, $punctuation_pattern);
149
22
66
16
146
  my $word_pattern = join '|', (grep { defined $_ && /./ } ($upper_pattern, $lower_pattern, $punctuation_pattern));
150
22
21
  $word_pattern = q<\\w|'> unless $word_pattern;
151
22
44
  if ((defined $shortest && not_empty($longest)) &&
152      ($shortest > $longest)) {
153
0
0
    $word_pattern = "(?:$word_pattern){3}";
154
0
0
    return qr/$word_pattern/;
155  }
156
22
20
  $shortest = 3 unless defined $shortest;
157
22
17
  $longest = '' unless not_empty($longest);
158
22
76
  $word_match = "(?:$word_pattern){$shortest,$longest}";
159
22
237
  return qr/\b$word_match\b/;
160}
161
162sub load_dictionary {
163
12
1957
  my ($dict) = @_;
164
12
6
  our ($word_match, $longest, $shortest, $longest_word, $shortest_word, %dictionary);
165
12
11
  $longest_word = CheckSpelling::Util::get_val_from_env('INPUT_LONGEST_WORD', undef);
166
12
9
  $shortest_word = CheckSpelling::Util::get_val_from_env('INPUT_SHORTEST_WORD', undef);
167
12
9
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
168
12
7
  $ignore_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_IGNORE_PATTERN', q<[^a-zA-Z']>);
169
12
40
  $upper_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_UPPER_PATTERN', '[A-Z]');
170
12
25
  $lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_LOWER_PATTERN', '[a-z]');
171
12
19
  $not_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_LOWER_PATTERN', '[^a-z]');
172
12
22
  $not_upper_or_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_UPPER_OR_LOWER_PATTERN', '[^A-Za-z]');
173
12
26
  $punctuation_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_PUNCTUATION_PATTERN', q<'>);
174
12
23
  %dictionary = ();
175
176
12
406
  open(DICT, '<:utf8', $dict);
177
12
50
  while (!eof(DICT)) {
178
31
34
    my $word = <DICT>;
179
31
26
    chomp $word;
180
31
91
    next unless $word =~ $word_match;
181
28
27
    my $l = length $word;
182
28
14
    $longest = -1 unless not_empty($longest);
183
28
29
    $longest = $l if $l > $longest;
184
28
22
    $shortest = $l if $l < $shortest;
185
28
53
    $dictionary{$word}=1;
186  }
187
12
27
  close DICT;
188
189
12
10
  $word_match = valid_word();
190}
191
192sub hunspell_dictionary {
193
3
6
  my ($dict) = @_;
194
3
5
  my $name = $dict;
195
3
4
  $name =~ s{/src/index/hunspell/index\.dic$}{};
196
3
15
  $name =~ s{.*/}{};
197
3
3
  my $aff = $dict;
198
3
2
  my $encoding;
199
3
4
  $aff =~ s/\.dic$/.aff/;
200
3
31
  if (open AFF, '<', $aff) {
201
3
20
    while (<AFF>) {
202
0
0
      next unless /^SET\s+(\S+)/;
203
0
0
      $encoding = $1 if ($1 !~ /utf-8/i);
204
0
0
      last;
205    }
206
3
8
    close AFF;
207  }
208  return {
209
3
346
    name => $name,
210    dict => $dict,
211    aff => $aff,
212    encoding => $encoding,
213    engine => Text::Hunspell->new($aff, $dict),
214  }
215}
216
217sub init {
218
9
11512
  my ($configuration) = @_;
219
9
12
  our ($word_match, %unique, $patterns_re, @forbidden_re_list, $forbidden_re, @candidates_re_list, $candidates_re);
220
9
28
  our $sandbox = CheckSpelling::Util::get_file_from_env('sandbox', '');
221
9
9
  our $hunspell_dictionary_path = CheckSpelling::Util::get_file_from_env('hunspell_dictionary_path', '');
222
9
18
  our $timeout = CheckSpelling::Util::get_val_from_env('splitter_timeout', 30);
223
9
4
  our %forbidden_re_descriptions;
224
9
11
  if ($hunspell_dictionary_path) {
225
3
35
    our @hunspell_dictionaries = ();
226
1
1
1
1
1
1
1
1
1
3
184
1056
19
4
1
15
6
0
15
141
    if (eval 'use Text::Hunspell; 1') {
227
3
116
      my @hunspell_dictionaries_list = glob("$hunspell_dictionary_path/*.dic");
228
3
6
      for my $hunspell_dictionary_file (@hunspell_dictionaries_list) {
229
3
9
        push @hunspell_dictionaries, hunspell_dictionary($hunspell_dictionary_file);
230      }
231    } else {
232
0
0
      print STDERR "Could not load Text::Hunspell for dictionaries (hunspell-unavailable)\n";
233    }
234  }
235
9
11
  my (@patterns_re_list, %in_patterns_re_list);
236
9
60
  if (-e "$configuration/patterns.txt") {
237
0
0
    @patterns_re_list = file_to_list "$configuration/patterns.txt";
238
0
0
    $patterns_re = list_to_re @patterns_re_list;
239
0
0
0
0
    %in_patterns_re_list = map {$_ => 1} @patterns_re_list;
240  } else {
241
9
11
    $patterns_re = undef;
242  }
243
244
9
41
  if (-e "$configuration/forbidden.txt") {
245
1
1
    my $forbidden_re_info = file_to_lists "$configuration/forbidden.txt";
246
1
1
1
2
    @forbidden_re_list = @{$forbidden_re_info->{'patterns'}};
247
1
1
0
3
    %forbidden_re_descriptions = %{$forbidden_re_info->{'hints'}};
248
1
1
    $forbidden_re = list_to_re @forbidden_re_list;
249  } else {
250
8
5
    $forbidden_re = undef;
251  }
252
253
9
41
  if (-e "$configuration/candidates.txt") {
254
1
2
    @candidates_re_list = file_to_list "$configuration/candidates.txt";
255
1
2
2
1
2
4
    @candidates_re_list = map { my $quoted = quote_re($_); $in_patterns_re_list{$_} || !test_re($quoted) ? '' : $quoted } @candidates_re_list;
256
1
2
    $candidates_re = list_to_re @candidates_re_list;
257  } else {
258
8
7
    $candidates_re = undef;
259  }
260
261
9
13
  our $largest_file = CheckSpelling::Util::get_val_from_env('INPUT_LARGEST_FILE', 1024*1024);
262
263
9
9
  my $disable_flags = CheckSpelling::Util::get_file_from_env('INPUT_DISABLE_CHECKS', '');
264
9
11
  our $disable_word_collating = $disable_flags =~ /(?:^|,|\s)word-collating(?:,|\s|$)/;
265
9
6
  our $disable_minified_file = $disable_flags =~ /(?:^|,|\s)minified-file(?:,|\s|$)/;
266
9
5
  our $disable_single_line_file = $disable_flags =~ /(?:^|,|\s)single-line-file(?:,|\s|$)/;
267
268
9
6
  our $ignore_next_line_pattern = CheckSpelling::Util::get_file_from_env('INPUT_IGNORE_NEXT_LINE', '');
269
9
7
  $ignore_next_line_pattern =~ s/\s+/|/g;
270
271
9
6
  our $check_images = CheckSpelling::Util::get_val_from_env('INPUT_CHECK_IMAGES', '');
272
9
5
  $check_images = $check_images =~ /^(?:1|true)$/i;
273
274
9
4
  our $check_file_names = CheckSpelling::Util::get_file_from_env('check_file_names', '');
275
276
9
5
  our $use_magic_file = CheckSpelling::Util::get_val_from_env('INPUT_USE_MAGIC_FILE', '');
277
278
9
14
  $word_match = valid_word();
279
280
9
18
  our $base_dict = CheckSpelling::Util::get_file_from_env('dict', "$configuration/words");
281
9
50
  $base_dict = '/usr/share/dict/words' unless -e $base_dict;
282
9
9
  load_dictionary($base_dict);
283}
284
285sub split_line {
286
1156
504
  our (%dictionary, $word_match, $disable_word_collating);
287
1156
536
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
288
1156
441
  our @hunspell_dictionaries;
289
1156
512
  our $shortest;
290
1156
768
  my $shortest_threshold = $shortest + 2;
291
1156
614
  my $pattern = '.';
292  # $pattern = "(?:$upper_pattern){$shortest,}|$upper_pattern(?:$lower_pattern){2,}\n";
293
294  # https://www.fileformat.info/info/unicode/char/2019/
295
1156
551
  my $rsqm = "\xE2\x80\x99";
296
297
1156
668
  my ($words, $unrecognized) = (0, 0);
298
1156
766
  my ($line, $unique_ref, $unique_unrecognized_ref, $unrecognized_line_items_ref) = @_;
299
1156
5461
    $line =~ s/(?:$rsqm|&apos;|&#39;|\%27|&#8217;|&#x2019;|&rsquo;|\\u2019|\x{2019}|')+/'/g;
300
1156
2221
    $line =~ s/(?:$ignore_pattern)+/ /g;
301
1156
1671
    while ($line =~ s/($upper_pattern{2,})($upper_pattern$lower_pattern{2,})/ $1 $2 /g) {}
302
1156
3459
    while ($line =~ s/((?:$lower_pattern|$punctuation_pattern)+)($upper_pattern)/$1 $2/g) {}
303
1156
1338
    for my $token (split /\s+/, $line) {
304
3619
3428
      next unless $token =~ /$pattern/;
305
2464
2093
      $token =~ s/^(?:'|$rsqm)+//g;
306
2464
2516
      $token =~ s/(?:'|$rsqm)+s?$//g;
307
2464
1329
      my $raw_token = $token;
308
2464
1675
      $token =~ s/^[^Ii]?'+(.*)/$1/;
309
2464
1162
      $token =~ s/(.*?)'+$/$1/;
310
2464
3855
      next unless $token =~ $word_match;
311
2311
2053
      if (defined $dictionary{$token}) {
312
1032
492
        ++$words;
313
1032
564
        $unique_ref->{$token}=1;
314
1032
735
        next;
315      }
316
1279
915
      if (@hunspell_dictionaries) {
317
1254
620
        my $found = 0;
318
1254
714
        for my $hunspell_dictionary (@hunspell_dictionaries) {
319          my $token_encoded = defined $hunspell_dictionary->{'encoding'} ?
320
1254
1105
            encode($hunspell_dictionary->{'encoding'}, $token) : $token;
321
1254
2847
          next unless ($hunspell_dictionary->{'engine'}->check($token_encoded));
322
0
0
          ++$words;
323
0
0
          $dictionary{$token} = 1;
324
0
0
          $unique_ref->{$token}=1;
325
0
0
          $found = 1;
326
0
0
          last;
327        }
328
1254
973
        next if $found;
329      }
330
1279
942
      my $key = lc $token;
331
1279
1175
      if (defined $dictionary{$key}) {
332
6
4
        ++$words;
333
6
4
        $unique_ref->{$key}=1;
334
6
7
        next;
335      }
336
1273
890
      unless ($disable_word_collating) {
337
1273
761
        $key =~ s/''+/'/g;
338
1273
1386
        $key =~ s/'[sd]$// unless length $key >= $shortest_threshold;
339      }
340
1273
1098
      if (defined $dictionary{$key}) {
341
0
0
        ++$words;
342
0
0
        $unique_ref->{$key}=1;
343
0
0
        next;
344      }
345
1273
611
      ++$unrecognized;
346
1273
775
      $unique_unrecognized_ref->{$raw_token}=1;
347
1273
1673
      $unrecognized_line_items_ref->{$raw_token}=1;
348    }
349
1156
1617
    return ($words, $unrecognized);
350}
351
352sub skip_file {
353
7
21
  my ($temp_dir, $reason) = @_;
354
7
191
  open(SKIPPED, '>:utf8', "$temp_dir/skipped");
355
7
38
  print SKIPPED $reason;
356
7
121
  close SKIPPED;
357}
358
359sub maybe_ocr_file {
360
0
0
  my ($file) = @_;
361
0
0
  my $tesseract = dirname(dirname(dirname(__FILE__)))."/wrappers/run-tesseract";
362
0
0
  $ENV{'input'} = $file;
363
0
0
  my $text_file = `"$tesseract"`;
364
0
0
  delete $ENV{'input'};
365
0
0
  return ($file, 0) unless defined $text_file;
366
0
0
  my $file_converted = 0;
367
0
0
  chomp $text_file;
368
0
0
  if ($text_file =~ /./) {
369
0
0
    $file_converted = 1;
370
0
0
    $file = $text_file;
371  }
372
0
0
  return ($file, $file_converted);
373}
374
375sub split_file {
376
16
11728
  my ($file) = @_;
377  our (
378
16
11
    $unrecognized, $shortest, $largest_file, $words,
379    $word_match, %unique, %unique_unrecognized, $forbidden_re,
380    @forbidden_re_list, $patterns_re, %dictionary,
381    $candidates_re, @candidates_re_list, $check_file_names, $use_magic_file, $disable_minified_file,
382    $disable_single_line_file,
383    $ignore_next_line_pattern,
384    $sandbox,
385    $check_images,
386  );
387
16
32
  $ignore_next_line_pattern = '$^' unless $ignore_next_line_pattern =~ /./;
388
389
16
5
  our %forbidden_re_descriptions;
390
16
6
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
391
392  # https://www.fileformat.info/info/unicode/char/2019/
393
16
9
  my $rsqm = "\xE2\x80\x99";
394
395
16
16
  my @candidates_re_hits = (0) x scalar @candidates_re_list;
396
16
10
  my @candidates_re_lines = (0) x scalar @candidates_re_list;
397
16
13
  my @forbidden_re_hits = (0) x scalar @forbidden_re_list;
398
16
7
  my @forbidden_re_lines = (0) x scalar @forbidden_re_list;
399
16
31
  my $temp_dir = tempdir(DIR=>$sandbox);
400
16
2358
  print STDERR "checking file: $file\n" if defined $ENV{'DEBUG'};
401
16
369
  open(NAME, '>', "$temp_dir/name");
402
16
37
    print NAME $file;
403
16
213
  close NAME;
404
16
202
  if (defined readlink($file) &&
405      rindex(File::Spec->abs2rel(abs_path($file)), '../', 0) == 0) {
406
1
4
    skip_file($temp_dir, "file only has a single line (out-of-bounds-symbolic-link)\n");
407
1
3
    return $temp_dir;
408  }
409
15
34
  if ($use_magic_file) {
410
8
11461
    if (open(my $file_fh, '-|',
411              '/usr/bin/file',
412              '-b',
413              '--mime',
414              '-e', 'cdf',
415              '-e', 'compress',
416              '-e', 'csv',
417              '-e', 'elf',
418              '-e', 'json',
419              '-e', 'tar',
420              $file)) {
421
8
29582
      my $file_kind = <$file_fh>;
422
8
4829
      close $file_fh;
423
8
11
      my $file_converted = 0;
424
8
18
      if ($check_images && $file_kind =~ m<^image/>) {
425
0
0
        ($file, $file_converted) = maybe_ocr_file($file);
426      }
427
8
178
      if ($file_converted == 0 && $file_kind =~ /^(.*?); charset=binary/) {
428
2
31
        skip_file($temp_dir, "it appears to be a binary file (`$1`) (binary-file)\n");
429
2
51
        return $temp_dir;
430      }
431    }
432  } elsif ($file =~ /\.(?:png|jpe?g|gif)$/) {
433
0
0
    my $file_converted = 0;
434
0
0
    ($file, $file_converted) = maybe_ocr_file($file);
435  }
436
13
103
  my $file_size = -s $file;
437
13
13
  if (defined $largest_file) {
438
13
14
    unless ($check_file_names eq $file) {
439
13
21
      if ($file_size > $largest_file) {
440
1
2
        skip_file($temp_dir, "size `$file_size` exceeds limit `$largest_file` (large-file)\n");
441
1
3
        return $temp_dir;
442      }
443    }
444  }
445
12
124
  open FILE, '<', $file;
446
12
11
  binmode FILE;
447
12
6
  my $head;
448
12
108
  read(FILE, $head, 4096);
449
12
811
  $head =~ s/(?:\r|\n)+$//;
450
12
46
  my $dos_new_lines = () = $head =~ /\r\n/gi;
451
12
29
  my $unix_new_lines = () = $head =~ /\n/gi;
452
12
110
  my $mac_new_lines = () = $head =~ /\r/gi;
453
12
52
  local $/;
454
12
60
  if ($unix_new_lines == 0 && $mac_new_lines == 0) {
455
3
5
    $/ = "\n";
456  } elsif ($dos_new_lines >= $unix_new_lines && $dos_new_lines >= $mac_new_lines) {
457
1
9
    $/ = "\r\n";
458  } elsif ($mac_new_lines > $unix_new_lines) {
459
2
7
    $/ = "\r";
460  } else {
461
6
5
    $/ = "\n";
462  }
463
12
29
  seek(FILE, 0, 0);
464
12
18
  ($words, $unrecognized) = (0, 0);
465
12
35
  %unique = ();
466
12
32
  %unique_unrecognized = ();
467
468  local $SIG{__WARN__} = sub {
469
0
0
    my $message = shift;
470
0
0
    $message =~ s/> line/> in $file - line/;
471
0
0
    chomp $message;
472
0
0
    print STDERR "$message\n";
473
12
110
  };
474
475
12
312
  open(WARNINGS, '>:utf8', "$temp_dir/warnings");
476
12
10
  our $timeout;
477
12
7
  eval {
478
12
0
106
0
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
479
12
33
    alarm $timeout;
480
481
12
14
    my $ignore_next_line = 0;
482
12
15
    my $offset = 0;
483
12
88
    while (<FILE>) {
484
1159
1051
      if ($. == 1) {
485
12
14
        unless ($disable_minified_file) {
486
12
53
          if ($file_size >= 512 && length($_) == $file_size) {
487
1
11
            skip_file($temp_dir, "file only has a single line (single-line-file)\n");
488
1
4
            last;
489          }
490        }
491      }
492
1158
2302
      $_ = decode_utf8($_, FB_DEFAULT);
493
1158
2884
      if (/[\x{D800}-\x{DFFF}]/) {
494
0
0
        skip_file($temp_dir, "file contains a UTF-16 surrogate -- UTF-16 surrogates are not supported (utf16-surrogate-file)\n");
495
0
0
        last;
496      }
497
1158
1449
      s/\R$//;
498
1158
1103
      s/^\x{FEFF}// if $. == 1;
499
1158
1075
      next unless /./;
500
1157
753
      my $raw_line = $_;
501
502
1157
605
      my $ignore_this_line = $ignore_next_line;
503
1157
1015
      $ignore_next_line = ($_ =~ /$ignore_next_line_pattern/);
504
1157
782
      next if $ignore_this_line;
505
506      # hook for custom line based text exclusions:
507
1156
746
      if (defined $patterns_re) {
508
2
6
10
8
        s/($patterns_re)/"="x length($1)/ge;
509      }
510
1156
698
      my $initial_line_state = $_;
511
1156
726
      my $previous_line_state = $_;
512
1156
554
      my $line_flagged;
513
1156
830
      if ($forbidden_re) {
514
9
5
58
11
        while (s/($forbidden_re)/"="x length($1)/e) {
515
5
3
          $line_flagged = 1;
516
5
9
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
517
5
4
          my $found_trigger_re;
518
5
4
          for my $i (0 .. $#forbidden_re_list) {
519
7
5
            my $forbidden_re_singleton = $forbidden_re_list[$i];
520
7
6
            my $test_line = $previous_line_state;
521
7
4
57
7
            if ($test_line =~ s/($forbidden_re_singleton)/"="x length($1)/e) {
522
4
5
              next unless $test_line eq $_;
523
4
6
              my ($begin_test, $end_test, $match_test) = ($-[0] + 1, $+[0] + 1, $1);
524
4
3
              next unless $begin == $begin_test;
525
4
3
              next unless $end == $end_test;
526
4
3
              next unless $match eq $match_test;
527
4
4
              $found_trigger_re = $forbidden_re_singleton;
528
4
6
              my $hit = "$.:$begin:$end";
529
4
4
              $forbidden_re_hits[$i]++;
530
4
3
              $forbidden_re_lines[$i] = $hit unless $forbidden_re_lines[$i];
531
4
8
              last;
532            }
533          }
534
5
12
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
535
5
6
          if ($found_trigger_re) {
536
4
10
            my $description = $forbidden_re_descriptions{$found_trigger_re} || '';
537
4
9
            $found_trigger_re =~ s/^\(\?:(.*)\)$/$1/;
538
4
2
            my $quoted_trigger_re = CheckSpelling::Util::truncate_with_ellipsis(CheckSpelling::Util::wrap_in_backticks($found_trigger_re), 99);
539
4
6
            if ($description ne '') {
540
3
13
              print WARNINGS ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns rule: $description - $quoted_trigger_re (forbidden-pattern)\n";
541            } else {
542
1
5
              print WARNINGS ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns entry: $quoted_trigger_re (forbidden-pattern)\n";
543            }
544          } else {
545
1
4
            print WARNINGS ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns entry (forbidden-pattern)\n";
546          }
547
5
24
          $previous_line_state = $_;
548        }
549
9
8
        $_ = $initial_line_state;
550      }
551      # This is to make it easier to deal w/ rules:
552
1156
1040
      s/^/ /;
553
1156
679
      my %unrecognized_line_items = ();
554
1156
883
      my ($new_words, $new_unrecognized) = split_line($_, \%unique, \%unique_unrecognized, \%unrecognized_line_items);
555
1156
603
      $words += $new_words;
556
1156
538
      $unrecognized += $new_unrecognized;
557
1156
734
      my $line_length = length($raw_line);
558
1156
1642
      for my $token (sort CheckSpelling::Util::case_biased keys %unrecognized_line_items) {
559
1020
500
        my $found_token = 0;
560
1020
464
        my $raw_token = $token;
561
1020
577
        $token =~ s/'/(?:'|\x{2019}|\&apos;|\&#39;)+/g;
562
1020
434
        my $before;
563
1020
1541
        if ($token =~ /^$upper_pattern$lower_pattern/) {
564
5
4
          $before = '(?<=.)';
565        } elsif ($token =~ /^$upper_pattern/) {
566
0
0
          $before = "(?<!$upper_pattern)";
567        } else {
568
1015
620
          $before = "(?<=$not_lower_pattern)";
569        }
570
1020
1141
        my $after = ($token =~ /$upper_pattern$/) ? "(?=$not_upper_or_lower_pattern)|(?=$upper_pattern$lower_pattern)" : "(?=$not_lower_pattern)";
571
1020
2149
        while ($raw_line =~ /(?:\b|$before)($token)(?:\b|$after)/g) {
572
1270
692
          $line_flagged = 1;
573
1270
501
          $found_token = 1;
574
1270
1723
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
575
1270
1214
          next unless $match =~ /./;
576
1270
973
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
577
1270
4830
          print WARNINGS ":$.:$begin ... $end: $wrapped\n";
578        }
579
1020
1122
        unless ($found_token) {
580
3
28
          if ($raw_line !~ /$token.*$token/ && $raw_line =~ /($token)/) {
581
3
4
            my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
582
3
3
            my $wrapped = CheckSpelling::Util::wrap_in_backticks($raw_token);
583
3
12
            print WARNINGS ":$.:$begin ... $end: $wrapped\n";
584          } else {
585
0
0
            my $offset = $line_length + 1;
586
0
0
            my $wrapped = CheckSpelling::Util::wrap_in_backticks($raw_token);
587
0
0
            print WARNINGS ":$.:1 ... $offset, Warning - Could not identify whole word $wrapped in line (token-is-substring)\n";
588          }
589        }
590      }
591
1156
1917
      if ($line_flagged && $candidates_re) {
592
1
2
        $_ = $previous_line_state = $initial_line_state;
593
1
1
17
2
        s/($candidates_re)/"="x length($1)/ge;
594
1
2
        if ($_ ne $initial_line_state) {
595
1
1
          $_ = $previous_line_state;
596
1
1
          for my $i (0 .. $#candidates_re_list) {
597
2
2
            my $candidate_re = $candidates_re_list[$i];
598
2
17
            next unless $candidate_re =~ /./ && $raw_line =~ /$candidate_re/;
599
1
1
6
2
            if (($_ =~ s/($candidate_re)/"="x length($1)/e)) {
600
1
2
              my ($begin, $end) = ($-[0] + 1, $+[0] + 1);
601
1
2
              my $hit = "$.:$begin:$end";
602
1
1
              $_ = $previous_line_state;
603
1
1
5
2
              my $replacements = ($_ =~ s/($candidate_re)/"="x length($1)/ge);
604
1
1
              $candidates_re_hits[$i] += $replacements;
605
1
4
              $candidates_re_lines[$i] = $hit unless $candidates_re_lines[$i];
606
1
2
              $_ = $previous_line_state;
607            }
608          }
609        }
610      }
611
1156
859
      unless ($disable_minified_file) {
612
1156
913
        s/={3,}//g;
613
1156
822
        $offset += length;
614
1156
1070
        my $ratio = int($offset / $.);
615
1156
620
        my $ratio_threshold = 1000;
616
1156
3066
        if ($ratio > $ratio_threshold) {
617
2
7
          skip_file($temp_dir, "average line width ($ratio) exceeds the threshold ($ratio_threshold) (minified-file)\n");
618
2
6
          last;
619        }
620      }
621    }
622
623
12
81
    alarm 0;
624  };
625
12
9
  if ($@) {
626
0
0
    die unless $@ eq "alarm\n";
627
0
0
    print WARNINGS ":$.:1 ... 1, Warning - Could not parse file within time limit (slow-file)\n";
628
0
0
    skip_file($temp_dir, "it could not be parsed file within time limit (slow-file)\n");
629
0
0
    last;
630  }
631
632
12
41
  close FILE;
633
12
136
  close WARNINGS;
634
635
12
23
  if ($unrecognized || @candidates_re_hits || @forbidden_re_hits) {
636
11
275
    open(STATS, '>:utf8', "$temp_dir/stats");
637
11
146
      print STATS "{words: $words, unrecognized: $unrecognized, unknown: ".(keys %unique_unrecognized).
638      ", unique: ".(keys %unique).
639      (@candidates_re_hits ? ", candidates: [".(join ',', @candidates_re_hits)."]" : "").
640      (@candidates_re_lines ? ", candidate_lines: [".(join ',', @candidates_re_lines)."]" : "").
641      (@forbidden_re_hits ? ", forbidden: [".(join ',', @forbidden_re_hits)."]" : "").
642      (@forbidden_re_lines ? ", forbidden_lines: [".(join ',', @forbidden_re_lines)."]" : "").
643      "}";
644
11
140
    close STATS;
645
11
215
    open(UNKNOWN, '>:utf8', "$temp_dir/unknown");
646
11
19
43
31
      print UNKNOWN map { "$_\n" } sort CheckSpelling::Util::case_biased keys %unique_unrecognized;
647
11
107
    close UNKNOWN;
648  }
649
650
12
117
  return $temp_dir;
651}
652
653sub main {
654
2
406
  my ($configuration, @ARGV) = @_;
655
2
2
  our %dictionary;
656
2
2
  unless (%dictionary) {
657
1
1
    init($configuration);
658  }
659
660  # read all input
661
2
1
  my @reports;
662
663
2
2
  for my $file (@ARGV) {
664
2
3
    my $temp_dir = split_file($file);
665
2
3
    push @reports, "$temp_dir\n";
666  }
667
2
8
  print join '', @reports;
668}
669
6701;