Debian Codegraph @

ext/ripper/tools/preproc.rb

raw
1 # frozen_string_literal: true
2 # $Id$
3
4 require 'optparse'
5
6 def main
7 output = nil
8 template = nil
9 parser = OptionParser.new
10 parser.banner = "Usage: #{File.basename($0)} [--output=PATH] [--template=PATH] <parse.y>"
11 parser.on('--output=PATH', 'An output file.') {|path|
12 output = path
13 }
14 parser.on('--template=PATH', 'An template file.') {|path|
15 template = path
16 }
17 parser.on('--help', 'Prints this message and quit.') {
18 puts parser.help
19 exit true
20 }
21 begin
22 parser.parse!
23 rescue OptionParser::ParseError => err
24 warn err.message
25 abort parser.help
26 end
27 out = "".dup
28 if ARGV[0] == "-"
29 unless ARGV.size == 2
30 abort "wrong number of arguments (#{ARGV.size} for 2)"
31 end
32 process STDIN, out, ARGV[1], template
33 else
34 unless ARGV.size == 1
35 abort "wrong number of arguments (#{ARGV.size} for 1)"
36 end
37 File.open(ARGV[0]) {|f|
38 process f, out, ARGV[0], template
39 }
40 end
41 if output
42 File.write(output, out)
43 else
44 print out
45 end
46 end
47
48 def process(f, out, path, template)
49 prelude f, out
50 grammar f, out
51 usercode f, out, path, template
52 end
53
54 def prelude(f, out)
55 @exprs = {}
56 lex_state_def = false
57 while line = f.gets
58 case line
59 when /\A%%/
60 out << "%%\n"
61 return
62 when /\A%token/, /\A%type/, /\A} <node(?>_\w+)?>/
63 # types in %union which have corresponding set_yylval_* macro.
64 out << line.sub(/<(?:node(?>_\w+)?|num|id)>/, '<val>')
65 when /^enum lex_state_(?:bits|e) \{/
66 lex_state_def = true
67 out << line
68 when /^\}/
69 lex_state_def = false
70 out << line
71 else
72 out << line
73 end
74 if lex_state_def
75 case line
76 when /^\s*(EXPR_\w+),\s+\/\*(.+)\*\//
77 @exprs[$1.chomp("_bit")] = $2.strip
78 when /^\s*(EXPR_\w+)\s+=\s+(.+)$/
79 name = $1
80 val = $2.chomp(",")
81 @exprs[name] = "equals to " + (val.start_with?("(") ? "<tt>#{val}</tt>" : "+#{val}+")
82 end
83 end
84 end
85 end
86
87 require_relative "dsl"
88
89 def grammar(f, out)
90 while line = f.gets
91 case line
92 when %r</\*% *ripper(?:\[(.*?)\])?: *(.*?) *%\*/>
93 out << DSL.new($2, ($1 || "").split(",")).generate << "\n"
94 when %r</\*%%%\*/>
95 out << "#if 0\n"
96 when %r</\*%>
97 out << "#endif\n"
98 when %r<%\*/>
99 out << "\n"
100 when /\A%%/
101 out << "%%\n"
102 return
103 else
104 out << line
105 end
106 end
107 end
108
109 def usercode(f, out, path, template)
110 require 'erb'
111 lineno = nil
112 src = nil
113 compiler = ERB::Compiler.new('%-')
114 compiler.put_cmd = compiler.insert_cmd = "out.<<"
115
116 if template
117 File.open(template) do |f|
118 out.clear
119 lineno = f.lineno
120 src, = compiler.compile(f.read)
121 path = template
122 end
123 else
124 lineno = f.lineno
125 src, = compiler.compile(f.read)
126 end
127
128 eval(src, binding, path, lineno)
129 end
130
131 main