File Coverage

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

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
109039
1
use 5.022;
11
1
1
1
2
1
41
use feature 'unicode_strings';
12
1
1
1
1
2
7
use strict;
13
1
1
1
2
1
20
use warnings;
14
1
1
1
1
0
15
no warnings qw(experimental::vlb);
15
1
1
1
1
1
1
use utf8;
16
1
1
1
11
2
24
use Encode qw/decode_utf8 encode FB_DEFAULT/;
17
1
1
1
2
1
25
use File::Basename;
18
1
1
1
1
1
15
use Cwd 'abs_path';
19
1
1
1
1
1
20
use File::Spec;
20
1
1
1
1
0
16
use File::Temp qw/ tempfile tempdir /;
21
1
1
1
301
1
3700
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 $begin_block_re = '';
26my @begin_block_list = ();
27my @end_block_list = ();
28my ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
29my ($shortest, $longest) = (255, 0);
30my @forbidden_re_list;
31my %forbidden_re_descriptions;
32my @candidates_re_list;
33my $hunspell_dictionary_path;
34my @hunspell_dictionaries;
35my %dictionary = ();
36my $base_dict;
37my %unique;
38my %unique_unrecognized;
39my ($last_file, $words, $unrecognized) = ('', 0, 0);
40my ($ignore_next_line_pattern);
41
42my $disable_flags;
43
44sub test_re {
45
32
39
  my ($expression) = @_;
46
32
32
20
205
  return eval { qr /$expression/ };
47}
48
49sub quote_re {
50
34
24
  my ($expression) = @_;
51
34
30
  return $expression if $expression =~ /\?\{/;
52
34
64
  $expression =~ s/
53   \G
54   (
55      (?:[^\\]|\\[^Q])*
56   )
57   (?:
58      \\Q
59      (?:[^\\]|\\[^E])*
60      (?:\\E)?
61   )?
62/
63
68
110
   $1 . (defined($2) ? quotemeta($2) : '')
64/xge;
65
34
44
  return $expression;
66}
67
68sub file_to_lists {
69
6
6
  my ($re) = @_;
70
6
6
  my @patterns;
71  my %hints;
72
6
0
  my $fh;
73
6
53
  if (open($fh, '<:utf8', $re)) {
74
6
10
    local $/=undef;
75
6
35
    my $file=<$fh>;
76
6
14
    close $fh;
77
6
4
    my $line_number = 0;
78
6
3
    my $hint = '';
79
6
23
    for (split /\R/, $file) {
80
32
25
      ++$line_number;
81
32
11
      chomp;
82
32
35
      if (/^#(?:\s(.+)|)/) {
83
12
27
        $hint = $1 if ($hint eq '' && defined $1);
84
12
12
        next;
85      }
86
20
23
      $hint = '' unless $_ ne '';
87
20
16
      my $pattern = $_;
88
20
66
      next unless s/^(.+)/(?:$1)/;
89
13
13
      my $quoted = quote_re($1);
90
13
10
      unless (test_re $quoted) {
91
1
1
        my $error = $@;
92
1
40
        my $home = dirname(__FILE__);
93
1
18
        $error =~ s/$home.*?\.pm line \d+\./$re line $line_number (bad-regex)/;
94
1
10
        print STDERR $error;
95
1
1
        $_ = '(?:\$^ - skipped because bad-regex)';
96
1
1
        $hint = '';
97      }
98
13
18
      if (defined $hints{$_}) {
99
1
2
        my $pattern_length = length $pattern;
100
1
1
        my $wrapped = CheckSpelling::Util::wrap_in_backticks($pattern);
101
1
14
        print STDERR "$re:$line_number:1 ... $pattern_length, Warning - duplicate pattern: $wrapped (duplicate-pattern)\n";
102
1
2
        $_ = '(?:\$^ - skipped because duplicate-pattern on $line_number)';
103      } else {
104
12
14
        push @patterns, $_;
105
12
13
        $hints{$_} = $hint;
106      }
107
13
20
      $hint = '';
108    }
109  }
110
111  return {
112
6
21
    patterns => \@patterns,
113    hints => \%hints,
114  };
115}
116
117sub file_to_list {
118
5
1140
  my ($re) = @_;
119
5
7
  my $lists = file_to_lists($re);
120
121
5
5
3
15
  return @{$lists->{'patterns'}};
122}
123
124sub list_to_re {
125
5
5
  my (@list) = @_;
126
5
11
11
3
8
10
  @list = map { my $quoted = quote_re($_); test_re($quoted) ? $quoted : '' } @list;
127
5
11
4
11
  @list = grep { $_ ne '' } @list;
128
5
4
  return '$^' unless scalar @list;
129
5
13
  return join "|", (@list);
130}
131
132sub not_empty {
133
78
58
  my ($thing) = @_;
134
78
222
  return defined $thing && $thing ne ''
135}
136
137sub parse_block_list {
138
3
1
  my ($re) = @_;
139
3
3
  my @file;
140
3
22
  return @file unless (open(FILE, '<:utf8', $re));
141
142
3
5
  local $/=undef;
143
3
17
  my $file=<FILE>;
144
3
4
  my $last_line = $.;
145
3
8
  close FILE;
146
3
8
  for (split /\R/, $file) {
147
8
11
    next if /^#/;
148
5
3
    chomp;
149
5
4
    s/^\\#/#/;
150
5
6
    next unless /^./;
151
5
5
    push @file, $_;
152  }
153
154
3
4
  my $pairs = (0+@file) / 2;
155
3
3
  my $true_pairs = $pairs | 0;
156
3
2
  unless ($pairs == $true_pairs) {
157
1
1
    my $early_warnings = CheckSpelling::Util::get_file_from_env('early_warnings', '/dev/null');
158
1
1
1
1
2
1
2
13
    open EARLY_WARNINGS, ">>:encoding(UTF-8)", $early_warnings;
159
1
374
    print EARLY_WARNINGS "$re:$last_line:Block delimiters must come in pairs (uneven-block-delimiters)\n";
160
1
22
    close EARLY_WARNINGS;
161
1
1
    my $i = 0;
162
1
2
    while ($i < $true_pairs) {
163
0
0
      print STDERR "block-delimiter $i S: $file[$i*2]\n";
164
0
0
      print STDERR "block-delimiter $i E: $file[$i*2+1]\n";
165
0
0
      $i++;
166    }
167
1
9
    print STDERR "block-delimiter unmatched S: `$file[$i*2]`\n";
168
1
2
    @file = ();
169  }
170
171
3
7
  return @file;
172}
173
174sub valid_word {
175  # shortest_word is an absolute
176
28
7
  our ($shortest, $longest, $shortest_word, $longest_word);
177
28
25
  $shortest = $shortest_word if $shortest_word;
178
28
25
  if ($longest_word) {
179    # longest_word is an absolute
180
26
21
    $longest = $longest_word;
181  } elsif (not_empty($longest)) {
182    # we allow for some sloppiness (a couple of stuck keys per word)
183    # it's possible that this should scale with word length
184
1
1
    $longest += 2;
185  }
186
28
14
  our ($upper_pattern, $lower_pattern, $punctuation_pattern);
187
28
84
25
179
  my $word_pattern = join '|', (grep { defined $_ && /./ } ($upper_pattern, $lower_pattern, $punctuation_pattern));
188
28
22
  $word_pattern = q<\\w|'> unless $word_pattern;
189
28
55
  if ((defined $shortest && not_empty($longest)) &&
190      ($shortest > $longest)) {
191
0
0
    $word_pattern = "(?:$word_pattern){3}";
192
0
0
    return qr/$word_pattern/;
193  }
194
28
28
  $shortest = 3 unless defined $shortest;
195
28
27
  $longest = '' unless defined $longest;
196
28
98
  $word_match = "(?:$word_pattern){$shortest,$longest}";
197
28
196
  return qr/\b$word_match\b/;
198}
199
200sub load_dictionary {
201
15
1970
  my ($dict) = @_;
202
15
9
  our ($word_match, $longest, $shortest, $longest_word, $shortest_word, %dictionary);
203
15
12
  $longest_word = CheckSpelling::Util::get_val_from_env('INPUT_LONGEST_WORD', undef);
204
15
12
  $shortest_word = CheckSpelling::Util::get_val_from_env('INPUT_SHORTEST_WORD', undef);
205
15
7
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
206
15
11
  $ignore_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_IGNORE_PATTERN', q<[^a-zA-Z']>);
