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
111246
1
use 5.022;
11
1
1
1
1
1
46
use feature 'unicode_strings';
12
1
1
1
2
0
9
use strict;
13
1
1
1
1
2
20
use warnings;
14
1
1
1
1
1
13
no warnings qw(experimental::vlb);
15
1
1
1
1
3
2
use utf8;
16
1
1
1
10
1
27
use Encode qw/decode_utf8 encode FB_DEFAULT/;
17
1
1
1
1
1
26
use File::Basename;
18
1
1
1
2
0
13
use Cwd 'abs_path';
19
1
1
1
4
0
17
use File::Spec;
20
1
1
1
2
0
16
use File::Temp qw/ tempfile tempdir /;
21
1
1
1
301
1
3655
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
21
  my ($expression) = @_;
46
32
32
16
219
  return eval { qr /$expression/ };
47}
48
49sub quote_re {
50
34
26
  my ($expression) = @_;
51
34
31
  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
107
   $1 . (defined($2) ? quotemeta($2) : '')
64/xge;
65
34
40
  return $expression;
66}
67
68sub file_to_lists {
69
6
6
  my ($re) = @_;
70
6
7
  my @patterns;
71  my %hints;
72
6
0
  my $fh;
73
6
53
  if (open($fh, '<:utf8', $re)) {
74
6
8
    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
24
    for (split /\R/, $file) {
80
32
21
      ++$line_number;
81
32
10
      chomp;
82
32
37
      if (/^#(?:\s(.+)|)/) {
83
12
27
        $hint = $1 if ($hint eq '' && defined $1);
84
12
10
        next;
85      }
86
20
18
      $hint = '' unless $_ ne '';
87
20
18
      my $pattern = $_;
88
20
48
      next unless s/^(.+)/(?:$1)/;
89
13
13
      my $quoted = quote_re($1);
90
13
13
      unless (test_re $quoted) {
91
1
2
        my $error = $@;
92
1
47
        my $home = dirname(__FILE__);
93
1
22
        $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
16
      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
12
        push @patterns, $_;
105
12
17
        $hints{$_} = $hint;
106      }
107
13
19
      $hint = '';
108    }
109  }
110
111  return {
112
6
21
    patterns => \@patterns,
113    hints => \%hints,
114  };
115}
116
117sub file_to_list {
118
5
1156
  my ($re) = @_;
119
5
7
  my $lists = file_to_lists($re);
120
121
5
5
2
15
  return @{$lists->{'patterns'}};
122}
123
124sub list_to_re {
125
5
5
  my (@list) = @_;
126
5
11
11
4
8
8
  @list = map { my $quoted = quote_re($_); test_re($quoted) ? $quoted : '' } @list;
127
5
11
5
10
  @list = grep { $_ ne '' } @list;
128
5
5
  return '$^' unless scalar @list;
129
5
12
  return join "|", (@list);
130}
131
132sub not_empty {
133
78
50
  my ($thing) = @_;
134
78
227
  return defined $thing && $thing ne ''
135}
136
137sub parse_block_list {
138
3
3
  my ($re) = @_;
139
3
2
  my @file;
140
3
21
  return @file unless (open(FILE, '<:utf8', $re));
141
142
3
5
  local $/=undef;
143
3
18
  my $file=<FILE>;
144
3
4
  my $last_line = $.;
145
3
7
  close FILE;
146
3
9
  for (split /\R/, $file) {
147
8
10
    next if /^#/;
148
5
2
    chomp;
149
5
5
    s/^\\#/#/;
150
5
6
    next unless /^./;
151
5
6
    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
1
13
    open EARLY_WARNINGS, ">>:encoding(UTF-8)", $early_warnings;
159
1
394
    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
10
    print STDERR "block-delimiter unmatched S: `$file[$i*2]`\n";
168
1
2
    @file = ();
169  }
170
171
3
8
  return @file;
172}
173
174sub valid_word {
175  # shortest_word is an absolute
176
28
18
  our ($shortest, $longest, $shortest_word, $longest_word);
177
28
21
  $shortest = $shortest_word if $shortest_word;
178
28
20
  if ($longest_word) {
179    # longest_word is an absolute
180
26
29
    $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
20
187
  my $word_pattern = join '|', (grep { defined $_ && /./ } ($upper_pattern, $lower_pattern, $punctuation_pattern));
188
28
24
  $word_pattern = q<\\w|'> unless $word_pattern;
189
28
49
  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
25
  $shortest = 3 unless defined $shortest;
195
28
21
  $longest = '' unless defined $longest;
196
28
97
  $word_match = "(?:$word_pattern){$shortest,$longest}";
197
28
192
  return qr/\b$word_match\b/;
198}
199
200sub load_dictionary {
201
15
1939
  my ($dict) = @_;
202
15
6
  our ($word_match, $longest, $shortest, $longest_word, $shortest_word, %dictionary);
203
15
13
  $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
11
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
206
15
7
  $ignore_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_IGNORE_PATTERN', q<[^a-zA-Z']>);
