1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2009 Jean Privat <jean@pryen.org>
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 # prescc, a Sablecc preprocessor.
21 # Extends a sablecc grammar with parametrized productions.
25 # A production named foo~bar~baz semantically correspond to a production foo with two boolean parameters bar and baz
26 # In fact foo is a family of 4 distinct productions: foo, foo_bar, foo_baz and foo_bar_baz
27 # In a parametrized production with a parameter ~xxx:
28 # * parameters (~xxx) are substituted with _xxx if the parameter is true and removed if the parameter is false
29 # * guarded alternatives (!xxx) are disabled if the parameter is true
33 # prescc is badly implemented with shell, sed and perl and is not robust.
34 # Users must remember the following:
35 # * parametrized productions MUST be terminated with a line containing only a single semicolon (;)
36 # * parameters (~) and guards (!) in alternatives MUST correspond to a parameter of the enclosing production
37 # * if required, names in transformations MUST contain the full invocation name (with all parameters)
38 # foo bar_x~y~z_t baz {-> New p(foo, bar_x~y~z_t.q)}
39 # * guards do not understand grammar, they just remove the whole line
40 # * The AST MUST start with a line containing only "Abstract Syntax Tree"
42 # Example of the dangling else implementation:
45 # 'if' expr 'then' stmt_withelse 'else' stmt~withelse |
46 # !withelse 'if' expr 'then' stmt |
53 *) echo "Usage: prescc infile outfile"; exit
59 tmpfile
=`mktemp "$2.XXXXXX"`
61 echo -n
"/* This file is autogenerated, do not modify it */" > "$outfile"
62 cat "$infile" >> "$outfile"
64 # The perl code is used to list all the available parameters in the extended grammar
65 for token
in `perl -ne 'if (/\~(\w+)/ && !$found{$1}) {print "$1\n"; $found{$1}=1}' "$infile"`
67 echo "Parameter ~$token"
68 # first, sed starts from first line to the AST line and removes ~xxx and !xxx
69 sed -n
-e
"1,/^Abstract Syntax Tree/{/^Abstract Syntax Tree/b;s/[\~!]$token//g;p}" "$outfile" > "$tmpfile"
70 # second, sed clones ~xxx parametrized productions, substitute ~xxx with _xxx and delete !xxx lines
71 sed -n
-e
"/\~$token/,/;/{s/\~$token/_$token/g;/!$token/d;p}" "$outfile" >> "$tmpfile"
72 # third, sed continues fron AST line to last line and remove ~xxx and !xxx
73 sed -n
-e
"/^Abstract Syntax Tree/,\${s/[\~!]$token//g;p}" "$outfile" >> "$tmpfile"
74 mv "$tmpfile" "$outfile"