207
15
48
  $upper_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_UPPER_PATTERN', '[A-Z]');
208
15
31
  $lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_LOWER_PATTERN', '[a-z]');
209
15
28
  $not_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_LOWER_PATTERN', '[^a-z]');
210
15
42
  $not_upper_or_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_UPPER_OR_LOWER_PATTERN', '[^A-Za-z]');
211
15
29
  $punctuation_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_PUNCTUATION_PATTERN', q<'>);
212
15
33
  %dictionary = ();
213
214
15
536
  open(DICT, '<:utf8', $dict);
215
15
84
  while (!eof(DICT)) {
216
52
54
    my $word = <DICT>;
217
52
39
    chomp $word;
218
52
123
    next unless $word =~ $word_match;
219
49
52
    my $l = length $word;
220
49
34
    $longest = -1 unless not_empty($longest);
221
49
46
    $longest = $l if $l > $longest;
222
49
40
    $shortest = $l if $l < $shortest;
223
49
92
    $dictionary{$word}=1;
224  }
225
15
30
  close DICT;
226
227
15
14
  $word_match = valid_word();
228}
229
230sub hunspell_dictionary {
231
3
3
  my ($dict) = @_;
232
3
3
  my $name = $dict;
233
3
3
  $name =~ s{/src/index/hunspell/index\.dic$}{};
234
3
13
  $name =~ s{.*/}{};
235
3
0
  my $aff = $dict;
236
3
3
  my $encoding;
237
3
5
  $aff =~ s/\.dic$/.aff/;
238
3
27
  if (open AFF, '<', $aff) {
239
3
19
    while (<AFF>) {
240
0
0
      next unless /^SET\s+(\S+)/;
241
0
0
      $encoding = $1 if ($1 !~ /utf-8/i);
242
0
0
      last;
243    }
244
3
10
    close AFF;
245  }
246  return {
247
3
270
    name => $name,
248    dict => $dict,
249    aff => $aff,
250    encoding => $encoding,
251    engine => Text::Hunspell->new($aff, $dict),
252  }
253}
254
255sub init {
256
12
14671
  my ($configuration) = @_;
257
12
13
  our ($word_match, %unique, $patterns_re, @forbidden_re_list, $forbidden_re, @candidates_re_list, $candidates_re);
258
12
7
  our ($begin_block_re, @begin_block_list, @end_block_list);
259
12
24
  our $sandbox = CheckSpelling::Util::get_file_from_env('sandbox', '');
260
12
9
  our $hunspell_dictionary_path = CheckSpelling::Util::get_file_from_env('hunspell_dictionary_path', '');
261
12
16
  our $timeout = CheckSpelling::Util::get_val_from_env('splitter_timeout', 30);
262
12
3
  our %forbidden_re_descriptions;
263
12
13
  if ($hunspell_dictionary_path) {
264
3
27
    our @hunspell_dictionaries = ();
265
1
1
1
1
1
1
1
1
1
3
220
1025
22
3
2
14
6
1
17
140
    if (eval 'use Text::Hunspell; 1') {
266
3
104
      my @hunspell_dictionaries_list = glob("$hunspell_dictionary_path/*.dic");
267
3
5
      for my $hunspell_dictionary_file (@hunspell_dictionaries_list) {
268
3
3
        push @hunspell_dictionaries, hunspell_dictionary($hunspell_dictionary_file);
269      }
270    } else {
271
0
0
      print STDERR "Could not load Text::Hunspell for dictionaries (hunspell-unavailable)\n";
272    }
273  }
274
275
12
105
  if (-e "$configuration/block-delimiters.list") {
276
3
3
    my @block_delimiters = parse_block_list "$configuration/block-delimiters.list";
277
3
4
    if (@block_delimiters) {
278
2
1
      @begin_block_list = ();
279
2
1
      @end_block_list = ();
280
281
2
2
      while (@block_delimiters) {
282
2
2
        my ($begin, $end) = splice @block_delimiters, 0, 2;
283
2
2
        push @begin_block_list, $begin;
284
2
3
        push @end_block_list, $end;
285      }
286
287
2
2
2
2
      $begin_block_re = join '|', (map { '('.quote_re("\Q$_\E").')' } @begin_block_list);
288    }
289  }
290
291
12
12
  my (@patterns_re_list, %in_patterns_re_list);
292
12
47
  if (-e "$configuration/patterns.txt") {
293
0
0
    @patterns_re_list = file_to_list "$configuration/patterns.txt";
294
0
0
    $patterns_re = list_to_re @patterns_re_list;
295
0
0
0
0
    %in_patterns_re_list = map {$_ => 1} @patterns_re_list;
296  } else {
297
12
10
    $patterns_re = undef;
298  }
299
300
12
42
  if (-e "$configuration/forbidden.txt") {
301
1
1
    my $forbidden_re_info = file_to_lists "$configuration/forbidden.txt";
302
1
1
1
2
    @forbidden_re_list = @{$forbidden_re_info->{'patterns'}};
303
1
1
0
3
    %forbidden_re_descriptions = %{$forbidden_re_info->{'hints'}};
304
1
1
    $forbidden_re = list_to_re @forbidden_re_list;
305  } else {
306
11
10
    $forbidden_re = undef;
307  }
308
309
12
41
  if (-e "$configuration/candidates.txt") {
310
4
5
    @candidates_re_list = file_to_list "$configuration/candidates.txt";
311
4
8
8
4
6
29
    @candidates_re_list = map { my $quoted = quote_re($_); $in_patterns_re_list{$_} || !test_re($quoted) ? '' : $quoted } @candidates_re_list;
312
4
5
    $candidates_re = list_to_re @candidates_re_list;
313  } else {
314
8
8
    $candidates_re = undef;
315  }
316
317
12
19
  our $largest_file = CheckSpelling::Util::get_val_from_env('INPUT_LARGEST_FILE', 1024*1024);
318
319
12
12
  my $disable_flags = CheckSpelling::Util::get_file_from_env('INPUT_DISABLE_CHECKS', '');
320
12
12
  our $disable_word_collating = $disable_flags =~ /(?:^|,|\s)word-collating(?:,|\s|$)/;
321
12
11
  our $disable_minified_file = $disable_flags =~ /(?:^|,|\s)minified-file(?:,|\s|$)/;
322
12
2
  our $disable_single_line_file = $disable_flags =~ /(?:^|,|\s)single-line-file(?:,|\s|$)/;
323
324
12
11
  our $ignore_next_line_pattern = CheckSpelling::Util::get_file_from_env('INPUT_IGNORE_NEXT_LINE', '');
325
12
9
  $ignore_next_line_pattern =~ s/\s+/|/g;
326
327
12
11
  our $check_file_names = CheckSpelling::Util::get_file_from_env('check_file_names', '');
328
329
12
10
  our $use_magic_file = CheckSpelling::Util::get_val_from_env('INPUT_USE_MAGIC_FILE', '');
330
331
12
16
  $word_match = valid_word();
332
333
12
17
  our $base_dict = CheckSpelling::Util::get_file_from_env('dict', "$configuration/words");
334
12
52
  $base_dict = '/usr/share/dict/words' unless -e $base_dict;
335
12
11
  load_dictionary($base_dict);
336}
337
338sub split_line {
339
1160
481
  our (%dictionary, $word_match, $disable_word_collating);
340
1160
411
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
341
1160
565
  our @hunspell_dictionaries;
342
1160
514
  our $shortest;
343
1160
739
  my $shortest_threshold = $shortest + 2;
344
1160
551
  my $pattern = '.';
345  # $pattern = "(?:$upper_pattern){$shortest,}|$upper_pattern(?:$lower_pattern){2,}\n";
346
347  # https://www.fileformat.info/info/unicode/char/2019/
348
1160
578
  my $rsqm = "\xE2\x80\x99";
349
350
1160
664
  my ($words, $unrecognized) = (0, 0);
351
1160
785
  my ($line, $unique_ref, $unique_unrecognized_ref, $unrecognized_line_items_ref) = @_;
352
1160
5612
    $line =~ s/(?:$rsqm|&apos;|&#39;|\%27|&#8217;|&#x2019;|&rsquo;|\\u2019|\x{2019}|')+/'/g;
353
1160
2260
    $line =~ s/(?:$ignore_pattern)+/ /g;
354
1160
1667
    while ($line =~ s/($upper_pattern{2,})($upper_pattern$lower_pattern{2,})/ $1 $2 /g) {}
355
1160
3399
    while ($line =~ s/((?:$lower_pattern|$punctuation_pattern)+)($upper_pattern)/$1 $2/g) {}
356
1160
1309
    for my $token (split /\s+/, $line) {
357
3642
3259
      next unless $token =~ /$pattern/;
358
2483
2106
      $token =~ s/^(?:'|$rsqm)+//g;
359
2483
2501
      $token =~ s/(?:'|$rsqm)+s?$//g;
360
2483
1412
      my $raw_token = $token;
361
2483
1509
      $token =~ s/^[^Ii]?'+(.*)/$1/;
362
2483
1245
      $token =~ s/(.*?)'+$/$1/;
363
2483
3779
      next unless $token =~ $word_match;
364
2318
2146
      if (defined $dictionary{$token}) {
365
1038
462
        ++$words;
366
1038
559
        $unique_ref->{$token}=1;
367
1038
876
        next;
368      }
369
1280
966
      if (@hunspell_dictionaries) {
370
1254
600
        my $found = 0;
371
1254
746
        for my $hunspell_dictionary (@hunspell_dictionaries) {
372          my $token_encoded = defined $hunspell_dictionary->{'encoding'} ?
373
1254
1063
            encode($hunspell_dictionary->{'encoding'}, $token) : $token;
374
1254
2763
          next unless ($hunspell_dictionary->{'engine'}->check($token_encoded));
375
0
0
          ++$words;
376
0
0
          $dictionary{$token} = 1;
377
0
0
          $unique_ref->{$token}=1;
378
0
0
          $found = 1;
379
0
0
          last;
380        }
381
1254
891
        next if $found;
382      }
383
1280
927
      my $key = lc $token;
384
1280
1161
      if (defined $dictionary{$key}) {
385
6
3
        ++$words;
386
6
4
        $unique_ref->{$key}=1;
387
6
9
        next;
388      }
389
1274
901
      unless ($disable_word_collating) {
390
1274
690
        $key =~ s/''+/'/g;
391
1274
1331
        $key =~ s/'[sd]$// unless length $key >= $shortest_threshold;
392      }
393
1274
1098
      if (defined $dictionary{$key}) {
394
0
0
        ++$words;
395
0
0
        $unique_ref->{$key}=1;
396
0
0
        next;
397      }
398
1274
682
      ++$unrecognized;
399
1274
787
      $unique_unrecognized_ref->{$raw_token}=1;
400
1274
1803
      $unrecognized_line_items_ref->{$raw_token}=1;
401    }
402
1160
1613
    return ($words, $unrecognized);
403}
404
405sub skip_file {
406
7
19
  my ($temp_dir, $reason) = @_;
407
7
190
  open(SKIPPED, '>:utf8', "$temp_dir/skipped");
408
7
34
  print SKIPPED $reason;
409
7
81
  close SKIPPED;
410}
411
412sub split_file {
413
18
11117
  my ($file) = @_;
414  our (
415
18
11
    $unrecognized, $shortest, $largest_file, $words,
416    $word_match, %unique, %unique_unrecognized, $forbidden_re,
417    @forbidden_re_list, $patterns_re, %dictionary,
418    $begin_block_re, @begin_block_list, @end_block_list,
419    $candidates_re, @candidates_re_list, $check_file_names, $use_magic_file, $disable_minified_file,
420    $disable_single_line_file,
421    $ignore_next_line_pattern,
422    $sandbox,
423  );
424
18
30
  $ignore_next_line_pattern = '$^' unless $ignore_next_line_pattern =~ /./;
425
426
18
8
  our %forbidden_re_descriptions;
427
18
9
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
428
429  # https://www.fileformat.info/info/unicode/char/2019/
430
18
7
  my $rsqm = "\xE2\x80\x99";
431
432
18
18
  my @candidates_re_hits = (0) x scalar @candidates_re_list;
433
18
11
  my @candidates_re_lines = (0) x scalar @candidates_re_list;
434
18
11
  my @forbidden_re_hits = (0) x scalar @forbidden_re_list;
435
18
11
  my @forbidden_re_lines = (0) x scalar @forbidden_re_list;
436
18
27
  my $temp_dir = tempdir(DIR=>$sandbox);
437
18
2576
  print STDERR "checking file: $file\n" if defined $ENV{'DEBUG'};
438
18
395
  open(NAME, '>', "$temp_dir/name");
439
18
40
    print NAME $file;
440
18
193
  close NAME;
441
18
61
  my $file_size = -s $file;
442
18
17
  if (defined $largest_file) {
443
18
14
    unless ($check_file_names eq $file) {
444
18
20
      if ($file_size > $largest_file) {
445
1
2
        skip_file($temp_dir, "size `$file_size` exceeds limit `$largest_file` (large-file)\n");
446
1
2
        return $temp_dir;
447      }
448    }
449  }
450
17
149
  if (defined readlink($file) &&
451      rindex(File::Spec->abs2rel(abs_path($file)), '../', 0) == 0) {
452
1
13
    skip_file($temp_dir, "file only has a single line (out-of-bounds-symbolic-link)\n");
453
1
5
    return $temp_dir;
454  }
455
16
15
  if ($use_magic_file) {
456
8
10973
    if (open(my $file_fh, '-|',
457              '/usr/bin/file',
458              '-b',
459              '--mime',
460              '-e', 'cdf',
461              '-e', 'compress',
462              '-e', 'csv',
463              '-e', 'elf',
464              '-e', 'json',
465              '-e', 'tar',
466              $file)) {
467
8
27598
      my $file_kind = <$file_fh>;
468
8
4770
      close $file_fh;
469
8
98
      if ($file_kind =~ /^(.*?); charset=binary/) {
470
2
25
        skip_file($temp_dir, "it appears to be a binary file (`$1`) (binary-file)\n");
471
2
46
        return $temp_dir;
472      }
473    }
474  }
475
14
118
  open FILE, '<', $file;
476
14
12
  binmode FILE;
477
14
4
  my $head;
478
14
102
  read(FILE, $head, 4096);
479
14
880
  $head =~ s/(?:\r|\n)+$//;
480
14
49
  my $dos_new_lines = () = $head =~ /\r\n/gi;
481
14
36
  my $unix_new_lines = () = $head =~ /\n/gi;
482
14
103
  my $mac_new_lines = () = $head =~ /\r/gi;
483
14
57
  local $/;
484
14
61
  if ($unix_new_lines == 0 && $mac_new_lines == 0) {
485
3
9
    $/ = "\n";
486  } elsif ($dos_new_lines >= $unix_new_lines && $dos_new_lines >= $mac_new_lines) {
487
1
5
    $/ = "\r\n";
488  } elsif ($mac_new_lines > $unix_new_lines) {
489
2
2
    $/ = "\r";
490  } else {
491
8
10
    $/ = "\n";
492  }
493
14
25
  seek(FILE, 0, 0);
494
14
20
  ($words, $unrecognized) = (0, 0);
495
14
27
  %unique = ();
496
14
24
  %unique_unrecognized = ();
497
498  local $SIG{__WARN__} = sub {
499
0
0
    my $message = shift;
500
0
0
    $message =~ s/> line/> in $file - line/;
501
0
0
    chomp $message;
502
0
0
    print STDERR "$message\n";
503
14
108
  };
504
505
14
361
  open(WARNINGS, '>:utf8', "$temp_dir/warnings");
506
14
8
  our $timeout;
507
14
12
  eval {
508
14
0
84
0
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
509
14
31
    alarm $timeout;
510
511
14
15
    my $ignore_next_line = 0;
512
14
29
    my ($current_begin_marker, $next_end_marker, $start_marker_line) = ('', '', '');
513
14
9
    my $offset = 0;
514
14
91
    LINE: while (<FILE>) {
515
1169
1008
      if ($. == 1) {
516
14
15
        unless ($disable_minified_file) {
517
14
53
          if ($file_size >= 512 && length($_) == $file_size) {
518
1
7
            skip_file($temp_dir, "file only has a single line (single-line-file)\n");
519
1
4
            last;
520          }
521        }
522      }
523
1168
2462
      $_ = decode_utf8($_, FB_DEFAULT);
524
1168
2809
      if (/[\x{D800}-\x{DFFF}]/) {
525
0
0
        skip_file($temp_dir, "file contains a UTF-16 surrogate -- UTF-16 surrogates are not supported (utf16-surrogate-file)\n");
526
0
0
        last;
527      }
528
1168
1527
      s/\R$//;
529
1168
1042
      s/^\x{FEFF}// if $. == 1;
530
1168
1109
      next unless /./;
531
1167
772
      my $raw_line = $_;
532
1167
588
      my $parsed_block_markers;
533
534      # hook for custom multiline based text exclusions:
535
1167
835
      if ($begin_block_re) {
536
1148
549
        FIND_END_MARKER: while (1) {
537
1150
889
          while ($next_end_marker ne '') {
538
6
25
            next LINE unless /\Q$next_end_marker\E/;
539
1
5
            s/.*?\Q$next_end_marker\E//;
540
1
2
            ($current_begin_marker, $next_end_marker, $start_marker_line) = ('', '', '');
541
1
1
            $parsed_block_markers = 1;
542          }
543
1145
1147
          my @captured = (/^.*?$begin_block_re/);
544
1145
982
          last unless (@captured);
545
2
3
          for my $capture (0 .. $#captured) {
546
2
2
            if ($captured[$capture]) {
547
2
4
              ($current_begin_marker, $next_end_marker, $start_marker_line) = ($begin_block_list[$capture], $end_block_list[$capture], "$.:1 ... 1");
548
2
11
              s/^.*?\Q$begin_block_list[$capture]\E//;
549
2
2
              $parsed_block_markers = 1;
550
2
3
              next FIND_END_MARKER;
551            }
552          }
553        }
554
1143
769
        next if $parsed_block_markers;
555      }
556
557
1161
597
      my $ignore_this_line = $ignore_next_line;
558
1161
989
      $ignore_next_line = ($_ =~ /$ignore_next_line_pattern/);
559
1161
669
      next if $ignore_this_line;
560
561      # hook for custom line based text exclusions:
562
1160
732
      if (defined $patterns_re) {
563
2
6
11
8
        s/($patterns_re)/"="x length($1)/ge;
564      }
565
1160
638
      my $initial_line_state = $_;
566
1160
651
      my $previous_line_state = $_;
567
1160
567
      my $line_flagged;
568
1160
727
      if ($forbidden_re) {
569
9
5
59
12
        while (s/($forbidden_re)/"="x length($1)/e) {
570
5
2
          $line_flagged = 1;
571
5
10
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
572
5
3
          my $found_trigger_re;
573
5
6
          for my $i (0 .. $#forbidden_re_list) {
574
7
5
            my $forbidden_re_singleton = $forbidden_re_list[$i];
575
7
4
            my $test_line = $previous_line_state;
576
7
4
57
7
            if ($test_line =~ s/($forbidden_re_singleton)/"="x length($1)/e) {
577
4
4
              next unless $test_line eq $_;
578
4
8
              my ($begin_test, $end_test, $match_test) = ($-[0] + 1, $+[0] + 1, $1);
579
4
3
              next unless $begin == $begin_test;
580
4
5
              next unless $end == $end_test;
581
4
5
              next unless $match eq $match_test;
582
4
3
              $found_trigger_re = $forbidden_re_singleton;
583
4
8
              my $hit = "$.:$begin:$end";
584
4
2
              $forbidden_re_hits[$i]++;
585
4
7
              $forbidden_re_lines[$i] = $hit unless $forbidden_re_lines[$i];
586
4
5
              last;
587            }
588          }
589
5
5
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
590
5
5
          if ($found_trigger_re) {
591
4
8
            my $description = $forbidden_re_descriptions{$found_trigger_re} || '';
592
4
9
            $found_trigger_re =~ s/^\(\?:(.*)\)$/$1/;
593
4
4
            my $quoted_trigger_re = CheckSpelling::Util::truncate_with_ellipsis(CheckSpelling::Util::wrap_in_backticks($found_trigger_re), 99);
594
4
3
            if ($description ne '') {
595
3
14
              print WARNINGS ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns rule: $description - $quoted_trigger_re (forbidden-pattern)\n";
596            } else {
597
1
6
              print WARNINGS ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns entry: $quoted_trigger_re (forbidden-pattern)\n";
598            }
599          } else {
600
1
3
            print WARNINGS ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns entry (forbidden-pattern)\n";
601          }
602
5
26
          $previous_line_state = $_;
603        }
604
9
8
        $_ = $initial_line_state;
605      }
606      # This is to make it easier to deal w/ rules:
607
1160
1147
      s/^/ /;
608
1160
737
      my %unrecognized_line_items = ();
609
1160
910
      my ($new_words, $new_unrecognized) = split_line($_, \%unique, \%unique_unrecognized, \%unrecognized_line_items);
610
1160
646
      $words += $new_words;
611
1160
484
      $unrecognized += $new_unrecognized;
612
1160
845
      my $line_length = length($raw_line);
613
1160
1527
      for my $token (sort CheckSpelling::Util::case_biased keys %unrecognized_line_items) {
614
1021
506
        my $found_token = 0;
615
1021
454
        my $raw_token = $token;
616
1021
575
        $token =~ s/'/(?:'|\x{2019}|\&apos;|\&#39;)+/g;
617
1021
427
        my $before;
618
1021
1497
        if ($token =~ /^$upper_pattern$lower_pattern/) {
619
5
3
          $before = '(?<=.)';
620        } elsif ($token =~ /^$upper_pattern/) {
621
0
0
          $before = "(?<!$upper_pattern)";
622        } else {
623
1016
591
          $before = "(?<=$not_lower_pattern)";
624        }
625
1021
1168
        my $after = ($token =~ /$upper_pattern$/) ? "(?=$not_upper_or_lower_pattern)|(?=$upper_pattern$lower_pattern)" : "(?=$not_lower_pattern)";
626
1021
2143
        while ($raw_line =~ /(?:\b|$before)($token)(?:\b|$after)/g) {
627
1271
641
          $line_flagged = 1;
628
1271
565
          $found_token = 1;
629
1271
1680
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
630
1271
1114
          next unless $match =~ /./;
631
1271
921
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
632
1271
4803
          print WARNINGS ":$.:$begin ... $end: $wrapped\n";
633        }
634
1021
1136
        unless ($found_token) {
635
3
28
          if ($raw_line !~ /$token.*$token/ && $raw_line =~ /($token)/) {
636
3
6
            my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
637
3
2
            my $wrapped = CheckSpelling::Util::wrap_in_backticks($raw_token);
638
3
11
            print WARNINGS ":$.:$begin ... $end: $wrapped\n";
639          } else {
640
0
0
            my $offset = $line_length + 1;
641
0
0
            my $wrapped = CheckSpelling::Util::wrap_in_backticks($raw_token);
642
0
0
            print WARNINGS ":$.:1 ... $offset, Warning - Could not identify whole word $wrapped in line (token-is-substring)\n";
643          }
644        }
645      }
646
1160
1865
      if ($line_flagged && $candidates_re) {
647
2
2
        $_ = $previous_line_state = $initial_line_state;
648
2
2
20
4
        s/($candidates_re)/"="x length($1)/ge;
649
2
3
        if ($_ ne $initial_line_state) {
650
2
1
          $_ = $previous_line_state;
651
2
2
          for my $i (0 .. $#candidates_re_list) {
652
4
4
            my $candidate_re = $candidates_re_list[$i];
653
4
58
            next unless $candidate_re =~ /./ && $raw_line =~ /$candidate_re/;
654
2
2
14
7
            if (($_ =~ s/($candidate_re)/"="x length($1)/e)) {
655
2
4
              my ($begin, $end) = ($-[0] + 1, $+[0] + 1);
656
2
5
              my $hit = "$.:$begin:$end";
657
2
2
              $_ = $previous_line_state;
658
2
2
6
4
              my $replacements = ($_ =~ s/($candidate_re)/"="x length($1)/ge);
659
2
2
              $candidates_re_hits[$i] += $replacements;
660
2
3
              $candidates_re_lines[$i] = $hit unless $candidates_re_lines[$i];
661
2
5
              $_ = $previous_line_state;
662            }
663          }
664        }
665      }
666
1160
869
      unless ($disable_minified_file) {
667
1160
883
        s/={3,}//g;
668
1160
824
        $offset += length;
669
1160
1071
        my $ratio = int($offset / $.);
670
1160
655
        my $ratio_threshold = 1000;
671
1160
3268
        if ($ratio > $ratio_threshold) {
672
2
7
          skip_file($temp_dir, "average line width ($ratio) exceeds the threshold ($ratio_threshold) (minified-file)\n");
673
2
7
          last;
674        }
675      }
676    }
677
14
14
    if ($next_end_marker) {
678
1
2
      if ($start_marker_line) {
679
1
1
        my $wrapped = CheckSpelling::Util::wrap_in_backticks($current_begin_marker);
680
1
7
        print WARNINGS ":$start_marker_line, Warning - Failed to find matching end marker for $wrapped (unclosed-block-ignore-begin)\n";
681      }
682
1
2
      my $wrapped = CheckSpelling::Util::wrap_in_backticks($next_end_marker);
683
1
3
      print WARNINGS ":$.:1 ... 1, Warning - Expected to find end block marker $wrapped (unclosed-block-ignore-end)\n";
684    }
685
686
14
85
    alarm 0;
687  };
688
14
12
  if ($@) {
689
0
0
    die unless $@ eq "alarm\n";
690
0
0
    print WARNINGS ":$.:1 ... 1, Warning - Could not parse file within time limit (slow-file)\n";
691
0
0
    skip_file($temp_dir, "it could not be parsed file within time limit (slow-file)\n");
692
0
0
    last;
693  }
694
695
14
36
  close FILE;
696
14
154
  close WARNINGS;
697
698
14
47
  if ($unrecognized || @candidates_re_hits || @forbidden_re_hits) {
699
13
323
    open(STATS, '>:utf8', "$temp_dir/stats");
700
13
163
      print STATS "{words: $words, unrecognized: $unrecognized, unknown: ".(keys %unique_unrecognized).
701      ", unique: ".(keys %unique).
702      (@candidates_re_hits ? ", candidates: [".(join ',', @candidates_re_hits)."]" : "").
703      (@candidates_re_lines ? ", candidate_lines: [".(join ',', @candidates_re_lines)."]" : "").
704      (@forbidden_re_hits ? ", forbidden: [".(join ',', @forbidden_re_hits)."]" : "").
705      (@forbidden_re_lines ? ", forbidden_lines: [".(join ',', @forbidden_re_lines)."]" : "").
706      "}";
707
13
134
    close STATS;
708
13
277
    open(UNKNOWN, '>:utf8', "$temp_dir/unknown");
709
13
20
39
35
      print UNKNOWN map { "$_\n" } sort CheckSpelling::Util::case_biased keys %unique_unrecognized;
710
13
99
    close UNKNOWN;
711  }
712
713
14
118
  return $temp_dir;
714}
715
716sub main {
717
4
371
  my ($configuration, @ARGV) = @_;
718
4
2
  our %dictionary;
719
4
4
  unless (%dictionary) {
720
1
3
    init($configuration);
721  }
722
723  # read all input
724
4
7
  my @reports;
725
726
4
3
  for my $file (@ARGV) {
727
4
3
    my $temp_dir = split_file($file);
728
4
7
    push @reports, "$temp_dir\n";
729  }
730
4
10
  print join '', @reports;
731}
732
7331;