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
110651
1
use 5.022;
11
1
1
1
2
1
66
use feature 'unicode_strings';
12
1
1
1
2
0
10
use strict;
13
1
1
1
1
0
22
use warnings;
14
1
1
1
1
0
16
no warnings qw(experimental::vlb);
15
1
1
1
1
1
2
use utf8;
16
1
1
1
13
0
31
use Encode qw/decode_utf8 encode FB_DEFAULT/;
17
1
1
1
2
1
25
use File::Basename;
18
1
1
1
1
0
13
use Cwd 'abs_path';
19
1
1
1
1
1
21
use File::Spec;
20
1
1
1
1
0
16
use File::Temp qw/ tempfile tempdir /;
21
1
1
1
264
1
3590
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
14
  my ($expression) = @_;
44
14
14
5
103
  return eval { qr /$expression/ };
45}
46
47sub quote_re {
48
14
13
  my ($expression) = @_;
49
14
11
  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
47
   $1 . (defined($2) ? quotemeta($2) : '')
62/xge;
63
14
16
  return $expression;
64}
65
66sub file_to_lists {
67
3
4
  my ($re) = @_;
68
3
5
  my @patterns;
69  my %hints;
70
3
0
  my $fh;
71
3
30
  if (open($fh, '<:utf8', $re)) {
72
3
5
    local $/=undef;
73
3
23
    my $file=<$fh>;
74
3
11
    close $fh;
75
3
2
    my $line_number = 0;
76
3
2
    my $hint = '';
77
3
14
    for (split /\R/, $file) {
78
17
12
      ++$line_number;
79
17
6
      chomp;
80
17
21
      if (/^#(?:\s(.+)|)/) {
81
6
13
        $hint = $1 if ($hint eq '' && defined $1);
82
6
3
        next;
83      }
84
11
12
      $hint = '' unless $_ ne '';
85
11
10
      next if $_ eq '$^';
86
11
8
      my $pattern = $_;
87
11
29
      next unless s/^(.+)/(?:$1)/;
88
7
8
      my $quoted = quote_re($1);
89
7
7
      unless (test_re $quoted) {
90
1
3
        my $error = $@;
91
1
48
        my $home = dirname(__FILE__);
92
1
20
        $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
2
        $hint = '';
96      }
97
7
10
      if (defined $hints{$_}) {
98
1
1
        my $pattern_length = length $pattern;
99
1
2
        my $wrapped = CheckSpelling::Util::wrap_in_backticks($pattern);
100
1
16
        print STDERR "$re:$line_number:1 ... $pattern_length, Warning - duplicate pattern: $wrapped (duplicate-pattern)\n";
101
1
3
        $_ = '(?:\$^ - skipped because duplicate-pattern on $line_number)';
102      } else {
103
6
8
        push @patterns, $_;
104
6
9
        $hints{$_} = $hint;
105      }
106
7
11
      $hint = '';
107    }
108  }
109
110  return {
111
3
14
    patterns => \@patterns,
112    hints => \%hints,
113  };
114}
115
116sub file_to_list {
117
2
1298
  my ($re) = @_;
118
2
5
  my $lists = file_to_lists($re);
119
120
2
2
1
6
  return @{$lists->{'patterns'}};
121}
122
123sub list_to_re {
124
2
2
  my (@list) = @_;
125
2
5
5
1
4
2
  @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
58
  my ($thing) = @_;
133
73
312
  return defined $thing && $thing ne '' && $thing =~ /^\d+$/;
134}
135
136sub valid_word {
137  # shortest_word is an absolute
138
22
26
  our ($shortest, $longest, $shortest_word, $longest_word);
139
22
20
  $shortest = $shortest_word if $shortest_word;
140
22
18
  if ($longest_word) {
141    # longest_word is an absolute
142
20
20
    $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
18
  our ($upper_pattern, $lower_pattern, $punctuation_pattern);
149
22
66
12
145
  my $word_pattern = join '|', (grep { defined $_ && /./ } ($upper_pattern, $lower_pattern, $punctuation_pattern));
150
22
18
  $word_pattern = q<\\w|'> unless $word_pattern;
151
22
41
  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
21
  $shortest = 3 unless defined $shortest;
157
22
18
  $longest = '' unless not_empty($longest);
158
22
70
  $word_match = "(?:$word_pattern){$shortest,$longest}";
159
22
172
  return qr/\b$word_match\b/;
160}
161
162sub load_dictionary {
163
12
2017
  my ($dict) = @_;
164
12
5
  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
6
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
168
12
14
  $ignore_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_IGNORE_PATTERN', q<[^a-zA-Z']>);
