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
117446
4
use 5.022;
11
1
1
1
2
3
56
use feature 'unicode_strings';
12
1
1
1
2
2
13
use strict;
13
1
1
1
1
1
28
use warnings;
14
1
1
1
1
1
18
no warnings qw(experimental::vlb);
15
1
1
1
2
0
3
use utf8;
16
1
1
1
14
1
37
use Encode qw/decode_utf8 encode FB_DEFAULT/;
17
1
1
1
2
0
33
use File::Basename;
18
1
1
1
2
1
18
use Cwd 'abs_path';
19
1
1
1
2
0
22
use File::Spec;
20
1
1
1
1
1
23
use File::Temp qw/ tempfile tempdir /;
21
1
1
1
362
1
3846
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
24
  my ($expression) = @_;
46
32
32
12
225
  return eval { qr /$expression/ };
47}
48
49sub quote_re {
50
34
27
  my ($expression) = @_;
51
34
33
  return $expression if $expression =~ /\?\{/;
52
34
71
  $expression =~ s/
53   \G
54   (
55      (?:[^\\]|\\[^Q])*
56   )
57   (?:
58      \\Q
59      (?:[^\\]|\\[^E])*
60      (?:\\E)?
61   )?
62/
63
68
111
   $1 . (defined($2) ? quotemeta($2) : '')
64/xge;
65
34
43
  return $expression;
66}
67
68sub file_to_lists {
69
6
10
  my ($re) = @_;
70
6
8
  my @patterns;
71  my %hints;
72
6
0
  my $fh;
73
6
72
  if (open($fh, '<:utf8', $re)) {
74
6
10
    local $/=undef;
75
6
39
    my $file=<$fh>;
76
6
17
    close $fh;
77
6
5
    my $line_number = 0;
78
6
6
    my $hint = '';
79
6
27
    for (split /\R/, $file) {
80
32
23
      ++$line_number;
81
32
13
      chomp;
82
32
47
      if (/^#(?:\s(.+)|)/) {
83
12
31
        $hint = $1 if ($hint eq '' && defined $1);
84
12
10
        next;
85      }
86
20
21
      $hint = '' unless $_ ne '';
87
20
19
      my $pattern = $_;
88
20
49
      next unless s/^(.+)/(?:$1)/;
89
13
19
      my $quoted = quote_re($1);
90
13
15
      unless (test_re $quoted) {
91
1
1
        my $error = $@;
92
1
46
        my $home = dirname(__FILE__);
93
1
28
        $error =~ s/$home.*?\.pm line \d+\./$re line $line_number (bad-regex)/;
94
1
14
        print STDERR $error;
95
1
1
        $_ = '(?:\$^ - skipped because bad-regex)';
96
1
2
        $hint = '';
97      }
98
13
17
      if (defined $hints{$_}) {
99
1
2
        my $pattern_length = length $pattern;
100
1
2
        my $wrapped = CheckSpelling::Util::wrap_in_backticks($pattern);
101
1
15
        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
13
        push @patterns, $_;
105
12
16
        $hints{$_} = $hint;
106      }
107
13
21
      $hint = '';
108    }
109  }
110
111  return {
112
6
25
    patterns => \@patterns,
113    hints => \%hints,
114  };
115}
116
117sub file_to_list {
118
5
1422
  my ($re) = @_;
119
5
11
  my $lists = file_to_lists($re);
120
121
5
5
4
18
  return @{$lists->{'patterns'}};
122}
123
124sub list_to_re {
125
5
7
  my (@list) = @_;
126
5
11
11
5
8
8
  @list = map { my $quoted = quote_re($_); test_re($quoted) ? $quoted : '' } @list;
127
5
11
5
12
  @list = grep { $_ ne '' } @list;
128
5
5
  return '$^' unless scalar @list;
129
5
15
  return join "|", (@list);
130}
131
132sub not_empty {
133
78
71
  my ($thing) = @_;
134
78
264
  return defined $thing && $thing ne ''
135}
136
137sub parse_block_list {
138
3
3
  my ($re) = @_;
139
3
3
  my @file;
140
3
28
  return @file unless (open(FILE, '<:utf8', $re));
141
142
3
6
  local $/=undef;
143
3
22
  my $file=<FILE>;
144
3
5
  my $last_line = $.;
145
3
7
  close FILE;
146
3
12
  for (split /\R/, $file) {
147
8
15
    next if /^#/;
148
5
4
    chomp;
149
5
7
    s/^\\#/#/;
150
5
8
    next unless /^./;
151
5
7
    push @file, $_;
152  }
153
154
3
6
  my $pairs = (0+@file) / 2;
155
3
5
  my $true_pairs = $pairs | 0;
156
3
3
  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
4
1
3
19
    open EARLY_WARNINGS, ">>:encoding(UTF-8)", $early_warnings;
159
1
512
    print EARLY_WARNINGS "$re:$last_line:Block delimiters must come in pairs (uneven-block-delimiters)\n";
160
1
51
    close EARLY_WARNINGS;
161
1
2
    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
11
    print STDERR "block-delimiter unmatched S: `$file[$i*2]`\n";
168
1
2
    @file = ();
169  }
170
171
3
9
  return @file;
172}
173
174sub valid_word {
175  # shortest_word is an absolute
176
28
15
  our ($shortest, $longest, $shortest_word, $longest_word);
177
28
35
  $shortest = $shortest_word if $shortest_word;
178
28
35
  if ($longest_word) {
179    # longest_word is an absolute
180
26
28
    $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
21
  our ($upper_pattern, $lower_pattern, $punctuation_pattern);
187
28
84
32
197
  my $word_pattern = join '|', (grep { defined $_ && /./ } ($upper_pattern, $lower_pattern, $punctuation_pattern));
188
28
27
  $word_pattern = q<\\w|'> unless $word_pattern;
189
28
59
  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
38
  $shortest = 3 unless defined $shortest;
195
28
32
  $longest = '' unless defined $longest;
196
28
104
  $word_match = "(?:$word_pattern){$shortest,$longest}";
197
28
215
  return qr/\b$word_match\b/;
198}
199
200sub load_dictionary {
201
15
2017
  my ($dict) = @_;
202
15
10
  our ($word_match, $longest, $shortest, $longest_word, $shortest_word, %dictionary);
203
15
16
  $longest_word = CheckSpelling::Util::get_val_from_env('INPUT_LONGEST_WORD', undef);
204
15
16
  $shortest_word = CheckSpelling::Util::get_val_from_env('INPUT_SHORTEST_WORD', undef);
205
15
12
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
206
15
20
  $ignore_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_IGNORE_PATTERN', q<[^a-zA-Z']>);
