Skip to content

Commit a710028

Browse files
authored
Merge pull request #12 from birkenfeld/either
Convert Eithers into Results.
2 parents 3e8f0e2 + 2819294 commit a710028

File tree

11 files changed

+104
-122
lines changed

11 files changed

+104
-122
lines changed

src/analysis/decl_analysis.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,12 +59,12 @@ pub fn tParamDecl(_0: CDecl) -> m<ParamDecl> {
5959
}
6060
}
6161

62-
pub fn computeParamStorage(_0: NodeInfo, _1: StorageSpec) -> Either<BadSpecifierError, Storage> {
62+
pub fn computeParamStorage(_0: NodeInfo, _1: StorageSpec) -> Result<Storage, BadSpecifierError> {
6363
match (_0, _1) {
64-
(_, NoStorageSpec) => Right((Auto(false))),
65-
(_, RegSpec) => Right((Auto(true))),
64+
(_, NoStorageSpec) => Ok((Auto(false))),
65+
(_, RegSpec) => Ok((Auto(true))),
6666
(node, spec) => {
67-
Left(badSpecifierError(node,
67+
Err(badSpecifierError(node,
6868
__op_addadd("Bad storage specified for parameter: "
6969
.to_string(),
7070
show(spec))))

src/analysis/trav_monad.rs

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -233,8 +233,8 @@ pub fn isDeclaration(_0: IdentDecl) -> bool {
233233
}
234234
}
235235

236-
pub fn checkCompatibleTypes(_: Type, _: Type) -> Either<TypeMismatch, ()> {
237-
Right(())
236+
pub fn checkCompatibleTypes(_: Type, _: Type) -> Result<(), TypeMismatch> {
237+
Ok(())
238238
}
239239

240240
pub fn handleObjectDef(local: bool, ident: Ident, obj_def: ObjDef) -> m<()> {
@@ -359,10 +359,10 @@ pub fn astError<a>(node: NodeInfo, msg: String) -> m<a> {
359359
throwTravError(invalidAST(node, msg))
360360
}
361361

362-
pub fn throwOnLeft<a>(_0: Either<e, a>) -> m<a> {
362+
pub fn throwOnLeft<a>(_0: Result<a, e>) -> m<a> {
363363
match (_0) {
364-
Left(err) => throwTravError(err),
365-
Right(v) => v,
364+
Err(err) => throwTravError(err),
365+
Ok(v) => v,
366366
}
367367
}
368368

@@ -371,9 +371,9 @@ pub fn warn(err: e) -> m<()> {
371371
}
372372

373373
pub struct Trav<s, a> {
374-
unTrav: fn(TravState<s>) -> Either<CError, (a, TravState<s>)>,
374+
unTrav: fn(TravState<s>) -> Result<(a, TravState<s>), CError>,
375375
}
376-
fn unTrav(a: Trav) -> fn(TravState<s>) -> Either<CError, (a, TravState<s>)> {
376+
fn unTrav(a: Trav) -> fn(TravState<s>) -> Result<(a, TravState<s>), CError> {
377377
a.unTrav
378378
}
379379

@@ -393,21 +393,21 @@ pub fn put(s: TravState<s>) -> Trav<s, ()> {
393393
Trav((|_| Right(((), s))))
394394
}
395395

396-
pub fn runTrav<a>(state: s, traversal: Trav<s, a>) -> Either<Vec<CError>, (a, TravState<s>)> {
396+
pub fn runTrav<a>(state: s, traversal: Trav<s, a>) -> Result<(a, TravState<s>), Vec<CError>> {
397397

398398
let action = /*do*/ {
399399
withDefTable((__TODO_const(((), builtins))));
400400
traversal
401401
};
402402

403403
match unTrav(action, (initTravState(state))) {
404-
Left(trav_err) => Left(vec![trav_err]),
405-
Right((v, ts)) if hadHardErrors((travErrors(ts))) => Left((travErrors(ts))),
406-
Right((v, ts)) => Right((v, ts)),
404+
Err(trav_err) => Err(vec![trav_err]),
405+
Ok((v, ts)) if hadHardErrors((travErrors(ts))) => Err((travErrors(ts))),
406+
Ok((v, ts)) => Ok((v, ts)),
407407
}
408408
}
409409

410-
pub fn runTrav_<a>(t: Trav<(), a>) -> Either<Vec<CError>, (a, Vec<CError>)> {
410+
pub fn runTrav_<a>(t: Trav<(), a>) -> Result<(a, Vec<CError>), Vec<CError>> {
411411
fmap(fst,
412412
runTrav((),
413413
/*do*/

src/analysis/type_check.rs

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -32,11 +32,13 @@ use analysis::type_utils::*;
3232
use analysis::trav_monad::*;
3333
use data::ident::*;
3434

35+
pub type TcResult<T> = Result<T, String>;
36+
3537
pub fn pType() -> String {
3638
render(pretty)
3739
}
3840

39-
pub fn typeErrorOnLeft<a>(_0: NodeInfo, _1: Either<String, a>) -> m<a> {
41+
pub fn typeErrorOnLeft<a>(_0: NodeInfo, _1: TcResult<a>) -> m<a> {
4042
match (_0, _1) {
4143
(ni, Left(err)) => typeError(ni, err),
4244
(_, Right(v)) => v,
@@ -47,7 +49,7 @@ pub fn typeError<a>() -> m<a> {
4749
astError
4850
}
4951

50-
pub fn notFound<a>(i: Ident) -> Either<String, a> {
52+
pub fn notFound<a>(i: Ident) -> TcResult<a> {
5153
Left(__op_addadd("not found: ".to_string(), identToString(i)))
5254
}
5355

@@ -71,7 +73,7 @@ pub fn conditionalType_q(ni: NodeInfo, t1: Type, t2: Type) -> m<Type> {
7173
typeErrorOnLeft(ni, conditionalType(t1, t2))
7274
}
7375

74-
pub fn checkScalar(t: Type) -> Either<String, ()> {
76+
pub fn checkScalar(t: Type) -> TcResult<()> {
7577
match canonicalType(t) {
7678
DirectType(_, _, _) => (),
7779
PtrType(_, _, _) => (),
@@ -120,11 +122,11 @@ pub fn constType(_0: CConst) -> m<Type> {
120122
}
121123
}
122124

123-
pub fn compatible(t1: Type, t2: Type) -> Either<String, ()> {
125+
pub fn compatible(t1: Type, t2: Type) -> TcResult<()> {
124126
void(compositeType(t1, t2))
125127
}
126128

127-
pub fn compositeType(_0: Type, _1: Type) -> Either<String, Type> {
129+
pub fn compositeType(_0: Type, _1: Type) -> TcResult<Type> {
128130
match (_0, _1) {
129131
(t1, DirectType(TyBuiltin(TyAny), _, _)) => t1,
130132
(DirectType(TyBuiltin(TyAny), _, _), t2) => t2,
@@ -254,7 +256,7 @@ pub fn compositeType(_0: Type, _1: Type) -> Either<String, Type> {
254256
}
255257
}
256258

257-
pub fn compositeSize(_0: ArraySize, _1: ArraySize) -> Either<String, ArraySize> {
259+
pub fn compositeSize(_0: ArraySize, _1: ArraySize) -> TcResult<ArraySize> {
258260
match (_0, _1) {
259261
(UnknownArraySize(_), s2) => s2,
260262
(s1, UnknownArraySize(_)) => s1,
@@ -276,7 +278,7 @@ pub fn mergeAttrs() -> Attributes {
276278
(__op_addadd)
277279
}
278280

279-
pub fn compositeParamDecl(_0: ParamDecl, _1: ParamDecl) -> Either<String, ParamDecl> {
281+
pub fn compositeParamDecl(_0: ParamDecl, _1: ParamDecl) -> TcResult<ParamDecl> {
280282
match (_0, _1) {
281283
(ParamDecl(vd1, ni1), ParamDecl(vd2, _)) => compositeParamDecl_q(ParamDecl, vd1, vd2, ni1),
282284
(AbstractParamDecl(vd1, _), ParamDecl(vd2, ni2)) => {
@@ -295,7 +297,7 @@ pub fn compositeParamDecl_q(f: fn(VarDecl) -> fn(NodeInfo) -> ParamDecl,
295297
VarDecl(n1, attrs1, t1): VarDecl,
296298
VarDecl(n2, attrs2, t2): VarDecl,
297299
dni: NodeInfo)
298-
-> Either<String, ParamDecl> {
300+
-> TcResult<ParamDecl> {
299301

300302
let t1_q = canonicalType(t1);
301303

@@ -311,7 +313,7 @@ pub fn compositeParamDecl_q(f: fn(VarDecl) -> fn(NodeInfo) -> ParamDecl,
311313

312314
pub fn compositeVarDecl(VarDecl(n1, attrs1, t1): VarDecl,
313315
VarDecl(_, attrs2, t2): VarDecl)
314-
-> Either<String, VarDecl> {
316+
-> TcResult<VarDecl> {
315317
/*do*/
316318
{
317319
let t = compositeType(t1, t2);
@@ -326,14 +328,14 @@ pub fn compositeDeclAttrs(DeclAttrs(inl, stor, attrs1): DeclAttrs,
326328
DeclAttrs(inl, stor, (mergeAttrs(attrs1, attrs2)))
327329
}
328330

329-
pub fn castCompatible(t1: Type, t2: Type) -> Either<String, ()> {
331+
pub fn castCompatible(t1: Type, t2: Type) -> TcResult<()> {
330332
match (canonicalType(t1), canonicalType(t2)) {
331333
(DirectType(TyVoid, _, _), _) => (),
332334
(_, _) => __op_rshift(checkScalar(t1), checkScalar(t2)),
333335
}
334336
}
335337

336-
pub fn assignCompatible(_0: CAssignOp, _1: Type, _2: Type) -> Either<String, ()> {
338+
pub fn assignCompatible(_0: CAssignOp, _1: Type, _2: Type) -> TcResult<()> {
337339
match (_0, _1, _2) {
338340
(CAssignOp, t1, t2) => {
339341
match (canonicalType(t1), canonicalType(t2)) {
@@ -369,7 +371,7 @@ pub fn assignCompatible(_0: CAssignOp, _1: Type, _2: Type) -> Either<String, ()>
369371
}
370372
}
371373

372-
pub fn binopType(op: CBinaryOp, t1: Type, t2: Type) -> Either<String, Type> {
374+
pub fn binopType(op: CBinaryOp, t1: Type, t2: Type) -> TcResult<Type> {
373375
match (op, canonicalType(t1), canonicalType(t2)) {
374376
(_, t1_q, t2_q) if isLogicOp(op) => {
375377
__op_rshift(checkScalar(t1_q), __op_rshift(checkScalar(t2_q), boolType))
@@ -443,7 +445,7 @@ pub fn binopType(op: CBinaryOp, t1: Type, t2: Type) -> Either<String, Type> {
443445
}
444446
}
445447

446-
pub fn conditionalType(t1: Type, t2: Type) -> Either<String, Type> {
448+
pub fn conditionalType(t1: Type, t2: Type) -> TcResult<Type> {
447449
match (canonicalType(t1), canonicalType(t2)) {
448450
(PtrType(DirectType(TyVoid, _, _), _, _), t2_q) if isPointerType(t2_q) => t2,
449451
(t1_q, PtrType(DirectType(TyVoid, _, _), _, _)) if isPointerType(t1_q) => t1,
@@ -468,7 +470,7 @@ pub fn conditionalType(t1: Type, t2: Type) -> Either<String, Type> {
468470
}
469471
}
470472

471-
pub fn derefType(_0: Type) -> Either<String, Type> {
473+
pub fn derefType(_0: Type) -> TcResult<Type> {
472474
match (_0) {
473475
PtrType(t, _, _) => t,
474476
ArrayType(t, _, _, _) => t,
@@ -482,7 +484,7 @@ pub fn derefType(_0: Type) -> Either<String, Type> {
482484
}
483485
}
484486

485-
pub fn varAddrType(d: IdentDecl) -> Either<String, Type> {
487+
pub fn varAddrType(d: IdentDecl) -> TcResult<Type> {
486488

487489
let t = declType(d);
488490

src/lib.rs

Lines changed: 27 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,18 @@
22
//!
33
//! ```rust,no_run
44
//! extern crate parser_c;
5-
//!
5+
//!
66
//! use parser_c::parse;
7-
//!
7+
//!
88
//! const INPUT: &'static str = r#"
9-
//!
9+
//!
1010
//! int main() {
1111
//! printf("hello world!");
1212
//! return 0;
1313
//! }
14-
//!
14+
//!
1515
//! "#;
16-
//!
16+
//!
1717
//! fn main() {
1818
//! match parse(INPUT, "simple.c") {
1919
//! Err(err) => {
@@ -31,13 +31,15 @@
3131
#![feature(proc_macro)]
3232
#![feature(slice_patterns, box_syntax, box_patterns, fnbox)]
3333
#![allow(unused_parens)]
34+
// Cut down on number of warnings until we manage it.
35+
#![allow(non_snake_case, non_camel_case_types, unused_imports, unused_variables, dead_code)]
3436
#![recursion_limit="500"]
3537

3638
extern crate num;
3739
#[macro_use] extern crate matches;
38-
#[macro_use] extern crate num_derive;
40+
extern crate num_derive;
3941
extern crate parser_c_macro;
40-
#[macro_use] extern crate lazy_static;
42+
extern crate lazy_static;
4143

4244
// pub mod analysis;
4345
#[macro_use] pub mod support;
@@ -66,38 +68,28 @@ fn parseCFile<C: Preprocessor>(cpp: C,
6668
tmp_dir_opt: Option<FilePath>,
6769
args: Vec<String>,
6870
input_file: FilePath)
69-
-> Either<ParseError, CTranslUnit> {
71+
-> Result<CTranslUnit, ParseError> {
7072

7173
let handleCppError = |_0| match (_0) {
72-
Left(exitCode) => __error!(__op_addadd("Preprocessor failed with ".to_string(), show(exitCode))),
73-
Right(ok) => ok,
74+
Err(exitCode) => __error!(format!("Preprocessor failed with {}", exitCode)),
75+
Ok(ok) => ok,
7476
};
7577

76-
/*do*/
77-
{
78-
let input_stream = if !isPreprocessed(input_file.clone().into()) {
79-
{
80-
let cpp_args = __assign!((rawCppArgs(args, input_file.clone())), {
81-
cppTmpDir: tmp_dir_opt
82-
});
83-
84-
handleCppError(runPreprocessor(cpp, cpp_args))
85-
}
86-
} else {
87-
readInputStream(input_file.clone())
88-
};
89-
90-
parseC(input_stream, (initPos(input_file)))
91-
}
92-
}
78+
let input_stream = if !isPreprocessed(input_file.clone().into()) {
79+
let cpp_args = __assign!((rawCppArgs(args, input_file.clone())), {
80+
cppTmpDir: tmp_dir_opt
81+
});
9382

94-
fn parseCFilePre(file: FilePath) -> Either<ParseError, CTranslUnit> {
95-
/*do*/
96-
{
97-
let input_stream = readInputStream(file.clone());
83+
handleCppError(runPreprocessor(cpp, cpp_args))} else {
84+
readInputStream(input_file.clone())
85+
};
86+
87+
parseC(input_stream, initPos(input_file))
88+
}
9889

99-
parseC(input_stream, (initPos(file)))
100-
}
90+
fn parseCFilePre(file: FilePath) -> Result<CTranslUnit, ParseError> {
91+
let input_stream = readInputStream(file.clone());
92+
parseC(input_stream, initPos(file))
10193
}
10294

10395
/// Basic public API. Accepts C source and a filename.
@@ -114,15 +106,6 @@ pub fn parse(input: &str, filename: &str) -> Result<CTranslUnit, ParseError> {
114106
thread::Builder::new().stack_size(32 * 1024 * 1024).spawn(move || {
115107
let input_stream = inputStreamFromString(input);
116108

117-
let todo = parseC(input_stream, (initPos(FilePath::from(filename))));
118-
119-
match todo {
120-
Left(err) => {
121-
Err(err)
122-
}
123-
Right(ast) => {
124-
Ok(ast)
125-
}
126-
}
109+
parseC(input_stream, (initPos(FilePath::from(filename))))
127110
}).unwrap().join().unwrap()
128-
}
111+
}

src/parser/lexer.rs

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33254,7 +33254,7 @@ pub fn alex_actions() -> Vec<Box<Fn(Position, isize, InputStream) -> P<CToken>>>
3325433254
])
3325533255
}
3325633256

33257-
pub fn readCOctal(s: String) -> Either<String, CInteger> {
33257+
pub fn readCOctal(s: String) -> Result<CInteger, String> {
3325833258
if s.chars().nth(0).unwrap() == '0' {
3325933259
if s.len() > 1 && isDigit(s.chars().nth(1).unwrap()) {
3326033260
readCInteger(OctalRepr, s[1..].to_string())
@@ -33616,16 +33616,19 @@ pub fn token_fail(errmsg: String, pos: Position, _: isize, _: InputStream) -> P<
3361633616
failP(pos, vec!["Lexical Error !".to_string(), errmsg])
3361733617
}
3361833618

33619-
pub fn token<a>(mkTok: Box<Fn(PosLength, a) -> CToken>, fromStr: Box<Fn(String) -> a>, pos: Position, len: isize, __str: InputStream) -> P<CToken> {
33619+
pub fn token<a>(mkTok: Box<Fn(PosLength, a) -> CToken>,
33620+
fromStr: Box<Fn(String) -> a>, pos: Position, len: isize, __str: InputStream) -> P<CToken> {
3362033621
__return((mkTok((pos, len), (fromStr(takeChars_str(len, __str))))))
3362133622
}
3362233623

33623-
pub fn token_plus<a>(mkTok: Box<Fn(PosLength, a) -> CToken>, fromStr: Box<Fn(String) -> Either<String, a>>, pos: Position, len: isize, __str: InputStream) -> P<CToken> {
33624+
pub fn token_plus<a>(mkTok: Box<Fn(PosLength, a) -> CToken>,
33625+
fromStr: Box<Fn(String) -> Result<a, String>>,
33626+
pos: Position, len: isize, __str: InputStream) -> P<CToken> {
3362433627
match fromStr((takeChars_str(len, __str))) {
33625-
Left(err) => {
33628+
Err(err) => {
3362633629
failP(pos, vec!["Lexical error ! ".to_string(), err])
3362733630
},
33628-
Right(ok) => {
33631+
Ok(ok) => {
3362933632
__return(mkTok((pos, len), ok))
3363033633
},
3363133634
}

src/parser/mod.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,6 @@ use parser::parser_monad::ParseError;
2828
use data::position::Position;
2929
use data::input_stream::InputStream;
3030

31-
pub fn execParser_<a: 'static>(parser: P<a>, input: InputStream, pos: Position) -> Either<ParseError, a> {
32-
match execParser(parser, input, pos, builtinTypeNames(), newNameSupply()) {
33-
Left(s) => Left(s),
34-
Right((v, _)) => Right(v)
35-
}
31+
pub fn execParser_<a: 'static>(parser: P<a>, input: InputStream, pos: Position) -> Result<a, ParseError> {
32+
execParser(parser, input, pos, builtinTypeNames(), newNameSupply()).map(|(v, _)| v)
3633
}

src/parser/parser.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41759,7 +41759,7 @@ pub fn appendDeclrAttrs(_0: Vec<CAttribute<NodeInfo>>, _1: CDeclrR) -> CDeclrR {
4175941759
CFunDeclr(parameters, __op_addadd(cattrs, newAttrs), at),
4176041760
}
4176141761
};
41762-
41762+
4176341763
CDeclrR(ident, (Reversed((__op_concat(appendAttrs(x), xs)))), asmname, cattrs, at)
4176441764
}
4176541765
},
@@ -41891,7 +41891,7 @@ pub fn happyError<a: 'static>() -> P<a> {
4189141891
parseError()
4189241892
}
4189341893

41894-
pub fn parseC(input: InputStream, initialPosition: Position) -> Either<ParseError, CTranslationUnit<NodeInfo>> {
41894+
pub fn parseC(input: InputStream, initialPosition: Position) -> Result<CTranslationUnit<NodeInfo>, ParseError> {
4189541895
execParser(translUnitP(), input, initialPosition, builtinTypeNames(), (namesStartingFrom(0)))
4189641896
.map(|x| x.0)
4189741897
}

0 commit comments

Comments
 (0)