169
12
43
  $upper_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_UPPER_PATTERN', '[A-Z]');
170
12
27
  $lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_LOWER_PATTERN', '[a-z]');
171
12
20
  $not_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_LOWER_PATTERN', '[^a-z]');
172
12
20
  $not_upper_or_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_UPPER_OR_LOWER_PATTERN', '[^A-Za-z]');
173
12
22
  $punctuation_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_PUNCTUATION_PATTERN', q<'>);
174
12
26
  %dictionary = ();
175
176
12
428
  open(DICT, '<:utf8', $dict);
177
12
55
  while (!eof(DICT)) {
178
31
36
    my $word = <DICT>;
179
31
20
    chomp $word;
180
31
100
    next unless $word =~ $word_match;
181
28
23
    my $l = length $word;
182
28
22
    $longest = -1 unless not_empty($longest);
183
28
28
    $longest = $l if $l > $longest;
184
28
31
    $shortest = $l if $l < $shortest;
185
28
59
    $dictionary{$word}=1;
186  }
187
12
26
  close DICT;
188
189
12
10
  $word_match = valid_word();
190}
191
192sub hunspell_dictionary {
193
3
3
  my ($dict) = @_;
194
3
3
  my $name = $dict;
195
3
2
  $name =~ s{/src/index/hunspell/index\.dic$}{};
196
3
15
  $name =~ s{.*/}{};
197
3
3
  my $aff = $dict;
198
3
4
  my $encoding;
199
3
9
  $aff =~ s/\.dic$/.aff/;
200
3
26
  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
10
    close AFF;
207  }
208  return {
209
3
327
    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
11323
  my ($configuration) = @_;
219
9
11
  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
10
  our $hunspell_dictionary_path = CheckSpelling::Util::get_file_from_env('hunspell_dictionary_path', '');
222
9
11
  our $timeout = CheckSpelling::Util::get_val_from_env('splitter_timeout', 30);
223
9
4
  our %forbidden_re_descriptions;
224
9
7
  if ($hunspell_dictionary_path) {
225
3
35
    our @hunspell_dictionaries = ();
226
1
1
1
1
1
1
1
1
1
3
187
1087
20
6
1
15
7
2
16
144
    if (eval 'use Text::Hunspell; 1') {
227
3
114
      my @hunspell_dictionaries_list = glob("$hunspell_dictionary_path/*.dic");
228
3
3
      for my $hunspell_dictionary_file (@hunspell_dictionaries_list) {
229
3
5
        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
12
  my (@patterns_re_list, %in_patterns_re_list);
236
9
57
  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
7
    $patterns_re = undef;
242  }
243
244
9
35
  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
7
    $forbidden_re = undef;
251  }
252
253
9
55
  if (-e "$configuration/candidates.txt") {
254
1
1
    @candidates_re_list = file_to_list "$configuration/candidates.txt";
255
1
2
2
1
2
3
    @candidates_re_list = map { my $quoted = quote_re($_); $in_patterns_re_list{$_} || !test_re($quoted) ? '' : $quoted } @candidates_re_list;
256
1
1
    $candidates_re = list_to_re @candidates_re_list;
257  } else {
258
8
9
    $candidates_re = undef;
259  }
260
261
9
12
  our $largest_file = CheckSpelling::Util::get_val_from_env('INPUT_LARGEST_FILE', 1024*1024);
262
263
9
7
  my $disable_flags = CheckSpelling::Util::get_file_from_env('INPUT_DISABLE_CHECKS', '');
264
9
9
  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
4
  our $disable_single_line_file = $disable_flags =~ /(?:^|,|\s)single-line-file(?:,|\s|$)/;
267
268
9
8
  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
8
  our $check_images = CheckSpelling::Util::get_val_from_env('INPUT_CHECK_IMAGES', '');
272
9
6
  $check_images = $check_images =~ /^(?:1|true)$/i;
273
274
9
6
  our $check_file_names = CheckSpelling::Util::get_file_from_env('check_file_names', '');
275
276
9
8
  our $use_magic_file = CheckSpelling::Util::get_val_from_env('INPUT_USE_MAGIC_FILE', '');
277
278
9
6
  $word_match = valid_word();
279
280
9
11
  our $base_dict = CheckSpelling::Util::get_file_from_env('dict', "$configuration/words");
281
9
45
  $base_dict = '/usr/share/dict/words' unless -e $base_dict;
282
9
7
  load_dictionary($base_dict);
283}
284
285sub split_line {
286
1156
444
  our (%dictionary, $word_match, $disable_word_collating);
287
1156
507
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
288
1156
451
  our @hunspell_dictionaries;
289
1156
418
  our $shortest;
290
1156
756
  my $shortest_threshold = $shortest + 2;
291
1156
630
  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
535
  my $rsqm = "\xE2\x80\x99";
296
297
1156
673
  my ($words, $unrecognized) = (0, 0);
298
1156
771
  my ($line, $unique_ref, $unique_unrecognized_ref, $unrecognized_line_items_ref) = @_;
299
1156
5545
    $line =~ s/(?:$rsqm|&apos;|&#39;|\%27|&#8217;|&#x2019;|&rsquo;|\\u2019|\x{2019}|')+/'/g;
300
1156
2288
    $line =~ s/(?:$ignore_pattern)+/ /g;
301
1156
1754
    while ($line =~ s/($upper_pattern{2,})($upper_pattern$lower_pattern{2,})/ $1 $2 /g) {}
302
1156
3205
    while ($line =~ s/((?:$lower_pattern|$punctuation_pattern)+)($upper_pattern)/$1 $2/g) {}
303
1156
1327
    for my $token (split /\s+/, $line) {
304
3619
3358
      next unless $token =~ /$pattern/;
305
2464
2113
      $token =~ s/^(?:'|$rsqm)+//g;
306
2464
2455
      $token =~ s/(?:'|$rsqm)+s?$//g;
307
2464
1402
      my $raw_token = $token;
308
2464
1462
      $token =~ s/^[^Ii]?'+(.*)/$1/;
309
2464
1213
      $token =~ s/(.*?)'+$/$1/;
310
2464
3855
      next unless $token =~ $word_match;
311
2311
2050
      if (defined $dictionary{$token}) {
312
1032
520
        ++$words;
313
1032
551
        $unique_ref->{$token}=1;
314
1032
838
        next;
315      }
316
1279
938
      if (@hunspell_dictionaries) {
317
1254
623
        my $found = 0;
318
1254
725
        for my $hunspell_dictionary (@hunspell_dictionaries) {
319          my $token_encoded = defined $hunspell_dictionary->{'encoding'} ?
320
1254
1122
            encode($hunspell_dictionary->{'encoding'}, $token) : $token;
321
1254
2776
          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
960
        next if $found;
329      }
330
1279
934
      my $key = lc $token;
331
1279
1176
      if (defined $dictionary{$key}) {
332
6
3
        ++$words;
333
6
4
        $unique_ref->{$key}=1;
334
6
8
        next;
335      }
336
1273
927
      unless ($disable_word_collating) {
337
1273
719
        $key =~ s/''+/'/g;
338
1273
1360
        $key =~ s/'[sd]$// unless length $key >= $shortest_threshold;
339      }
340
1273
1070
      if (defined $dictionary{$key}) {
341
0
0
        ++$words;
342
0
0
        $unique_ref->{$key}=1;
343
0
0
        next;
344      }
345
1273
640
      ++$unrecognized;
346
1273
777
      $unique_unrecognized_ref->{$raw_token}=1;
347
1273
1667
      $unrecognized_line_items_ref->{$raw_token}=1;
348    }
349
1156
1628
    return ($words, $unrecognized);
350}
351
352sub skip_file {
353
7
26
  my ($temp_dir, $reason) = @_;
354
7
184
  open(SKIPPED, '>:utf8', "$temp_dir/skipped");
355
7
40
  print SKIPPED $reason;
356
7
102
  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
11756
  my ($file) = @_;
377  our (
378
16
10
    $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
42
  $ignore_next_line_pattern = '$^' unless $ignore_next_line_pattern =~ /./;
388
389
16
13
  our %forbidden_re_descriptions;
390
16
11
  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
17
  my @candidates_re_hits = (0) x scalar @candidates_re_list;
396
16
14
  my @candidates_re_lines = (0) x scalar @candidates_re_list;
397
16
11
  my @forbidden_re_hits = (0) x scalar @forbidden_re_list;
398
16
12
  my @forbidden_re_lines = (0) x scalar @forbidden_re_list;
399
16
29
  my $temp_dir = tempdir(DIR=>$sandbox);
400
16
2515
  print STDERR "checking file: $file\n" if defined $ENV{'DEBUG'};
401
16
408
  open(NAME, '>', "$temp_dir/name");
402
16
39
    print NAME $file;
403
16
209
  close NAME;
404
16
195
  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
5
    return $temp_dir;
408  }
409
15
21
  if ($use_magic_file) {
410
8
11484
    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
30302
      my $file_kind = <$file_fh>;
422
8
4894
      close $file_fh;
423
8
11
      my $file_converted = 0;
424
8
19
      if ($check_images && $file_kind =~ m<^image/>) {
425
0
0
        ($file, $file_converted) = maybe_ocr_file($file);
426      }
427
8
189
      if ($file_converted == 0 && $file_kind =~ /^(.*?); charset=binary/) {
428
2
35
        skip_file($temp_dir, "it appears to be a binary file (`$1`) (binary-file)\n");
429
2
49
        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
80
  my $file_size = -s $file;
437
13
9
  if (defined $largest_file) {
438
13
13
    unless ($check_file_names eq $file) {
439
13
12
      if ($file_size > $largest_file) {
440
1
2
        skip_file($temp_dir, "size `$file_size` exceeds limit `$largest_file` (large-file)\n");
441
1
2
        return $temp_dir;
442      }
443    }
444  }
445
12
99
  open FILE, '<', $file;
446
12
11
  binmode FILE;
447
12
6
  my $head;
448
12
110
  read(FILE, $head, 4096);
449
12
809
  $head =~ s/(?:\r|\n)+$//;
450
12
52
  my $dos_new_lines = () = $head =~ /\r\n/gi;
451
12
39
  my $unix_new_lines = () = $head =~ /\n/gi;
452
12
107
  my $mac_new_lines = () = $head =~ /\r/gi;
453
12
53
  local $/;
454
12
67
  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
5
    $/ = "\r\n";
458  } elsif ($mac_new_lines > $unix_new_lines) {
459
2
7
    $/ = "\r";
460  } else {
461
6
6
    $/ = "\n";
462  }
463
12
28
  seek(FILE, 0, 0);
464
12
18
  ($words, $unrecognized) = (0, 0);
465
12
37
  %unique = ();
466
12
30
  %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
116
  };
474
475
12
305
  open(WARNINGS, '>:utf8', "$temp_dir/warnings");
476
12
9
  our $timeout;
477
12
15
  eval {
478
12
0
100
0
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
479
12
33
    alarm $timeout;
480
481
12
17
    my $ignore_next_line = 0;
482
12
11
    my $offset = 0;
483
12
92
    while (<FILE>) {
484
1159
1007
      if ($. == 1) {
485
12
21
        unless ($disable_minified_file) {
486
12
74
          if ($file_size >= 512 && length($_) == $file_size) {
487
1
12
            skip_file($temp_dir, "file only has a single line (single-line-file)\n");
488
1
4
            last;
489          }
490        }
491      }
492
1158
2283
      $_ = decode_utf8($_, FB_DEFAULT);
493
1158
2676
      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
1459
      s/\R$//;
498
1158
1012
      s/^\x{FEFF}// if $. == 1;
499
1158
1061
      next unless /./;
500
1157
722
      my $raw_line = $_;
501
502
1157
652
      my $ignore_this_line = $ignore_next_line;
503
1157
1058
      $ignore_next_line = ($_ =~ /$ignore_next_line_pattern/);
504
1157
775
      next if $ignore_this_line;
505
506      # hook for custom line based text exclusions:
507
1156
757
      if (defined $patterns_re) {
508
2
6
10
8
        s/($patterns_re)/"="x length($1)/ge;
509      }
510
1156
705
      my $initial_line_state = $_;
511
1156
671
      my $previous_line_state = $_;
512
1156
579
      my $line_flagged;
513
1156
789
      if ($forbidden_re) {
514
9
5
59
12
        while (s/($forbidden_re)/"="x length($1)/e) {
515
5
4
          $line_flagged = 1;
516
5
9
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
517
5
2
          my $found_trigger_re;
518
5
5
          for my $i (0 .. $#forbidden_re_list) {
519
7
4
            my $forbidden_re_singleton = $forbidden_re_list[$i];
520
7
6
            my $test_line = $previous_line_state;
521
7
4
58
6
            if ($test_line =~ s/($forbidden_re_singleton)/"="x length($1)/e) {
522
4
4
              next unless $test_line eq $_;
523
4
6
              my ($begin_test, $end_test, $match_test) = ($-[0] + 1, $+[0] + 1, $1);
524
4
4
              next unless $begin == $begin_test;
525
4
3
              next unless $end == $end_test;
526
4
8
              next unless $match eq $match_test;
527
4
3
              $found_trigger_re = $forbidden_re_singleton;
528
4
7
              my $hit = "$.:$begin:$end";
529
4
3
              $forbidden_re_hits[$i]++;
530
4
5
              $forbidden_re_lines[$i] = $hit unless $forbidden_re_lines[$i];
531
4
7
              last;
532            }
533          }
534
5
13
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
535
5
5
          if ($found_trigger_re) {
536
4
8
            my $description = $forbidden_re_descriptions{$found_trigger_re} || '';
537
4
8
            $found_trigger_re =~ s/^\(\?:(.*)\)$/$1/;
538
4
4
            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
9
        $_ = $initial_line_state;
550      }
551      # This is to make it easier to deal w/ rules:
552
1156
1025
      s/^/ /;
553
1156
750
      my %unrecognized_line_items = ();
554
1156
941
      my ($new_words, $new_unrecognized) = split_line($_, \%unique, \%unique_unrecognized, \%unrecognized_line_items);
555
1156
694
      $words += $new_words;
556
1156
466
      $unrecognized += $new_unrecognized;
557
1156
746
      my $line_length = length($raw_line);
558
1156
1639
      for my $token (sort CheckSpelling::Util::case_biased keys %unrecognized_line_items) {
559
1020
569
        my $found_token = 0;
560
1020
480
        my $raw_token = $token;
561
1020
591
        $token =~ s/'/(?:'|\x{2019}|\&apos;|\&#39;)+/g;
562
1020
424
        my $before;
563
1020
1603
        if ($token =~ /^$upper_pattern$lower_pattern/) {
564
5
2
          $before = '(?<=.)';
565        } elsif ($token =~ /^$upper_pattern/) {
566
0
0
          $before = "(?<!$upper_pattern)";
567        } else {
568
1015
600
          $before = "(?<=$not_lower_pattern)";
569        }
570
1020
1119
        my $after = ($token =~ /$upper_pattern$/) ? "(?=$not_upper_or_lower_pattern)|(?=$upper_pattern$lower_pattern)" : "(?=$not_lower_pattern)";
571
1020
2078
        while ($raw_line =~ /(?:\b|$before)($token)(?:\b|$after)/g) {
572
1270
624
          $line_flagged = 1;
573
1270
509
          $found_token = 1;
574
1270
1759
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
575
1270
1169
          next unless $match =~ /./;
576
1270
896
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
577
1270
4794
          print WARNINGS ":$.:$begin ... $end: $wrapped\n";
578        }
579
1020
1076
        unless ($found_token) {
580
3
27
          if ($raw_line !~ /$token.*$token/ && $raw_line =~ /($token)/) {
581
3
6
            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
1801
      if ($line_flagged && $candidates_re) {
592
1
2
        $_ = $previous_line_state = $initial_line_state;
593
1
1
16
3
        s/($candidates_re)/"="x length($1)/ge;
594
1
2
        if ($_ ne $initial_line_state) {
595
1
0
          $_ = $previous_line_state;
596
1
2
          for my $i (0 .. $#candidates_re_list) {
597
2
1
            my $candidate_re = $candidates_re_list[$i];
598
2
18
            next unless $candidate_re =~ /./ && $raw_line =~ /$candidate_re/;
599
1
1
5
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
2
              $candidates_re_lines[$i] = $hit unless $candidates_re_lines[$i];
606
1
2
              $_ = $previous_line_state;
607            }
608          }
609        }
610      }
611
1156
944
      unless ($disable_minified_file) {
612
1156
903
        s/={3,}//g;
613
1156
810
        $offset += length;
614
1156
1023
        my $ratio = int($offset / $.);
615
1156
667
        my $ratio_threshold = 1000;
616
1156
2968
        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
80
    alarm 0;
624  };
625
12
14
  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
51
  close FILE;
633
12
141
  close WARNINGS;
634
635
12
26
  if ($unrecognized || @candidates_re_hits || @forbidden_re_hits) {
636
11
276
    open(STATS, '>:utf8', "$temp_dir/stats");
637
11
148
      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
148
    close STATS;
645
11
211
    open(UNKNOWN, '>:utf8', "$temp_dir/unknown");
646
11
19
49
32
      print UNKNOWN map { "$_\n" } sort CheckSpelling::Util::case_biased keys %unique_unrecognized;
647
11
105
    close UNKNOWN;
648  }
649
650
12
110
  return $temp_dir;
651}
652
653sub main {
654
2
427
  my ($configuration, @ARGV) = @_;
655
2
1
  our %dictionary;
656
2
2
  unless (%dictionary) {
657
1
1
    init($configuration);
658  }
659
660  # read all input
661
2
2
  my @reports;
662
663
2
2
  for my $file (@ARGV) {
664
2
2
    my $temp_dir = split_file($file);
665
2
2
    push @reports, "$temp_dir\n";
666  }
667
2
6
  print join '', @reports;
668}
669
6701;