]> git.sur5r.net Git - i3/i3/blob - generate-command-parser.pl
generate-command-parser: make input/output configurable
[i3/i3] / generate-command-parser.pl
1 #!/usr/bin/env perl
2 # vim:ts=4:sw=4:expandtab
3 #
4 # i3 - an improved dynamic tiling window manager
5 # © 2009-2012 Michael Stapelberg and contributors (see also: LICENSE)
6 #
7 # generate-command-parser.pl: script to generate parts of the command parser
8 # from its specification file parser-specs/commands.spec.
9 #
10 # Requires only perl >= 5.10, no modules.
11
12 use strict;
13 use warnings;
14 use Data::Dumper;
15 use Getopt::Long;
16 use v5.10;
17
18 my $input = '';
19 my $prefix = '';
20 my $result = GetOptions(
21     'input=s' => \$input,
22     'prefix=s' => \$prefix
23 );
24
25 die qq|Input file "$input" does not exist!| unless -e $input;
26
27 # reads in a whole file
28 sub slurp {
29     open my $fh, '<', shift;
30     local $/;
31     <$fh>;
32 }
33
34 # Stores the different states.
35 my %states;
36
37 my @raw_lines = split("\n", slurp($input));
38 my @lines;
39
40 # XXX: In the future, we might switch to a different way of parsing this. The
41 # parser is in many ways not good — one obvious one is that it is hand-crafted
42 # without a good reason, also it preprocesses lines and forgets about line
43 # numbers. Luckily, this is just an implementation detail and the specification
44 # for the i3 command parser is in-tree (not user input).
45 # -- michael, 2012-01-12
46
47 # First step of preprocessing:
48 # Join token definitions which are spread over multiple lines.
49 for my $line (@raw_lines) {
50     next if $line =~ /^\s*#/ || $line =~ /^\s*$/;
51
52     if ($line =~ /^\s+->/) {
53         # This is a continued token definition, append this line to the
54         # previous one.
55         $lines[$#lines] = $lines[$#lines] . $line;
56     } else {
57         push @lines, $line;
58         next;
59     }
60 }
61
62 # First step: We build up the data structure containing all states and their
63 # token rules.
64
65 my $current_state;
66
67 for my $line (@lines) {
68     if (my ($state) = ($line =~ /^state ([A-Z_]+):$/)) {
69         #say "got a new state: $state";
70         $current_state = $state;
71     } else {
72         # Must be a token definition:
73         # [identifier = ] <tokens> -> <action>
74         #say "token definition: $line";
75
76         my ($identifier, $tokens, $action) =
77             ($line =~ /
78                 ^\s*                  # skip leading whitespace
79                 ([a-z_]+ \s* = \s*|)  # optional identifier
80                 (.*?) -> \s*          # token 
81                 (.*)                  # optional action
82              /x);
83
84         # Cleanup the identifier (if any).
85         $identifier =~ s/^\s*(\S+)\s*=\s*$/$1/g;
86
87         # Cleanup the tokens (remove whitespace).
88         $tokens =~ s/\s*//g;
89
90         # The default action is to stay in the current state.
91         $action = $current_state if length($action) == 0;
92
93         #say "identifier = *$identifier*, token = *$tokens*, action = *$action*";
94         for my $token (split(',', $tokens)) {
95             my $store_token = {
96                 token => $token,
97                 identifier => $identifier,
98                 next_state => $action,
99             };
100             if (exists $states{$current_state}) {
101                 push @{$states{$current_state}}, $store_token;
102             } else {
103                 $states{$current_state} = [ $store_token ];
104             }
105         }
106     }
107 }
108
109 # Second step: Generate the enum values for all states.
110
111 # It is important to keep the order the same, so we store the keys once.
112 my @keys = keys %states;
113
114 open(my $enumfh, '>', "GENERATED_${prefix}_enums.h");
115
116 # XXX: we might want to have a way to do this without a trailing comma, but gcc
117 # seems to eat it.
118 say $enumfh 'typedef enum {';
119 my $cnt = 0;
120 for my $state (@keys, '__CALL') {
121     say $enumfh "    $state = $cnt,";
122     $cnt++;
123 }
124 say $enumfh '} cmdp_state;';
125 close($enumfh);
126
127 # Third step: Generate the call function.
128 open(my $callfh, '>', "GENERATED_${prefix}_call.h");
129 say $callfh 'static void GENERATED_call(const int call_identifier, struct CommandResult *result) {';
130 say $callfh '    switch (call_identifier) {';
131 my $call_id = 0;
132 for my $state (@keys) {
133     my $tokens = $states{$state};
134     for my $token (@$tokens) {
135         next unless $token->{next_state} =~ /^call /;
136         my ($cmd) = ($token->{next_state} =~ /^call (.*)/);
137         my ($next_state) = ($cmd =~ /; ([A-Z_]+)$/);
138         $cmd =~ s/; ([A-Z_]+)$//;
139         # Go back to the INITIAL state unless told otherwise.
140         $next_state ||= 'INITIAL';
141         my $fmt = $cmd;
142         # Replace the references to identified literals (like $workspace) with
143         # calls to get_string().
144         $cmd =~ s/\$([a-z_]+)/get_string("$1")/g;
145         # Used only for debugging/testing.
146         $fmt =~ s/\$([a-z_]+)/%s/g;
147         $fmt =~ s/"([a-z0-9_]+)"/%s/g;
148
149         say $callfh "         case $call_id:";
150         say $callfh '#ifndef TEST_PARSER';
151         my $real_cmd = $cmd;
152         if ($real_cmd =~ /\(\)/) {
153             $real_cmd =~ s/\(/(&current_match, result/;
154         } else {
155             $real_cmd =~ s/\(/(&current_match, result, /;
156         }
157         say $callfh "             $real_cmd;";
158         say $callfh '#else';
159         # debug
160         $cmd =~ s/[^(]+\(//;
161         $cmd =~ s/\)$//;
162         $cmd = ", $cmd" if length($cmd) > 0;
163         say $callfh qq|           fprintf(stderr, "$fmt\\n"$cmd);|;
164         say $callfh '#endif';
165         say $callfh "             state = $next_state;";
166         say $callfh "             break;";
167         $token->{next_state} = "call $call_id";
168         $call_id++;
169     }
170 }
171 say $callfh '        default:';
172 say $callfh '            printf("BUG in the parser. state = %d\n", call_identifier);';
173 say $callfh '    }';
174 say $callfh '}';
175 close($callfh);
176
177 # Fourth step: Generate the token datastructures.
178
179 open(my $tokfh, '>', "GENERATED_${prefix}_tokens.h");
180
181 for my $state (@keys) {
182     my $tokens = $states{$state};
183     say $tokfh 'static cmdp_token tokens_' . $state . '[' . scalar @$tokens . '] = {';
184     for my $token (@$tokens) {
185         my $call_identifier = 0;
186         my $token_name = $token->{token};
187         if ($token_name =~ /^'/) {
188             # To make the C code simpler, we leave out the trailing single
189             # quote of the literal. We can do strdup(literal + 1); then :).
190             $token_name =~ s/'$//;
191         }
192         my $next_state = $token->{next_state};
193         if ($next_state =~ /^call /) {
194             ($call_identifier) = ($next_state =~ /^call ([0-9]+)$/);
195             $next_state = '__CALL';
196         }
197         my $identifier = $token->{identifier};
198         say $tokfh qq|    { "$token_name", "$identifier", $next_state, { $call_identifier } }, |;
199     }
200     say $tokfh '};';
201 }
202
203 say $tokfh 'static cmdp_token_ptr tokens[' . scalar @keys . '] = {';
204 for my $state (@keys) {
205     my $tokens = $states{$state};
206     say $tokfh '    { tokens_' . $state . ', ' . scalar @$tokens . ' },';
207 }
208 say $tokfh '};';
209
210 close($tokfh);