1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
use std::collections::HashSet;
use std::error;
use std::fmt;
use std::io;
use std::path::Path;
use std::process::Command;
use ast::TranslationUnit;
use env::Env;
use parser::translation_unit;
#[derive(Clone, Debug)]
pub struct Config {
pub cpp_command: String,
pub cpp_options: Vec<String>,
pub flavor: Flavor,
}
impl Config {
pub fn with_gcc() -> Config {
Config {
cpp_command: "gcc".into(),
cpp_options: vec!["-E".into()],
flavor: Flavor::GnuC11,
}
}
pub fn with_clang() -> Config {
Config {
cpp_command: "clang".into(),
cpp_options: vec!["-E".into()],
flavor: Flavor::ClangC11,
}
}
}
impl Default for Config {
#[cfg(target_os = "macos")]
fn default() -> Config {
Self::with_clang()
}
#[cfg(not(target_os = "macos"))]
fn default() -> Config {
Self::with_gcc()
}
}
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum Flavor {
StdC11,
GnuC11,
ClangC11,
}
#[derive(Clone, Debug)]
pub struct Parse {
pub source: String,
pub unit: TranslationUnit,
}
#[derive(Debug)]
pub enum Error {
PreprocessorError(io::Error),
SyntaxError(SyntaxError),
}
impl From<SyntaxError> for Error {
fn from(e: SyntaxError) -> Error {
Error::SyntaxError(e)
}
}
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self {
&Error::PreprocessorError(ref e) => write!(fmt, "preprocessor error: {}", e),
&Error::SyntaxError(ref e) => write!(fmt, "syntax error: {}", e),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match self {
&Error::PreprocessorError(_) => "preprocessor error",
&Error::SyntaxError(_) => "syntax error",
}
}
}
#[derive(Debug, Clone)]
pub struct SyntaxError {
pub source: String,
pub line: usize,
pub column: usize,
pub offset: usize,
pub expected: HashSet<&'static str>,
}
impl SyntaxError {
pub fn format_expected(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let mut list = self.expected.iter().collect::<Vec<_>>();
list.sort();
for (i, t) in list.iter().enumerate() {
if i > 0 {
try!(write!(fmt, ", "));
}
try!(write!(fmt, "'{}'", t));
}
Ok(())
}
}
impl fmt::Display for SyntaxError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(write!(
fmt,
"unexpected token at line {} column {}, expected ",
self.line, self.column
));
self.format_expected(fmt)
}
}
pub fn parse<P: AsRef<Path>>(config: &Config, source: P) -> Result<Parse, Error> {
let processed = match preprocess(config, source.as_ref()) {
Ok(s) => s,
Err(e) => return Err(Error::PreprocessorError(e)),
};
Ok(try!(parse_preprocessed(config, processed)))
}
pub fn parse_preprocessed(config: &Config, source: String) -> Result<Parse, SyntaxError> {
let mut env = match config.flavor {
Flavor::StdC11 => Env::with_core(),
Flavor::GnuC11 => Env::with_gnu(),
Flavor::ClangC11 => Env::with_clang(),
};
match translation_unit(&source, &mut env) {
Ok(unit) => Ok(Parse {
source: source,
unit: unit,
}),
Err(err) => Err(SyntaxError {
source: source,
line: err.line,
column: err.column,
offset: err.offset,
expected: err.expected,
}),
}
}
fn preprocess(config: &Config, source: &Path) -> io::Result<String> {
let mut cmd = Command::new(&config.cpp_command);
for item in &config.cpp_options {
cmd.arg(item);
}
cmd.arg(source);
let output = try!(cmd.output());
if output.status.success() {
match String::from_utf8(output.stdout) {
Ok(s) => Ok(s),
Err(e) => Err(io::Error::new(io::ErrorKind::Other, e)),
}
} else {
match String::from_utf8(output.stderr) {
Ok(s) => Err(io::Error::new(io::ErrorKind::Other, s)),
Err(_) => Err(io::Error::new(
io::ErrorKind::Other,
"cpp error contains invalid utf-8",
)),
}
}
}