207
15
57
  $upper_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_UPPER_PATTERN', '[A-Z]');
208
15
42
  $lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_LOWER_PATTERN', '[a-z]');
209
15
31
  $not_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_LOWER_PATTERN', '[^a-z]');
210
15
37
  $not_upper_or_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_UPPER_OR_LOWER_PATTERN', '[^A-Za-z]');
211
15
31
  $punctuation_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_PUNCTUATION_PATTERN', q<'>);
212
15
39
  %dictionary = ();
213
214
15
546
  open(DICT, '<:utf8', $dict);
215
15
72
  while (!eof(DICT)) {
216
52
57
    my $word = <DICT>;
217
52
41
    chomp $word;
218
52
124
    next unless $word =~ $word_match;
219
49
57
    my $l = length $word;
220
49
31
    $longest = -1 unless not_empty($longest);
221
49
46
    $longest = $l if $l > $longest;
222
49
47
    $shortest = $l if $l < $shortest;
223
49
96
    $dictionary{$word}=1;
224  }
225
15
35
  close DICT;
226
227
15
36
  $word_match = valid_word();
228}
229
230sub hunspell_dictionary {
231
3
6
  my ($dict) = @_;
232
3
3
  my $name = $dict;
233
3
6
  $name =~ s{/src/index/hunspell/index\.dic$}{};
234
3
14
  $name =~ s{.*/}{};
235
3
3
  my $aff = $dict;
236
3
3
  my $encoding;
237
3
8
  $aff =~ s/\.dic$/.aff/;
238
3
50
  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
8
    close AFF;
245  }
246  return {
247
3
354
    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
18639
  my ($configuration) = @_;
257
12
15
  our ($word_match, %unique, $patterns_re, @forbidden_re_list, $forbidden_re, @candidates_re_list, $candidates_re);
258
12
21
  our ($begin_block_re, @begin_block_list, @end_block_list);
259
12
33
  our $sandbox = CheckSpelling::Util::get_file_from_env('sandbox', '');
260
12
25
  our $hunspell_dictionary_path = CheckSpelling::Util::get_file_from_env('hunspell_dictionary_path', '');
261
12
34
  our $timeout = CheckSpelling::Util::get_val_from_env('splitter_timeout', 30);
262
12
8
  our %forbidden_re_descriptions;
263
12
23
  if ($hunspell_dictionary_path) {
264
3
42
    our @hunspell_dictionaries = ();
265
1
1
1
1
1
1
1
1
1
3
289
1052
21
5
1
15
7
1
26
207
    if (eval 'use Text::Hunspell; 1') {
266
3
131
      my @hunspell_dictionaries_list = glob("$hunspell_dictionary_path/*.dic");
267
3
7
      for my $hunspell_dictionary_file (@hunspell_dictionaries_list) {
268
3
14
        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
88
  if (-e "$configuration/block-delimiters.list") {
276
3
5
    my @block_delimiters = parse_block_list "$configuration/block-delimiters.list";
277
3
5
    if (@block_delimiters) {
278
2
2
      @begin_block_list = ();
279
2
2
      @end_block_list = ();
280
281
2
3
      while (@block_delimiters) {
282
2
4
        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
3
      $begin_block_re = join '|', (map { '('.quote_re("\Q$_\E").')' } @begin_block_list);
288    }
289  }
290
291
12
20
  my (@patterns_re_list, %in_patterns_re_list);
292
12
49
  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
12
    $patterns_re = undef;
298  }
299
300
12
48
  if (-e "$configuration/forbidden.txt") {
301
1
3
    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
1
4
    %forbidden_re_descriptions = %{$forbidden_re_info->{'hints'}};
304
1
1
    $forbidden_re = list_to_re @forbidden_re_list;
305  } else {
306
11
18
    $forbidden_re = undef;
307  }
308
309
12
54
  if (-e "$configuration/candidates.txt") {
310
4
34
    @candidates_re_list = file_to_list "$configuration/candidates.txt";
311
4
8
8
5
7
14
    @candidates_re_list = map { my $quoted = quote_re($_); $in_patterns_re_list{$_} || !test_re($quoted) ? '' : $quoted } @candidates_re_list;
312
4
6
    $candidates_re = list_to_re @candidates_re_list;
313  } else {
314
8
13
    $candidates_re = undef;
315  }
316
317
12
18
  our $largest_file = CheckSpelling::Util::get_val_from_env('INPUT_LARGEST_FILE', 1024*1024);
318
319
12
18
  my $disable_flags = CheckSpelling::Util::get_file_from_env('INPUT_DISABLE_CHECKS', '');
320
12
17
  our $disable_word_collating = $disable_flags =~ /(?:^|,|\s)word-collating(?:,|\s|$)/;
321
12
13
  our $disable_minified_file = $disable_flags =~ /(?:^|,|\s)minified-file(?:,|\s|$)/;
322
12
10
  our $disable_single_line_file = $disable_flags =~ /(?:^|,|\s)single-line-file(?:,|\s|$)/;
323
324
12
14
  our $ignore_next_line_pattern = CheckSpelling::Util::get_file_from_env('INPUT_IGNORE_NEXT_LINE', '');
325
12
11
  $ignore_next_line_pattern =~ s/\s+/|/g;
326
327
12
8
  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
19
  $word_match = valid_word();
332
333
12
27
  our $base_dict = CheckSpelling::Util::get_file_from_env('dict', "$configuration/words");
334
12
61
  $base_dict = '/usr/share/dict/words' unless -e $base_dict;
335
12
19
  load_dictionary($base_dict);
336}
337
338sub split_line {
339
1160
533
  our (%dictionary, $word_match, $disable_word_collating);
340
1160
461
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
341
1160
466
  our @hunspell_dictionaries;
342
1160
482
  our $shortest;
343
1160
813
  my $shortest_threshold = $shortest + 2;
344
1160
645
  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
590
  my $rsqm = "\xE2\x80\x99";
349
350
1160
641
  my ($words, $unrecognized) = (0, 0);
351
1160
761
  my ($line, $unique_ref, $unique_unrecognized_ref, $unrecognized_line_items_ref) = @_;
352
1160
5809
    $line =~ s/(?:$rsqm|&apos;|&#39;|\%27|&#8217;|&#x2019;|&rsquo;|\\u2019|\x{2019}|')+/'/g;
353
1160
2265
    $line =~ s/(?:$ignore_pattern)+/ /g;
354
1160
1708
    while ($line =~ s/($upper_pattern{2,})($upper_pattern$lower_pattern{2,})/ $1 $2 /g) {}
355
1160
3609
    while ($line =~ s/((?:$lower_pattern|$punctuation_pattern)+)($upper_pattern)/$1 $2/g) {}
356
1160
1279
    for my $token (split /\s+/, $line) {
357
3642
3277
      next unless $token =~ /$pattern/;
358
2483
2106
      $token =~ s/^(?:'|$rsqm)+//g;
359
2483
2523
      $token =~ s/(?:'|$rsqm)+s?$//g;
360
2483
1404
      my $raw_token = $token;
361
2483
1367
      $token =~ s/^[^Ii]?'+(.*)/$1/;
362
2483
1256
      $token =~ s/(.*?)'+$/$1/;
363
2483
3614
      next unless $token =~ $word_match;
364
2318
2108
      if (defined $dictionary{$token}) {
365
1038
467
        ++$words;
366
1038
539
        $unique_ref->{$token}=1;
367
1038
840
        next;
368      }
369
1280
1047
      if (@hunspell_dictionaries) {
370
1254
676
        my $found = 0;
371
1254
697
        for my $hunspell_dictionary (@hunspell_dictionaries) {
372          my $token_encoded = defined $hunspell_dictionary->{'encoding'} ?
373
1254
1081
            encode($hunspell_dictionary->{'encoding'}, $token) : $token;
374
1254
2807
          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
935
        next if $found;
382      }
383
1280
929
      my $key = lc $token;
384
1280
1151
      if (defined $dictionary{$key}) {
385
6
3
        ++$words;
386
6
5
        $unique_ref->{$key}=1;
387
6
7
        next;
388      }
389
1274
909
      unless ($disable_word_collating) {
390
1274
746
        $key =~ s/''+/'/g;
391
1274
1333
        $key =~ s/'[sd]$// unless length $key >= $shortest_threshold;
392      }
393
1274
1029
      if (defined $dictionary{$key}) {
394
0
0
        ++$words;
395
0
0
        $unique_ref->{$key}=1;
396
0
0
        next;
397      }
398
1274
614
      ++$unrecognized;
399
1274
768
      $unique_unrecognized_ref->{$raw_token}=1;
400
1274
1733
      $unrecognized_line_items_ref->{$raw_token}=1;
401    }
402
1160
1632
    return ($words, $unrecognized);
403}
404
405sub skip_file {
406
7
23
  my ($temp_dir, $reason) = @_;
407
7
229
  open(SKIPPED, '>:utf8', "$temp_dir/skipped");
408
7
42
  print SKIPPED $reason;
409
7
112
  close SKIPPED;
410}
411
412sub split_file {
413
18
13209
  my ($file) = @_;
414  our (
415
18
14
    $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
38
  $ignore_next_line_pattern = '$^' unless $ignore_next_line_pattern =~ /./;
425
426
18
20
  our %forbidden_re_descriptions;
427
18
8
  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
17
  my $rsqm = "\xE2\x80\x99";
431
432
18
23
  my @candidates_re_hits = (0) x scalar @candidates_re_list;
433
18
38
  my @candidates_re_lines = (0) x scalar @candidates_re_list;
434
18
19
  my @forbidden_re_hits = (0) x scalar @forbidden_re_list;
435
18
36
  my @forbidden_re_lines = (0) x scalar @forbidden_re_list;
436
18
48
  my $temp_dir = tempdir(DIR=>$sandbox);
437
18
3116
  print STDERR "checking file: $file\n" if defined $ENV{'DEBUG'};
438
18
455
  open(NAME, '>', "$temp_dir/name");
439
18
46
    print NAME $file;
440
18
204
  close NAME;
441
18
90
  my $file_size = -s $file;
442
18
26
  if (defined $largest_file) {
443
18
19
    unless ($check_file_names eq $file) {
444
18
23
      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
191
  if (defined readlink($file) &&
451      rindex(File::Spec->abs2rel(abs_path($file)), '../', 0) == 0) {
452
1
2
    skip_file($temp_dir, "file only has a single line (out-of-bounds-symbolic-link)\n");
453
1
4
    return $temp_dir;
454  }
455
16
22
  if ($use_magic_file) {
456
8
14962
    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
31303
      my $file_kind = <$file_fh>;
468
8
6235
      close $file_fh;
469
8
152
      if ($file_kind =~ /^(.*?); charset=binary/) {
470
2
34
        skip_file($temp_dir, "it appears to be a binary file (`$1`) (binary-file)\n");
471
2
51
        return $temp_dir;
472      }
473    }
474  }
475
14
156
  open FILE, '<', $file;
476
14
15
  binmode FILE;
477
14
8
  my $head;
478
14
109
  read(FILE, $head, 4096);
479
14
877
  $head =~ s/(?:\r|\n)+$//;
480
14
59
  my $dos_new_lines = () = $head =~ /\r\n/gi;
481
14
38
  my $unix_new_lines = () = $head =~ /\n/gi;
482
14
132
  my $mac_new_lines = () = $head =~ /\r/gi;
483
14
63
  local $/;
484
14
119
  if ($unix_new_lines == 0 && $mac_new_lines == 0) {
485
3
10
    $/ = "\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
9
    $/ = "\r";
490  } else {
491
8
10
    $/ = "\n";
492  }
493
14
29
  seek(FILE, 0, 0);
494
14
33
  ($words, $unrecognized) = (0, 0);
495
14
34
  %unique = ();
496
14
31
  %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
132
  };
504
505
14
475
  open(WARNINGS, '>:utf8', "$temp_dir/warnings");
506
14
11
  our $timeout;
507
14
19
  eval {
508
14
0
118
0
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
509
14
40
    alarm $timeout;
510
511
14
18
    my $ignore_next_line = 0;
512
14
47
    my ($current_begin_marker, $next_end_marker, $start_marker_line) = ('', '', '');
513
14
16
    my $offset = 0;
514
14
120
    LINE: while (<FILE>) {
515
1169
1152
      if ($. == 1) {
516
14
27
        unless ($disable_minified_file) {
517
14
69
          if ($file_size >= 512 && length($_) == $file_size) {
518
1
8
            skip_file($temp_dir, "file only has a single line (single-line-file)\n");
519
1
4
            last;
520          }
521        }
522      }
523
1168
2684
      $_ = decode_utf8($_, FB_DEFAULT);
524
1168
2776
      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
1456
      s/\R$//;
529
1168
1112
      s/^\x{FEFF}// if $. == 1;
530
1168
1127
      next unless /./;
531
1167
739
      my $raw_line = $_;
532
1167
545
      my $parsed_block_markers;
533
534      # hook for custom multiline based text exclusions:
535
1167
830
      if ($begin_block_re) {
536
1148
574
        FIND_END_MARKER: while (1) {
537
1150
978
          while ($next_end_marker ne '') {
538
6
28
            next LINE unless /\Q$next_end_marker\E/;
539
1
6
            s/.*?\Q$next_end_marker\E//;
540
1
5
            ($current_begin_marker, $next_end_marker, $start_marker_line) = ('', '', '');
541
1
2
            $parsed_block_markers = 1;
542          }
543
1145
1215
          my @captured = (/^.*?$begin_block_re/);
544
1145
1009
          last unless (@captured);
545
2
3
          for my $capture (0 .. $#captured) {
546
2
3
            if ($captured[$capture]) {
547
2
5
              ($current_begin_marker, $next_end_marker, $start_marker_line) = ($begin_block_list[$capture], $end_block_list[$capture], "$.:1 ... 1");
548
2
12
              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
859
        next if $parsed_block_markers;
555      }
556
557
1161
646
      my $ignore_this_line = $ignore_next_line;
558
1161
1024
      $ignore_next_line = ($_ =~ /$ignore_next_line_pattern/);
559
1161
784
      next if $ignore_this_line;
560
561      # hook for custom line based text exclusions:
562
1160
824
      if (defined $patterns_re) {
563
2
6
10
9
        s/($patterns_re)/"="x length($1)/ge;
564      }
565
1160
665
      my $initial_line_state = $_;
566
1160
779
      my $previous_line_state = $_;
567
1160
590
      my $line_flagged;
568
1160
813
      if ($forbidden_re) {
569
9
5
65
12
        while (s/($forbidden_re)/"="x length($1)/e) {
570
5
5
          $line_flagged = 1;
571
5
10
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
572
5
5
          my $found_trigger_re;
573
5
5
          for my $i (0 .. $#forbidden_re_list) {
574
7
5
            my $forbidden_re_singleton = $forbidden_re_list[$i];
575
7
7
            my $test_line = $previous_line_state;
576
7
4
57
6
            if ($test_line =~ s/($forbidden_re_singleton)/"="x length($1)/e) {
577
4
5
              next unless $test_line eq $_;
578
4
8
              my ($begin_test, $end_test, $match_test) = ($-[0] + 1, $+[0] + 1, $1);
579
4
7
              next unless $begin == $begin_test;
580
4
4
              next unless $end == $end_test;
581
4
5
              next unless $match eq $match_test;
582
4
2
              $found_trigger_re = $forbidden_re_singleton;
583
4
8
              my $hit = "$.:$begin:$end";
584
4
31
              $forbidden_re_hits[$i]++;
585
4
7
              $forbidden_re_lines[$i] = $hit unless $forbidden_re_lines[$i];
586
4
6
              last;
587            }
588          }
589
5
9
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
590
5
8
          if ($found_trigger_re) {
591
4
9
            my $description = $forbidden_re_descriptions{$found_trigger_re} || '';
592
4
9
            $found_trigger_re =~ s/^\(\?:(.*)\)$/$1/;
593
4
5
            my $quoted_trigger_re = CheckSpelling::Util::truncate_with_ellipsis(CheckSpelling::Util::wrap_in_backticks($found_trigger_re), 99);
594
4
5
            if ($description ne '') {
595
3
16
              print WARNINGS ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns rule: $description - $quoted_trigger_re (forbidden-pattern)\n";
596            } else {
597
1
5
              print WARNINGS ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns entry: $quoted_trigger_re (forbidden-pattern)\n";
598            }
599          } else {
600
1
4
            print WARNINGS ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns entry (forbidden-pattern)\n";
601          }
602
5
25
          $previous_line_state = $_;
603        }
604
9
9
        $_ = $initial_line_state;
605      }
606      # This is to make it easier to deal w/ rules:
607
1160
1078
      s/^/ /;
608
1160
707
      my %unrecognized_line_items = ();
609
1160
959
      my ($new_words, $new_unrecognized) = split_line($_, \%unique, \%unique_unrecognized, \%unrecognized_line_items);
610
1160
677
      $words += $new_words;
611
1160
522
      $unrecognized += $new_unrecognized;
612
1160
780
      my $line_length = length($raw_line);
613
1160
1692
      for my $token (sort CheckSpelling::Util::case_biased keys %unrecognized_line_items) {
614
1021
474
        my $found_token = 0;
615
1021
547
        my $raw_token = $token;
616
1021
543
        $token =~ s/'/(?:'|\x{2019}|\&apos;|\&#39;)+/g;
617
1021
410
        my $before;
618
1021
1559
        if ($token =~ /^$upper_pattern$lower_pattern/) {
619
5
7
          $before = '(?<=.)';
620        } elsif ($token =~ /^$upper_pattern/) {
621
0
0
          $before = "(?<!$upper_pattern)";
622        } else {
623
1016
611
          $before = "(?<=$not_lower_pattern)";
624        }
625
1021
1167
        my $after = ($token =~ /$upper_pattern$/) ? "(?=$not_upper_or_lower_pattern)|(?=$upper_pattern$lower_pattern)" : "(?=$not_lower_pattern)";
626
1021
2116
        while ($raw_line =~ /(?:\b|$before)($token)(?:\b|$after)/g) {
627
1271
657
          $line_flagged = 1;
628
1271
614
          $found_token = 1;
629
1271
1788
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
630
1271
1154
          next unless $match =~ /./;
631
1271
964
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
632
1271
5007
          print WARNINGS ":$.:$begin ... $end: $wrapped\n";
633        }
634
1021
1203
        unless ($found_token) {
635
3
30
          if ($raw_line !~ /$token.*$token/ && $raw_line =~ /($token)/) {
636
3
6
            my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
637
3
3
            my $wrapped = CheckSpelling::Util::wrap_in_backticks($raw_token);
638
3
13
            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
1886
      if ($line_flagged && $candidates_re) {
647
2
3
        $_ = $previous_line_state = $initial_line_state;
648
2
2
23
4
        s/($candidates_re)/"="x length($1)/ge;
649
2
3
        if ($_ ne $initial_line_state) {
650
2
2
          $_ = $previous_line_state;
651
2
3
          for my $i (0 .. $#candidates_re_list) {
652
4
5
            my $candidate_re = $candidates_re_list[$i];
653
4
27
            next unless $candidate_re =~ /./ && $raw_line =~ /$candidate_re/;
654
2
2
9
3
            if (($_ =~ s/($candidate_re)/"="x length($1)/e)) {
655
2
7
              my ($begin, $end) = ($-[0] + 1, $+[0] + 1);
656
2
6
              my $hit = "$.:$begin:$end";
657
2
2
              $_ = $previous_line_state;
658
2
2
8
3
              my $replacements = ($_ =~ s/($candidate_re)/"="x length($1)/ge);
659
2
2
              $candidates_re_hits[$i] += $replacements;
660
2
4
              $candidates_re_lines[$i] = $hit unless $candidates_re_lines[$i];
661
2
4
              $_ = $previous_line_state;
662            }
663          }
664        }
665      }
666
1160
837
      unless ($disable_minified_file) {
667
1160
889
        s/={3,}//g;
668
1160
849
        $offset += length;
669
1160
1026
        my $ratio = int($offset / $.);
670
1160
570
        my $ratio_threshold = 1000;
671
1160
3299
        if ($ratio > $ratio_threshold) {
672
2
9
          skip_file($temp_dir, "average line width ($ratio) exceeds the threshold ($ratio_threshold) (minified-file)\n");
673
2
8
          last;
674        }
675      }
676    }
677
14
24
    if ($next_end_marker) {
678
1
2
      if ($start_marker_line) {
679
1
2
        my $wrapped = CheckSpelling::Util::wrap_in_backticks($current_begin_marker);
680
1
8
        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
108
    alarm 0;
687  };
688
14
17
  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
45
  close FILE;
696
14
187
  close WARNINGS;
697
698
14
46
  if ($unrecognized || @candidates_re_hits || @forbidden_re_hits) {
699
13
384
    open(STATS, '>:utf8', "$temp_dir/stats");
700
13
218
      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
148
    close STATS;
708
13
288
    open(UNKNOWN, '>:utf8', "$temp_dir/unknown");
709
13
20
55
34
      print UNKNOWN map { "$_\n" } sort CheckSpelling::Util::case_biased keys %unique_unrecognized;
710
13
101
    close UNKNOWN;
711  }
712
713
14
139
  return $temp_dir;
714}
715
716sub main {
717
4
454
  my ($configuration, @ARGV) = @_;
718
4
3
  our %dictionary;
719
4
6
  unless (%dictionary) {
720
1
9
    init($configuration);
721  }
722
723  # read all input
724
4
5
  my @reports;
725
726
4
3
  for my $file (@ARGV) {
727
4
5
    my $temp_dir = split_file($file);
728
4
7
    push @reports, "$temp_dir\n";
729  }
730
4
13
  print join '', @reports;
731}
732
7331;