File Coverage

File:lib/CheckSpelling/Homoglyph.pm
Coverage:79.2%

linestmtbrancondsubtimecode
1#! -*-perl-*-
2
3package CheckSpelling::Homoglyph;
4
5our $VERSION='0.1.0';
6our $flatten=0;
7
8
1
1
1
2
1
1
use utf8;
9
1
1
1
16
0
264
use CheckSpelling::Util;
10
11my %homoglyph_map;
12my $homoglyphs;
13
14my %homoglyph_to_glyph;
15
16sub init {
17
11
10
    my ($file) = @_;
18
1
1
1
11
2
0
3
137
    return unless open (my $fh, '<:encoding(UTF-8)', $file);
19
11
703
    my $ignore_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_IGNORE_PATTERN', q<[^a-zA-Z']>);
20
11
32
    my $upper_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_UPPER_PATTERN', '[A-Z]');
21
11
24
    my $lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_LOWER_PATTERN', '[a-z]');
22
11
22
    my $not_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_LOWER_PATTERN', '[^a-z]');
23
11
23
    my $not_upper_or_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_UPPER_OR_LOWER_PATTERN', '[^A-Za-z]');
24
11
29
    my $punctuation_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_PUNCTUATION_PATTERN', q<'>);
25
11
31
    local $/ = "\n";
26
11
112
    while (<$fh>) {
27
539
647
        next if /^#/;
28
539
311
        s/^\\//;
29
539
563
        next unless /(.)(.+)/;
30
539
408
        my ($expected, $aliases) = ($1, $2);
31
539
590
        my @chars = split('', $aliases);
32
539
618
        next unless $expected =~ /$upper_pattern|$lower_pattern|$punctuation_pattern/;
33
539
554
        next unless $expected =~ /$upper_pattern|$lower_pattern/;
34
539
242
        my @unexpected_chars;
35
539
256
        for my $ch (@chars) {
36
12727
11420
            if ($ch =~ /$ignore_pattern/) {
37
12727
5291
                my %ref;
38
12727
4926
                my $known_aliases = \%ref;
39
12727
8252
                if (defined $homoglyph_map{$ch}) {
40
11570
5355
                    $known_aliases = $homoglyph_map{$ch};
41                }
42
12727
6645
                $known_aliases->{$expected} = 1;
43
12727
10026
                $homoglyph_map{$ch} = $known_aliases;
44            }
45        }
46    }
47
11
55
    close $fh;
48
11
3480
    my @glyphs = sort keys %homoglyph_map;
49
11
378
    our $homoglyphs = join '', @glyphs;
50
11
8
    our %homoglyph_to_glyph;
51
11
5
    for my $ch (@glyphs) {
52
12727
12727
4945
7825
        my @known_aliases = keys %{$homoglyph_map{$ch}};
53
12727
6624
        if (scalar @known_aliases == 1) {
54
12727
8218
            $homoglyph_to_glyph{$ch} = $known_aliases[0];
55        } else {
56
0
            $homoglyph_to_glyph{$ch} = $ch;
57        }
58    }
59}
60
61sub dump_aliases {
62
0
    my $a;
63
0
    for my $ch (keys %homoglyph_map) {
64
0
        $a = $ch;
65
0
        my $b = $homoglyph_map{$a};
66
0
        print "$a: ".(join " ", (sort keys %$b))."\n";
67    }
68
0
    print "\n"."homoglyphs: $homoglyphs\n";
69}
701;