tools: validate utf8 encoding in stdin/out
[sheet.git] / tools / mkdigraphs-plan9
1 #!/usr/bin/env perl
2 use 5.014;
3 use warnings;
4 use utf8;
5 use open IO => ':encoding(utf-8)', ':std';
6 use Data::Dump 'pp';
7
8 our $VERSION = '1.01';
9
10 # translation table for deprecated code points
11 my %replace = (
12         0xF015 => '⎇',  # alt
13         0xF016 => '⇧',  # shift
14         0xF017 => '⎈',  # control
15 );
16
17 # expect input data source at command line
18 @ARGV or die "Specify input source file or - for STDIN\n";
19
20 # convert each character line to perl code
21 # (assume no backslashes or curlies, so we can just q{} w/o escaping)
22 say "# automatically generated by $0";
23 say 'use utf8;';
24 say '+{';
25 while ($_ = readline) {
26         my ($chrhex, $mnems, $sample, $name) = m{\A([0-9A-F ]{5}) (.{11}) (.)\h(.*)}i
27                 or warn("syntax error on line $.: $_"), next;
28         $chrhex =~ s/ $//;
29         my $chrnum = hex $chrhex;
30         my $chr = chr $chrnum;
31         $chr eq $sample
32                 or warn("character mismatch on line $.: $_"), next;
33         $chr = $replace{$chrnum} or next if defined $replace{$chrnum};
34         my $chrstr = pp($replace{$chrnum} // $chr);
35         for my $mnem (split / /, $mnems) {
36 #               next if length $mnem != 2;
37                 say "q{$mnem} => $chrstr, # $name";
38         }
39 }
40 say '}';
41
42 __END__
43
44 =head1 NAME
45
46 mkdigraphs-plan9 - Output digraph data from Plan9 keyboard data
47
48 =head1 SYNOPSIS
49
50 Extract digraphs from text specifications as a perl hash:
51
52     mkdigraphs-plan9 keyboard >digraphs-plan9.inc.pl
53
54 Input can be the literal RFC (or similar) document:
55
56     curl https://9fans.github.io/usr/local/plan9/lib/keyboard | mkdigraphs-plan9 -
57
58 Test by printing the character for DO (should be a dollar sign):
59
60     perl -e'$di = do "digraphs-plan9.inc.pl"; print chr $di->{DO}'
61
62 =head1 DESCRIPTION
63
64 Parses the official RFC-1345 document, searching the
65 'character mnemonic table' for all digraph definitions.
66 If successful, Perl code is output resulting in a hash
67 with Unicode code points keyed by digraph.
68 Obsolete values (references to private use area)
69 are converted to modern alternatives.
70 Any errors and warnings are given at STDERR.
71
72 =head1 AUTHOR
73
74 Mischa POSLAWSKY <perl@shiar.org>
75
76 =head1 LICENSE
77
78 Licensed under the GNU Affero General Public License version 3.
79