207
15
44
  $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
25
  $not_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_LOWER_PATTERN', '[^a-z]');
210
15
23
  $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
34
  %dictionary = ();
213
214
15
491
  open(DICT, '<:utf8', $dict);
215
15
61
  while (!eof(DICT)) {
216
52
53
    my $word = <DICT>;
217
52
35
    chomp $word;
218
52
129
    next unless $word =~ $word_match;
219
49
38
    my $l = length $word;
220
49
35
    $longest = -1 unless not_empty($longest);
221
49
48
    $longest = $l if $l > $longest;
222
49
33
    $shortest = $l if $l < $shortest;
223
49
93
    $dictionary{$word}=1;
224  }
225
15
34
  close DICT;
226
227
15
10
  $word_match = valid_word();
228}
229
230sub hunspell_dictionary {
231
3
3
  my ($dict) = @_;
232
3
4
  my $name = $dict;
233
3
3
  $name =~ s{/src/index/hunspell/index\.dic$}{};
234
3
11
  $name =~ s{.*/}{};
235
3
5
  my $aff = $dict;
236
3
1
  my $encoding;
237
3
8
  $aff =~ s/\.dic$/.aff/;
238
3
28
  if (open AFF, '<', $aff) {
239
3
18
    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
7
    close AFF;
245  }
246  return {
247
3
291
    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
14649
  my ($configuration) = @_;
257
12
9
  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
23
  our $sandbox = CheckSpelling::Util::get_file_from_env('sandbox', '');
260
12
12
  our $hunspell_dictionary_path = CheckSpelling::Util::get_file_from_env('hunspell_dictionary_path', '');
261
12
20
  our $timeout = CheckSpelling::Util::get_val_from_env('splitter_timeout', 30);
262
12
7
  our %forbidden_re_descriptions;
263
12
10
  if ($hunspell_dictionary_path) {
264
3
26
    our @hunspell_dictionaries = ();
265
1
1
1
1
1
1
1
1
1
3
221
1065
20
4
1
15
4
3
16
141
    if (eval 'use Text::Hunspell; 1') {
266
3
101
      my @hunspell_dictionaries_list = glob("$hunspell_dictionary_path/*.dic");
267
3
10
      for my $hunspell_dictionary_file (@hunspell_dictionaries_list) {
268
3
7
        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
70
  if (-e "$configuration/block-delimiters.list") {
276
3
4
    my @block_delimiters = parse_block_list "$configuration/block-delimiters.list";
277
3
4
    if (@block_delimiters) {
278
2
2
      @begin_block_list = ();
279
2
0
      @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
13
  my (@patterns_re_list, %in_patterns_re_list);
292
12
46
  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
14
    $patterns_re = undef;
298  }
299
300
12
37
  if (-e "$configuration/forbidden.txt") {
301
1
1
    my $forbidden_re_info = file_to_lists "$configuration/forbidden.txt";
302
1
1
0
2
    @forbidden_re_list = @{$forbidden_re_info->{'patterns'}};
303
1
1
1
2
    %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
45
  if (-e "$configuration/candidates.txt") {
310
4
5
    @candidates_re_list = file_to_list "$configuration/candidates.txt";
311
4
8
8
5
5
12
    @candidates_re_list = map { my $quoted = quote_re($_); $in_patterns_re_list{$_} || !test_re($quoted) ? '' : $quoted } @candidates_re_list;
312
4
3
    $candidates_re = list_to_re @candidates_re_list;
313  } else {
314
8
7
    $candidates_re = undef;
315  }
316
317
12
16
  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
13
  our $disable_word_collating = $disable_flags =~ /(?:^|,|\s)word-collating(?:,|\s|$)/;
321
12
4
  our $disable_minified_file = $disable_flags =~ /(?:^|,|\s)minified-file(?:,|\s|$)/;
322
12
9
  our $disable_single_line_file = $disable_flags =~ /(?:^|,|\s)single-line-file(?:,|\s|$)/;
323
324
12
5
  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
23
  our $check_file_names = CheckSpelling::Util::get_file_from_env('check_file_names', '');
328
329
12
8
  our $use_magic_file = CheckSpelling::Util::get_val_from_env('INPUT_USE_MAGIC_FILE', '');
330
331
12
12
  $word_match = valid_word();
332
333
12
20
  our $base_dict = CheckSpelling::Util::get_file_from_env('dict', "$configuration/words");
334
12
58
  $base_dict = '/usr/share/dict/words' unless -e $base_dict;
335
12
9
  load_dictionary($base_dict);
336}
337
338sub split_line {
339
1160
499
  our (%dictionary, $word_match, $disable_word_collating);
340
1160
410
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
341
1160
513
  our @hunspell_dictionaries;
342
1160
500
  our $shortest;
343
1160
754
  my $shortest_threshold = $shortest + 2;
344
1160
564
  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
602
  my $rsqm = "\xE2\x80\x99";
349
350
1160
625
  my ($words, $unrecognized) = (0, 0);
351
1160
832
  my ($line, $unique_ref, $unique_unrecognized_ref, $unrecognized_line_items_ref) = @_;
352
1160
5549
    $line =~ s/(?:$rsqm|&apos;|&#39;|\%27|&#8217;|&#x2019;|&rsquo;|\\u2019|\x{2019}|')+/'/g;
353
1160
2264
    $line =~ s/(?:$ignore_pattern)+/ /g;
354
1160
1707
    while ($line =~ s/($upper_pattern{2,})($upper_pattern$lower_pattern{2,})/ $1 $2 /g) {}
355
1160
3390
    while ($line =~ s/((?:$lower_pattern|$punctuation_pattern)+)($upper_pattern)/$1 $2/g) {}
356
1160
1330
    for my $token (split /\s+/, $line) {
357
3642
3200
      next unless $token =~ /$pattern/;
358
2483
1966
      $token =~ s/^(?:'|$rsqm)+//g;
359
2483
2540
      $token =~ s/(?:'|$rsqm)+s?$//g;
360
2483
1424
      my $raw_token = $token;
361
2483
1465
      $token =~ s/^[^Ii]?'+(.*)/$1/;
362
2483
1253
      $token =~ s/(.*?)'+$/$1/;
363
2483
3936
      next unless $token =~ $word_match;
364
2318
2129
      if (defined $dictionary{$token}) {
365
1038
499
        ++$words;
366
1038
548
        $unique_ref->{$token}=1;
367
1038
815
        next;
368      }
369
1280
1047
      if (@hunspell_dictionaries) {
370
1254
675
        my $found = 0;
371
1254
707
        for my $hunspell_dictionary (@hunspell_dictionaries) {
372          my $token_encoded = defined $hunspell_dictionary->{'encoding'} ?
373
1254
1080
            encode($hunspell_dictionary->{'encoding'}, $token) : $token;
374
1254
2995
          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
977
        next if $found;
382      }
383
1280
1002
      my $key = lc $token;
384
1280
1002
      if (defined $dictionary{$key}) {
385
6
4
        ++$words;
386
6
4
        $unique_ref->{$key}=1;
387
6
7
        next;
388      }
389
1274
876
      unless ($disable_word_collating) {
390
1274
725
        $key =~ s/''+/'/g;
391
1274
1338
        $key =~ s/'[sd]$// unless length $key >= $shortest_threshold;
392      }
393
1274
1106
      if (defined $dictionary{$key}) {
394
0
0
        ++$words;
395
0
0
        $unique_ref->{$key}=1;
396
0
0
        next;
397      }
398
1274
679
      ++$unrecognized;
399
1274
768
      $unique_unrecognized_ref->{$raw_token}=1;
400
1274
1751
      $unrecognized_line_items_ref->{$raw_token}=1;
401    }
402
1160
1626
    return ($words, $unrecognized);
403}
404
405sub skip_file {
406
7
21
  my ($temp_dir, $reason) = @_;
407
7
185
  open(SKIPPED, '>:utf8', "$temp_dir/skipped");
408
7
50
  print SKIPPED $reason;
409
7
85
  close SKIPPED;
410}
411
412sub split_file {
413
18
11590
  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
31
  $ignore_next_line_pattern = '$^' unless $ignore_next_line_pattern =~ /./;
425
426
18
10
  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
9
  my $rsqm = "\xE2\x80\x99";
431
432
18
18
  my @candidates_re_hits = (0) x scalar @candidates_re_list;
433
18
12
  my @candidates_re_lines = (0) x scalar @candidates_re_list;
434
18
17
  my @forbidden_re_hits = (0) x scalar @forbidden_re_list;
435
18
12
  my @forbidden_re_lines = (0) x scalar @forbidden_re_list;
436
18
32
  my $temp_dir = tempdir(DIR=>$sandbox);
437
18
2656
  print STDERR "checking file: $file\n" if defined $ENV{'DEBUG'};
438
18
462
  open(NAME, '>', "$temp_dir/name");
439
18
40
    print NAME $file;
440
18
196
  close NAME;
441
18
60
  my $file_size = -s $file;
442
18
19
  if (defined $largest_file) {
443
18
18
    unless ($check_file_names eq $file) {
444
18
16
      if ($file_size > $largest_file) {
445
1
2
        skip_file($temp_dir, "size `$file_size` exceeds limit `$largest_file` (large-file)\n");
446
1
3
        return $temp_dir;
447      }
448    }
449  }
450
17
210
  if (defined readlink($file) &&
451      rindex(File::Spec->abs2rel(abs_path($file)), '../', 0) == 0) {
452
1
4
    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
18
  if ($use_magic_file) {
456
8
12068
    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
28826
      my $file_kind = <$file_fh>;
468
8
4996
      close $file_fh;
469
8
106
      if ($file_kind =~ /^(.*?); charset=binary/) {
470
2
32
        skip_file($temp_dir, "it appears to be a binary file (`$1`) (binary-file)\n");
471
2
53
        return $temp_dir;
472      }
473    }
474  }
475
14
142
  open FILE, '<', $file;
476
14
10
  binmode FILE;
477
14
9
  my $head;
478
14
98
  read(FILE, $head, 4096);
479
14
806
  $head =~ s/(?:\r|\n)+$//;
480
14
49
  my $dos_new_lines = () = $head =~ /\r\n/gi;
481
14
38
  my $unix_new_lines = () = $head =~ /\n/gi;
482
14
102
  my $mac_new_lines = () = $head =~ /\r/gi;
483
14
49
  local $/;
484
14
79
  if ($unix_new_lines == 0 && $mac_new_lines == 0) {
485
3
11
    $/ = "\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
4
    $/ = "\r";
490  } else {
491
8
8
    $/ = "\n";
492  }
493
14
25
  seek(FILE, 0, 0);
494
14
20
  ($words, $unrecognized) = (0, 0);
495
14
30
  %unique = ();
496
14
25
  %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
103
  };
504
505
14
351
  open(WARNINGS, '>:utf8', "$temp_dir/warnings");
506
14
12
  our $timeout;
507
14
10
  eval {
508
14
0
90
0
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
509
14
31
    alarm $timeout;
510
511
14
16
    my $ignore_next_line = 0;
512
14
29
    my ($current_begin_marker, $next_end_marker, $start_marker_line) = ('', '', '');
513
14
16
    my $offset = 0;
514
14
84
    LINE: while (<FILE>) {
515
1169
1022
      if ($. == 1) {
516
14
10
        unless ($disable_minified_file) {
517
14
74
          if ($file_size >= 512 && length($_) == $file_size) {
518
1
9
            skip_file($temp_dir, "file only has a single line (single-line-file)\n");
519
1
2
            last;
520          }
521        }
522      }
523
1168
2428
      $_ = decode_utf8($_, FB_DEFAULT);
524
1168
2914
      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
1555
      s/\R$//;
529
1168
1038
      s/^\x{FEFF}// if $. == 1;
530
1168
1063
      next unless /./;
531
1167
724
      my $raw_line = $_;
532
1167
537
      my $parsed_block_markers;
533
534      # hook for custom multiline based text exclusions:
535
1167
780
      if ($begin_block_re) {
536
1148
526
        FIND_END_MARKER: while (1) {
537
1150
923
          while ($next_end_marker ne '') {
538
6
52
            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
1144
          my @captured = (/^.*?$begin_block_re/);
544
1145
990
          last unless (@captured);
545
2
2
          for my $capture (0 .. $#captured) {
546
2
2
            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
11
              s/^.*?\Q$begin_block_list[$capture]\E//;
549
2
2
              $parsed_block_markers = 1;
550
2
2
              next FIND_END_MARKER;
551            }
552          }
553        }
554
1143
864
        next if $parsed_block_markers;
555      }
556
557
1161
732
      my $ignore_this_line = $ignore_next_line;
558
1161
979
      $ignore_next_line = ($_ =~ /$ignore_next_line_pattern/);
559
1161
740
      next if $ignore_this_line;
560
561      # hook for custom line based text exclusions:
562
1160
788
      if (defined $patterns_re) {
563
2
6
11
8
        s/($patterns_re)/"="x length($1)/ge;
564      }
565
1160
674
      my $initial_line_state = $_;
566
1160
778
      my $previous_line_state = $_;
567
1160
512
      my $line_flagged;
568
1160
793
      if ($forbidden_re) {
569
9
5
60
10
        while (s/($forbidden_re)/"="x length($1)/e) {
570
5
5
          $line_flagged = 1;
571
5
8
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
572
5
4
          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
6
            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
6
              my ($begin_test, $end_test, $match_test) = ($-[0] + 1, $+[0] + 1, $1);
579
4
7
              next unless $begin == $begin_test;
580
4
2
              next unless $end == $end_test;
581
4
3
              next unless $match eq $match_test;
582
4
4
              $found_trigger_re = $forbidden_re_singleton;
583
4
7
              my $hit = "$.:$begin:$end";
584
4
4
              $forbidden_re_hits[$i]++;
585
4
4
              $forbidden_re_lines[$i] = $hit unless $forbidden_re_lines[$i];
586
4
6
              last;
587            }
588          }
589
5
6
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
590
5
6
          if ($found_trigger_re) {
591
4
6
            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
4
            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
5
              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
25
          $previous_line_state = $_;
603        }
604
9
7
        $_ = $initial_line_state;
605      }
606      # This is to make it easier to deal w/ rules:
607
1160
1172
      s/^/ /;
608
1160
715
      my %unrecognized_line_items = ();
609
1160
1016
      my ($new_words, $new_unrecognized) = split_line($_, \%unique, \%unique_unrecognized, \%unrecognized_line_items);
610
1160
624
      $words += $new_words;
611
1160
593
      $unrecognized += $new_unrecognized;
612
1160
767
      my $line_length = length($raw_line);
613
1160
1438
      for my $token (sort CheckSpelling::Util::case_biased keys %unrecognized_line_items) {
614
1021
582
        my $found_token = 0;
615
1021
489
        my $raw_token = $token;
616
1021
519
        $token =~ s/'/(?:'|\x{2019}|\&apos;|\&#39;)+/g;
617
1021
436
        my $before;
618
1021
1528
        if ($token =~ /^$upper_pattern$lower_pattern/) {
619
5
2
          $before = '(?<=.)';
620        } elsif ($token =~ /^$upper_pattern/) {
621
0
0
          $before = "(?<!$upper_pattern)";
622        } else {
623
1016
687
          $before = "(?<=$not_lower_pattern)";
624        }
625
1021
1198
        my $after = ($token =~ /$upper_pattern$/) ? "(?=$not_upper_or_lower_pattern)|(?=$upper_pattern$lower_pattern)" : "(?=$not_lower_pattern)";
626
1021
2149
        while ($raw_line =~ /(?:\b|$before)($token)(?:\b|$after)/g) {
627
1271
612
          $line_flagged = 1;
628
1271
601
          $found_token = 1;
629
1271
1712
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
630
1271
1188
          next unless $match =~ /./;
631
1271
947
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
632
1271
4958
          print WARNINGS ":$.:$begin ... $end: $wrapped\n";
633        }
634
1021
1184
        unless ($found_token) {
635
3
28
          if ($raw_line !~ /$token.*$token/ && $raw_line =~ /($token)/) {
636
3
5
            my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
637
3
3
            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
1894
      if ($line_flagged && $candidates_re) {
647
2
3
        $_ = $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
2
          $_ = $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
29
            next unless $candidate_re =~ /./ && $raw_line =~ /$candidate_re/;
654
2
2
9
3
            if (($_ =~ s/($candidate_re)/"="x length($1)/e)) {
655
2
3
              my ($begin, $end) = ($-[0] + 1, $+[0] + 1);
656
2
4
              my $hit = "$.:$begin:$end";
657
2
2
              $_ = $previous_line_state;
658
2
2
9
2
              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
4
              $_ = $previous_line_state;
662            }
663          }
664        }
665      }
666
1160
861
      unless ($disable_minified_file) {
667
1160
877
        s/={3,}//g;
668
1160
814
        $offset += length;
669
1160
1065
        my $ratio = int($offset / $.);
670
1160
559
        my $ratio_threshold = 1000;
671
1160
3205
        if ($ratio > $ratio_threshold) {
672
2
6
          skip_file($temp_dir, "average line width ($ratio) exceeds the threshold ($ratio_threshold) (minified-file)\n");
673
2
9
          last;
674        }
675      }
676    }
677
14
14
    if ($next_end_marker) {
678
1
1
      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
81
    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
37
  close FILE;
696
14
151
  close WARNINGS;
697
698
14
29
  if ($unrecognized || @candidates_re_hits || @forbidden_re_hits) {
699
13
329
    open(STATS, '>:utf8', "$temp_dir/stats");
700
13
182
      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
141
    close STATS;
708
13
268
    open(UNKNOWN, '>:utf8', "$temp_dir/unknown");
709
13
20
43
32
      print UNKNOWN map { "$_\n" } sort CheckSpelling::Util::case_biased keys %unique_unrecognized;
710
13
102
    close UNKNOWN;
711  }
712
713
14
114
  return $temp_dir;
714}
715
716sub main {
717
4
396
  my ($configuration, @ARGV) = @_;
718
4
1
  our %dictionary;
719
4
5
  unless (%dictionary) {
720
1
1
    init($configuration);
721  }
722
723  # read all input
724
4
4
  my @reports;
725
726
4
12
  for my $file (@ARGV) {
727
4
2
    my $temp_dir = split_file($file);
728
4
6
    push @reports, "$temp_dir\n";
729  }
730
4
10
  print join '', @reports;
731}
732
7331;