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