ctree_opt.rs 35.7 KB
Newer Older
1 2 3 4 5 6 7
//! ctree_opt, an optimiser for CTree, the Stratego/XT intermediate representation.
//!
//! Since the default Stratego compiler, strj, does most optimisation on the code it outputs
//! (e.g. Java), the CTree IR is rather messy and inefficient. This program removes some of the more
//! obvious inefficiencies that were easy to do in a general purpose language. In particular, this
//! program will a light-weight symbolic execution (no function call support) to find aliases; these
//! aliases are removed which results in less matches and builds on single variables that just moves
Jeff Smits's avatar
Jeff Smits committed
8
//! terms around without progressing.
9 10 11 12 13 14
extern crate structopt;
#[macro_use]
extern crate structopt_derive;
extern crate try_from;
extern crate strs;
extern crate aterm;
15
extern crate fnv;
16 17 18 19 20 21 22 23 24

use structopt::StructOpt;

use std::path::Path;
use std::process;
use std::io as stdio;

use try_from::TryInto;

25
use fnv::{FnvHashSet, FnvHashMap};
26

27 28
use aterm::string_share::InternedString;

29 30 31 32
use strs::io;
use strs::factory::ATermFactory;
use strs::error::{Error, Result};
use strs::ctree;
33 34
use strs::ir_v1::full_ctree as ir_v1_ext;
use strs::ir_v1;
35

36 37
// TODO: Remove single variable matches when the variable isn't used afterwards

38
#[derive(Debug, StructOpt)]
39
#[structopt(name = "ctree_opt",
40 41
            about = "A program that optimises CTree, the Stratego/XT intermediate representation. ")]
struct Opt {
42 43
    #[structopt(short = "d", long = "debug", help = "Debug: don't optimize, just rearrange")]
    debug: bool,
44 45 46 47 48 49 50 51 52 53
    #[structopt(help = "Program file (CTree)")]
    program: String,
    #[structopt(help = "Output file (CTree), stdout if not present", default_value = "-")]
    output: String,
}

fn main() {
    use std::error::Error;

    let opt = Opt::from_args();
54
    match exec(&opt.program, &opt.output, opt.debug) {
55
        Err(e) => {
56
            eprintln!("{} ({})", e, e.description());
57
            process::exit(1)
58 59
        }
        Ok(()) => {}
60 61 62
    }
}

63
fn exec(program: &str, output: &str, debug: bool) -> Result<()> {
64 65 66 67 68 69
    use aterm::print::ATermWrite;
    use std::io::Write;
    // Error out if the output file already exists
    if output != "-" {
        let output: &Path = output.as_ref();
        if output.exists() {
70 71 72 73
            return Err(Error::Io(stdio::Error::new(
                stdio::ErrorKind::AlreadyExists,
                "file already exists",
            )));
74 75 76 77 78 79
        }
    }

    let factory = ATermFactory::new();
    let program = io::read_aterm(&factory, &program)?;
    let program: ctree::Module = (&program).try_into()?;
80
    let program: ir_v1_ext::Module = program.try_into()?;
81

82 83 84 85 86
    let program = if !debug {
        program.optimize(&mut ())
    } else {
        program
    };
87 88 89 90 91 92 93 94 95 96 97 98

    if output == "-" {
        println!("{}", program.to_ascii_string()?);
    } else {
        use std::fs::File;
        let mut output_file = File::create(output)?;
        write!(output_file, "{}", program.to_ascii_string()?)?;
    }

    Ok(())
}

99 100 101 102 103 104 105 106 107 108 109 110
trait CTreeOptimize {
    type Context;

    fn optimize(self, context: &mut Self::Context) -> Self;
}

// TODO: Add MaybeBoundTo
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
enum Value<'s> {
    UnBound,
    MaybeBound,
    Bound,
111
    BoundTo(InternedString<'s>),
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
}

impl<'s> Value<'s> {
    fn lub(&self, other: &Self) -> Self {
        use self::Value::*;

        match (self, other) {
            (&BoundTo(_), &Bound) => self.clone(),
            (&Bound, &BoundTo(_)) => other.clone(),
            (l, r) => if l == r { l.clone() } else { MaybeBound },
        }
    }
}

impl<'s> PartialOrd<Value<'s>> for Value<'s> {
    fn partial_cmp(&self, other: &Self) -> Option<::std::cmp::Ordering> {
        use std::cmp::Ordering;

        let lub = self.lub(other);
        match (*self == lub, *other == lub) {
            (true, true) => Some(Ordering::Equal),
            (true, false) => Some(Ordering::Greater),
            (false, true) => Some(Ordering::Less),
            (false, false) => None,
        }
    }
}

140 141
impl<'a, 's> From<&'a Option<InternedString<'s>>> for Value<'s> {
    fn from(opt: &'a Option<InternedString<'s>>) -> Self {
142 143 144 145 146 147 148
        match *opt {
            None => Value::Bound,
            Some(name) => Value::BoundTo(name),
        }
    }
}

149
#[derive(Debug, Clone, PartialEq, Eq)]
150
struct Scope<'s> {
151 152
    strategy: FnvHashMap<InternedString<'s>, (::std::result::Result<FnvHashSet<InternedString<'s>>, DynamicCall>, usize)>,
    term: FnvHashMap<InternedString<'s>, Value<'s>>,
153
    is_overlay: bool,
154
    is_unbound_overlay: bool,
155 156 157
}

impl<'s> Scope<'s> {
158 159
    fn from_args<I1, I2>(no_of_scopes: usize, sargs: I1, targs: I2) -> Self
        where
160 161
            I1: IntoIterator<Item = InternedString<'s>>,
            I2: IntoIterator<Item = InternedString<'s>>,
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
    {
        Scope {
            term: targs
                .into_iter()
                .map(|targ| (targ, Value::UnBound))
                .collect(),
            strategy: sargs.into_iter()
                .map(|sarg| {
                    (sarg, (Ok(FnvHashSet::default()), no_of_scopes))
                })
                .collect(),
            is_overlay: false,
            is_unbound_overlay: false,
        }
    }

178 179
    fn from_let_defs<'a, I>(no_of_scopes: usize, defs: I) -> Self
    where
180
        I: IntoIterator<Item = &'a ir_v1::Def<'s>>,
181 182 183 184 185 186 187 188 189 190
        's: 'a,
    {
        Scope {
            term: FnvHashMap::default(),
            strategy: defs.into_iter()
                .map(|def| {
                    (def.name, (match_vars_in_strategy(&def.body), no_of_scopes))
                })
                .collect(),
            is_overlay: false,
191
            is_unbound_overlay: false,
192 193 194 195 196
        }
    }

    fn from_fresh_variables<I>(fresh_vars: I) -> Self
    where
197
        I: IntoIterator<Item = InternedString<'s>>,
198 199 200 201 202 203 204 205
    {
        Scope {
            term: fresh_vars
                .into_iter()
                .map(|fresh_var| (fresh_var, Value::UnBound))
                .collect(),
            strategy: FnvHashMap::default(),
            is_overlay: false,
206
            is_unbound_overlay: false,
207 208 209 210 211 212 213 214
        }
    }

    fn overlay() -> Self {
        Scope {
            term: FnvHashMap::default(),
            strategy: FnvHashMap::default(),
            is_overlay: true,
215 216 217 218 219 220 221 222 223 224
            is_unbound_overlay: false,
        }
    }

    fn unbound_overlay() -> Self {
        Scope {
            term: FnvHashMap::default(),
            strategy: FnvHashMap::default(),
            is_overlay: true,
            is_unbound_overlay: true,
225 226 227 228
        }
    }
}

229
#[derive(Debug, Clone, PartialEq, Eq)]
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
struct Scopes<'s>(Vec<Scope<'s>>);

impl<'s> Scopes<'s> {
    fn push_scope(&mut self, scope: Scope<'s>) {
        self.0.push(scope);
    }

    fn pop_scope(&mut self) -> Scope<'s> {
        self.0.pop().expect(
            "pop_scope: Interpreter bug, unexpected end of stack",
        )
    }

    fn push_overlay(&mut self) {
        self.0.push(Scope::overlay())
    }

247 248
    fn push_unbound_overlay(&mut self) {
        self.0.push(Scope::unbound_overlay())
249 250
    }

251
    fn get_term(&self, term_name: InternedString<'s>) -> Option<Value<'s>> {
252 253 254
        let mut found_unbound_overlay = false;
        for scope in self.0.iter().rev() {
            found_unbound_overlay |= scope.is_unbound_overlay;
255
            if let Some(value) = scope.term.get(&term_name) {
256 257 258 259 260 261 262 263 264 265
                if found_unbound_overlay && *value == Value::UnBound {
                    return Some(Value::MaybeBound);
                } else {
                    return Some(value.clone());
                }
            }
        }
        None
    }

266
    fn apply_strategy(&mut self, strat_name: InternedString<'s>) {
267 268 269 270
        let (vars, no_of_scopes) = {
            let opt = self.0
                .iter()
                .rev()
271
                .flat_map(|scope| scope.strategy.get(&strat_name))
272 273 274
                .cloned()
                .next();
            if opt.is_none() {
275
                eprintln!("> Cannot find strategy {}", strat_name);
276 277 278 279
                return;
            }
            opt.unwrap()
        };
280 281 282 283 284 285 286 287 288 289 290
        if vars == Err(DynamicCall) {
            conservative_maybe_bind(self);
            return;
        }
        let vars = vars.unwrap();
        for var in vars {
            let mut offset = None;
            for (n, scope) in self.0.iter().enumerate().rev().skip(self.0.len() - no_of_scopes).clone() {
                if offset == None && scope.is_overlay {
                    offset = Some(n);
                }
291
                if scope.term.get(&var) == Some(&Value::UnBound) {
292 293 294 295 296 297 298 299 300 301
                    offset = Some(offset.unwrap_or(n));
                    break;
                }
            }
            self.0[offset.expect("Term name was not found in any scope!")]
                .term
                .insert(var, Value::MaybeBound);
        }
    }

302
    fn set_term(&mut self, term_name: InternedString<'s>, value: Value<'s>) {
303
        for scope in self.0.iter_mut().rev() {
304
            if scope.term.contains_key(&term_name) || scope.is_overlay {
305 306 307 308 309 310 311 312
                scope.term.insert(term_name, value);
                return;
            }
        }
        unreachable!(format!("Name {} was not found in any scope!", term_name));
    }
}

313
impl<'s> CTreeOptimize for ir_v1_ext::Module<'s> {
314 315 316
    type Context = ();

    fn optimize(self, _: &mut Self::Context) -> Self {
317
        use ir_v1_ext::Module::*;
318

319 320
        // eprintln!("CTreeOptimize::optimize(Module, _)");

321 322 323 324 325 326
        match self {
            Module(name, decls) => {
                Module(
                    name,
                    decls
                        .into_iter()
327
                        .map(|d| d.optimize(&mut ()))
328 329 330 331 332 333 334
                        .collect(),
                )
            }
            Specification(decls) => {
                Specification(
                    decls
                        .into_iter()
335
                        .map(|d| d.optimize(&mut ()))
336 337 338 339 340 341 342
                        .collect(),
                )
            }
        }
    }
}

343
impl<'s> CTreeOptimize for ir_v1_ext::Decl<'s> {
344 345 346
    type Context = ();

    fn optimize(self, _: &mut Self::Context) -> Self {
347
        use ir_v1_ext::Decl::*;
348

349 350
        // eprintln!("CTreeOptimize::optimize(Decl, _)");

351 352 353 354 355
        match self {
            Imports(import_names) => Imports(import_names),
            Strategies(defs) => {
                Strategies(
                    defs.into_iter()
356
                        .map(|d| d.optimize(&mut ()))
357 358 359 360 361 362 363 364
                        .collect(),
                )
            }
            Signature(sdecls) => Signature(sdecls),
        }
    }
}

365
impl<'s> CTreeOptimize for ir_v1_ext::Def<'s> {
366 367 368
    type Context = ();

    fn optimize(self, _: &mut Self::Context) -> Self {
369
        use ir_v1_ext::Def::*;
370

371 372
        // eprintln!("CTreeOptimize::optimize(Def, _)");

373 374
        match self {
            SDefT(name, sargs, targs, strat) => {
375
                let mut context = (None, Scopes(vec![Scope::from_args(0, sargs.iter().map(|vd| vd.0), targs.iter().map(|vd| vd.0))]));
376
                SDefT(name, sargs, targs, strat.optimize(&mut context))
377 378
            }
            ExtSDefInl(name, sargs, targs, strat) => {
379
                let mut context = (None, Scopes(vec![Scope::from_args(0, sargs.iter().map(|vd| vd.0), targs.iter().map(|vd| vd.0))]));
380
                ExtSDefInl(name, sargs, targs, strat.optimize(&mut context))
381 382 383 384 385 386 387
            }
            ExtSDef(name, sargs, targs) => ExtSDef(name, sargs, targs),
            AnnoDef(annos, def) => AnnoDef(annos, Box::new(def.optimize(&mut ()))),
        }
    }
}

388
impl<'s> CTreeOptimize for ir_v1::Def<'s> {
389
    type Context = (Option<InternedString<'s>>, Scopes<'s>);
390 391 392 393

    fn optimize(mut self, c: &mut Self::Context) -> Self {
        // eprintln!("CTreeOptimize::optimize(\"LetDef\", _)");

394 395 396
        let no_of_scopes = (c.1).0.len();

        // TODO: reevaluate this from_args call.
397
        // It gives an empty set of influenced variable to the sargs, which probably not correct at
398 399 400
        //  this point. The closure given as sarg to this strategy could be made before this one,
        //  which would make it able to change variables that this Def would be able to observe. 
        c.1.push_scope(Scope::from_args(no_of_scopes, self.sargs.iter().map(|&s| s), self.targs.iter().map(|&s| s)));
401 402 403 404 405 406 407
        self.body = self.body.optimize(c);
        c.1.pop_scope();

        self
    }
}

408
fn conservative_maybe_bind<'s>(scopes: &mut Scopes<'s>) {
409 410 411 412 413
    for scope in scopes.0.iter_mut().rev() {
        if scope.is_overlay {
            scope.is_unbound_overlay = true;
            break;
        }
414 415 416 417 418 419 420 421 422 423
        for v in scope.term.values_mut() {
            if *v == Value::UnBound {
                *v = Value::MaybeBound
            }
        }
    }
}

fn conservative_maybe_bind2<'s, I>(scopes: &mut Scopes<'s>, affected_names: I)
where
424
    I: IntoIterator<Item=InternedString<'s>>,
425 426
{
    for name in affected_names {
427 428
        if scopes.get_term(name) == Some(Value::UnBound) {
            scopes.set_term(name, Value::MaybeBound);
429 430 431 432 433
        }
    }
}

// Pay attention, this is where the optimizing starts
434
impl<'s> CTreeOptimize for ir_v1::Strategy<'s> {
435
    type Context = (Option<InternedString<'s>>, Scopes<'s>);
436 437

    fn optimize(self, mut c: &mut Self::Context) -> Self {
438 439 440
        use ir_v1::Strategy;
        use ir_v1::MatchTerm;
        use ir_v1::BuildTerm;
441 442

        match self {
443
            Strategy::Let(defs, body) => {
444
                // eprintln!("CTreeOptimize::optimize(Strategy::Let, _)");
445 446
                let no_of_scopes = (c.1).0.len() + 1;
                c.1.push_scope(Scope::from_let_defs(no_of_scopes, &defs));
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461

                let cur = c.0.clone();
                let defs: Vec<_> = defs.into_iter().map(|d| {
                    // The context of the closures is like the one here except we don't know what
                    //  happened to the unbound variables by the time this sarg is actually called
                    c.1.push_unbound_overlay();
                    // Nor do we know anything about the current term anymore
                    c.0 = None;
                    let result = d.optimize(c);
                    c.1.pop_scope();

                    result
                }).collect();
                c.0 = cur;

462 463 464 465
                let result = Strategy::Let(defs, Box::new(body.optimize(c)));
                c.1.pop_scope();
                result
            }
466
            Strategy::CallT(name, sargs, targs) => {
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
                // eprintln!("CTreeOptimize::optimize(Strategy::CallT, _)");
                let cur = c.0.clone();
                let sargs: Vec<_> = sargs.into_iter().map(|s| {
                    // The context of the closures is like the one here except we don't know what
                    //  happened to the unbound variables by the time this sarg is actually called
                    c.1.push_unbound_overlay();
                    // Nor do we know anything about the current term anymore
                    c.0 = None;
                    let result = s.optimize(c);
                    c.1.pop_scope();

                    result
                }).collect();
                c.0 = cur;

                // We need to find all affected (and relevant) variables in the closures
483 484 485 486 487 488 489
                match sargs.iter().map(match_vars_in_strategy).collect() {
                    Err(DynamicCall) => {
                        conservative_maybe_bind(&mut c.1);
                    }
                    Ok(affected_names) => {
                        let affected_names: Vec<_> = affected_names;
                        c.1.apply_strategy(name);
490 491
                        // All affected `UnBound` names will now have the conservative MaybeBound
                        //  since we don't know if and when the sargs are called
492 493 494
                        conservative_maybe_bind2(&mut c.1, affected_names.into_iter().flat_map(|s| s));
                    }
                }
495 496 497 498 499
                // We also don't know the return value of the call
                c.0 = None;
                Strategy::CallT(name, sargs, targs)
            }
            Strategy::CallDynamic(name, sargs, targs) => {
500
                // eprintln!("CTreeOptimize::optimize(Strategy::CallDynamic, _)");
501 502
                // We cannot resolve the name of the strategy during symbolic execution
                // So bail out with conservative everything
503 504 505 506 507 508 509
                conservative_maybe_bind(&mut c.1);
                c.0 = None;
                Strategy::CallDynamic(name, sargs, targs)
            }
            Strategy::Fail => Strategy::Fail,
            Strategy::Id => Strategy::Id,
            Strategy::Match(mt) => {
510
                // eprintln!("CTreeOptimize::optimize(Strategy::Match, _)");
511 512
                // If we match against a single variable...
                if let MatchTerm::Var(v) = mt {
513
                    // eprintln!("\tSingle var match ({})...", v);
514
                    // ...and it's guaranteed to be UnBound at this point...
515 516
                    if c.1.get_term(v) == Some(Value::UnBound) {
                        // eprintln!("\t...var is unbound...");
517
                        // ...we set the name to be bound to what the current value is
518
                        c.1.set_term(v, (&c.0).into());
519 520 521
                        // if the current value is also a known binding, we've found an alias
                        //  that we can eliminate
                        if c.0.is_some() {
522
                            // eprintln!("\t...{} is an alias for {}!", v, c.0.unwrap());
523
                            return Strategy::Id;
Jeff Smits's avatar
Jeff Smits committed
524
                        } else {
525
                            // eprintln!("\t...{} is the new alias for the curren term", v);
Jeff Smits's avatar
Jeff Smits committed
526 527
                            // Otherwise the current is now a known binding
                            c.0 = Some(v);
528 529 530 531 532 533 534
                        }
                    }
                }
                // We optimize match patterns by replacing variables when they are aliases
                Strategy::Match(mt.optimize(c))
            }
            Strategy::Build(bt) => {
535
                // eprintln!("CTreeOptimize::optimize(Strategy::Build, _)");
536 537 538 539
                // We optimize build patterns by replacing variables when they are aliases
                let bt = bt.optimize(c);
                // If we build a single variable...
                if let BuildTerm::Var(v) = bt {
540
                    // eprintln!("\tSingle var build ({})...", v);
541
                    // ...and the variable is guaranteed to be bound at this point
542
                    match c.1.get_term(v) {
543 544
                        Some(Value::Bound) => {
                            // eprintln!("\t...var is bound");
545 546 547 548 549 550
                            // ...we record that the current term is also this known binding
                            c.0 = Some(v);
                            return Strategy::Build(bt);
                        }
                        // Note that we don't need to handle BoundTo because that would have
                        //  been an alias that was replace by the optimize call
551
                        _ => {}// eprintln!("\t...var is guaranteed to be bound");}
552 553 554 555 556 557 558 559
                    }
                }
                // If the build is not a single variable or a possibly unbound variable, we
                //  don't know for sure if the current term is also known as a variable
                c.0 = None;
                Strategy::Build(bt)
            }
            Strategy::Scope(mut names, body) => {
560
                // eprintln!("CTreeOptimize::optimize(Strategy::Scope, _)");
561 562 563 564 565
                c.1.push_scope(Scope::from_fresh_variables(names.iter().map(|&s| s)));

                let new_body = body.optimize(&mut c);

                let mut scope = c.1.pop_scope();
566 567

                // cull scoped names that we found to be aliases
568
                scope.term.retain(|_, v| match *v {
569 570 571
                    Value::BoundTo(_) => true,
                    _ => false,
                });
572
                names.retain(|s| !scope.term.contains_key(s));
573 574 575 576

                Strategy::Scope(names, Box::new(new_body))
            }
            Strategy::Seq(strats) => {
577 578
                // eprintln!("CTreeOptimize::optimize(Strategy::Seq, _)");
                // eprintln!("\tstrats.len() = {}", strats.len());
579
                // NOTE side-effecting optimize call in the map!
580
                let strats: Vec<_> = strats.into_vec().into_iter()
581 582 583
                    .map(|s| s.optimize(c))
                    // Identity strategies in a sequence don't do anything
                    // (These may be eliminated `Match`es of aliases)
584
                    .filter(|s| *s != Strategy::Id).collect();
585 586 587 588 589 590 591 592

                // Once the collect call is made the ids are dealt with
                // Now we remove double builds if the first one cannot fail
                let mut strats = strats.into_iter().peekable();
                let mut strats2 = Vec::new();
                while let Some(strat) = strats.next() {
                    match strat {
                        Strategy::Fail => {
593
                            // eprintln!("\tFail => early break");
594 595 596 597 598 599
                            // A fail in a sequence will always end the sequence, so drop the
                            //  dead code after this strategy
                            strats2.push(strat);
                            break;
                        }
                        Strategy::Build(ref bt) => {
600
                            // eprintln!("\tBuild...");
601 602
                            // When all variables in the build term are definitely bound...
                            if all_vars_bound(bt, &c.1) {
603
                                // eprintln!("\t...second Build...");
604 605
                                // ...and the next strategy is also a `Build`
                                if let Some(&Strategy::Build(_)) = strats.peek() {
606
                                    // eprintln!("\t...yup dropping it");
607 608 609 610 611 612 613 614 615
                                    continue;
                                }
                            }
                        }
                        _ => {}
                    }
                    strats2.push(strat);
                }

Jeff Smits's avatar
Jeff Smits committed
616
                if strats2.is_empty() {
617
                    // eprintln!("\tNo strats left in Seq");
Jeff Smits's avatar
Jeff Smits committed
618 619 620 621
                    Strategy::Id
                } else {
                    Strategy::Seq(strats2.into_boxed_slice())
                }
622 623
            }
            Strategy::GuardedLChoice(pairs, final_else) => {
624
                // eprintln!("CTreeOptimize::optimize(Strategy::GuardedLChoice, _)");
625 626 627 628 629
                use std::rc::Rc;

                let mut cs = Vec::with_capacity(pairs.len());
                // Optimize each branch with a separate context
                let mut pairs2 = Vec::with_capacity(pairs.len());
630
                let cur = c.0.clone();
631
                for (cond, then) in pairs.into_vec() {
632
                    c.1.push_overlay();
633 634 635
                    let cond = cond.optimize(&mut c);
                    let then = then.optimize(&mut c);
                    pairs2.push((cond, then));
636 637
                    cs.push((c.0, c.1.pop_scope()));
                    c.0 = cur.clone();
638 639 640
                }
                // Same for final_else separately
                let final_else = {
641
                    c.1.push_overlay();
642
                    let result = (*final_else).clone().optimize(&mut c);
643 644
                    cs.push((c.0, c.1.pop_scope()));
                    c.0 = cur.clone();
645 646 647 648 649 650 651
                    result
                };
                // Merge contexts
                for copy in cs {
                    c.0 = c.0.and_then(
                        |v| if copy.0 == Some(v) { Some(v) } else { None },
                    );
652 653 654
                    for (key, value) in copy.1.term {
                        let new_value = c.1.get_term(key).map(|v| v.lub(&value)).unwrap_or(value);
                        c.1.set_term(key, new_value);
655 656 657 658 659
                    }
                }
                Strategy::GuardedLChoice(pairs2.into_boxed_slice(), Rc::new(final_else))
            }
            Strategy::ConsMatch(map, final_else) => {
660
                // eprintln!("CTreeOptimize::optimize(Strategy::ConsMatch, _)");
661 662 663 664
                use std::rc::Rc;

                let mut cs = Vec::with_capacity(map.len());
                // Optimize each branch with a separate context
665 666 667 668 669 670 671 672 673 674
                let cur = c.0.clone();
                let map = map.into_iter()
                    .map(|(cons, strat)| {
                        c.1.push_overlay();
                        let strat = strat.optimize(&mut c);
                        cs.push((c.0, c.1.pop_scope()));
                        c.0 = cur.clone();
                        (cons, strat)
                    })
                    .collect();
675 676
                // Same for final_else separately
                let final_else = {
677
                    c.1.push_overlay();
678
                    let result = (*final_else).clone().optimize(&mut c);
679 680
                    cs.push((c.0, c.1.pop_scope()));
                    c.0 = cur.clone();
681 682 683 684 685 686 687
                    result
                };
                // Merge contexts
                for copy in cs {
                    c.0 = c.0.and_then(
                        |v| if copy.0 == Some(v) { Some(v) } else { None },
                    );
688 689 690
                    for (key, value) in copy.1.term {
                        let new_value = c.1.get_term(key).map(|v| v.lub(&value)).unwrap_or(value);
                        c.1.set_term(key, new_value);
691 692 693 694 695
                    }
                }
                Strategy::ConsMatch(map, Rc::new(final_else))
            }
            Strategy::PrimT(name, sargs, targs) => {
696
                // eprintln!("CTreeOptimize::optimize(Strategy::PrimT, _)");
697 698 699 700 701 702 703 704
                if !sargs.is_empty() {
                    // We don't analyse closures, so set all guaranteed UnBound names to the
                    //  conservative MaybeBound
                    conservative_maybe_bind(&mut c.1);
                }
                Strategy::PrimT(name, sargs, targs)
            }
            Strategy::Some(sarg) => {
705
                // eprintln!("CTreeOptimize::optimize(Strategy::Some, _)");
706 707 708 709 710 711 712 713
                // We don't know an alias for what we get as the current term in `sarg`
                c.0 = None;
                let sarg = sarg.optimize(c);
                // We don't know an alias for what we get from `Some(sarg)`
                c.0 = None;
                Strategy::Some(Box::new(sarg))
            }
            Strategy::One(sarg) => {
714
                // eprintln!("CTreeOptimize::optimize(Strategy::One, _)");
715 716 717 718 719 720
                c.0 = None;
                let sarg = sarg.optimize(c);
                c.0 = None;
                Strategy::One(Box::new(sarg))
            }
            Strategy::All(sarg) => {
721
                // eprintln!("CTreeOptimize::optimize(Strategy::All, _)");
722 723 724 725 726 727
                c.0 = None;
                let sarg = sarg.optimize(c);
                c.0 = None;
                Strategy::All(Box::new(sarg))
            }
            Strategy::ImportTerm(name) => {
728
                // eprintln!("CTreeOptimize::optimize(Strategy::ImportTerm, _)");
729 730 731 732 733 734 735
                c.0 = None;
                Strategy::ImportTerm(name)
            }
        }
    }
}

736 737
fn all_vars_bound<'s>(bt: &ir_v1::BuildTerm<'s>, m: &Scopes<'s>) -> bool {
    use ir_v1::BuildTerm::*;
738 739 740 741 742 743 744

    let mut stack = vec![bt];
    let mut combined_value = Value::Bound;

    while let Some(t) = stack.pop() {
        match t {
            &Var(v) => {
745
                match m.get_term(v) {
746
                    Some(val) => {
747
                        combined_value = combined_value.lub(&val);
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
                    }
                    None => {
                        return false;
                    }
                }
            }
            &Anno(ref t1, ref t2) => {
                stack.push(&**t1);
                stack.push(&**t2);
            }
            &Int(_) | &Real(_) | &Str(_) => {}
            &Op(_, ref children) => stack.extend_from_slice(&children.iter().collect::<Vec<_>>()),
            &Explode(ref t1, ref t2) => {
                stack.push(&**t1);
                stack.push(&**t2);
            }
            &Cached(_, ref t) => stack.push(&**t),
        }
    }
    combined_value.le(&Value::Bound)
}

770
impl<'s> CTreeOptimize for ir_v1::MatchTerm<'s> {
771
    type Context = (Option<InternedString<'s>>, Scopes<'s>);
772 773

    fn optimize(self, mut c: &mut Self::Context) -> Self {
774
        use ir_v1::MatchTerm::*;
775 776 777

        match self {
            Var(v) => {
778
                if let Some(Value::BoundTo(v2)) = c.1.get_term(v) {
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
                    Var(v2)
                } else {
                    Var(v)
                }
            }
            Wld => Wld,
            Anno(term, anno) => Anno(Box::new(term.optimize(c)), Box::new(anno.optimize(c))),
            Int(i) => Int(i),
            Real(r) => Real(r),
            Str(s) => Str(s),
            Op(cons, children) => Op(cons, children.into_iter().map(|t| t.optimize(c)).collect()),
            Explode(cons_term, children_term) => {
                Explode(
                    Box::new(cons_term.optimize(c)),
                    Box::new(children_term.optimize(c)),
                )
            }
            As(v, term) => {
797
                if let Some(Value::BoundTo(v2)) = c.1.get_term(v) {
798 799 800 801 802 803 804 805 806 807
                    As(v2, Box::new(term.optimize(c)))
                } else {
                    As(v, Box::new(term.optimize(c)))
                }
            }
            Cached(cache, term) => Cached(cache, Box::new(term.optimize(c))),
        }
    }
}

808
impl<'s> CTreeOptimize for ir_v1::BuildTerm<'s> {
809
    type Context = (Option<InternedString<'s>>, Scopes<'s>);
810 811

    fn optimize(self, mut c: &mut Self::Context) -> Self {
812
        use ir_v1::BuildTerm::*;
813 814 815

        match self {
            Var(v) => {
816
                if let Some(Value::BoundTo(v2)) = c.1.get_term(v) {
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
                    Var(v2)
                } else {
                    Var(v)
                }
            }
            Anno(term, anno) => Anno(Box::new(term.optimize(c)), Box::new(anno.optimize(c))),
            Int(i) => Int(i),
            Real(r) => Real(r),
            Str(s) => Str(s),
            Op(cons, children) => Op(cons, children.into_iter().map(|t| t.optimize(c)).collect()),
            Explode(cons_term, children_term) => {
                Explode(
                    Box::new(cons_term.optimize(c)),
                    Box::new(children_term.optimize(c)),
                )
            }
            Cached(cache, term) => Cached(cache, Box::new(term.optimize(c))),
        }
    }
836
}
Jeff Smits's avatar
Jeff Smits committed
837

838 839 840 841
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
struct DynamicCall;

fn match_vars_in_strategy<'s>(
842
    strat: &ir_v1::Strategy<'s>,
843
) -> ::std::result::Result<FnvHashSet<InternedString<'s>>, DynamicCall> {
844
    use ir_v1::Strategy;
845 846 847 848 849

    match *strat {
        Strategy::Let(_, ref body) => match_vars_in_strategy(body),
        // TODO: add vars from Call
        Strategy::CallT(_, ref sargs, _) => {
850
            let result = sargs.iter().map(match_vars_in_strategy).collect::<::std::result::Result<Vec<FnvHashSet<InternedString<'s>>>, DynamicCall>>()?;
851 852 853 854 855 856 857 858
            Ok(result.into_iter().flat_map(|s| s).collect())
        },
        Strategy::CallDynamic(_, _, _) => Err(DynamicCall),
        Strategy::Fail => Ok(FnvHashSet::default()),
        Strategy::Id => Ok(FnvHashSet::default()),
        Strategy::Match(ref term) => Ok(match_vars(term)),
        Strategy::Build(_) => Ok(FnvHashSet::default()),
        Strategy::Scope(ref names, ref body) => {
859
            let name_set: FnvHashSet<InternedString<'s>> = names.iter().map(|&s| s).collect();
860 861 862 863 864 865 866 867 868
            match match_vars_in_strategy(body) {
                Ok(mut v) => {
                    v.retain(|n| !name_set.contains(n));
                    Ok(v)
                }
                Err(e) => Err(e),
            }
        }
        Strategy::Seq(ref strats) => {
869
            let result = strats.iter().map(match_vars_in_strategy).collect::<::std::result::Result<Vec<FnvHashSet<InternedString<'s>>>, DynamicCall>>()?;
870 871 872 873 874 875 876 877
            Ok(result.into_iter().flat_map(|s| s).collect())
        },
        Strategy::GuardedLChoice(ref pairs, ref s_else) => {
            let pairs_names = pairs
                .iter()
                .map(|&(ref s_if, ref s_then)| {
                    let one = match_vars_in_strategy(s_if)?;
                    let two = match_vars_in_strategy(s_then)?;
878
                    Ok(one.union(&two).map(|&s| s).collect::<FnvHashSet<InternedString<'s>>>())
879
                })
880 881
                .collect::<::std::result::Result<Vec<FnvHashSet<InternedString<'s>>>, DynamicCall>>()?;
            let pairs_names: FnvHashSet<InternedString<'s>> = pairs_names.into_iter().flat_map(|s| s).collect();
882 883 884
            Ok(pairs_names.union(&match_vars_in_strategy(s_else)?).map(|&s| s).collect())
        }
        Strategy::ConsMatch(ref map, _) => {
885
            let result = map.values().map(match_vars_in_strategy).collect::<::std::result::Result<Vec<FnvHashSet<InternedString<'s>>>, DynamicCall>>()?;
886 887 888
            Ok(result.into_iter().flat_map(|s| s).collect())
        },
        Strategy::PrimT(_, ref sargs, _) => {
889
            let result = sargs.iter().map(match_vars_in_strategy).collect::<::std::result::Result<Vec<FnvHashSet<InternedString<'s>>>, DynamicCall>>()?;
890 891 892 893 894 895 896 897 898
            Ok(result.into_iter().flat_map(|s| s).collect())
        },
        Strategy::Some(ref s) => match_vars_in_strategy(s),
        Strategy::One(ref s) => match_vars_in_strategy(s),
        Strategy::All(ref s) => match_vars_in_strategy(s),
        Strategy::ImportTerm(_) => Ok(FnvHashSet::default()),
    }
}

899 900
fn match_vars<'s>(term: &ir_v1::MatchTerm<'s>) -> FnvHashSet<InternedString<'s>> {
    use ir_v1::MatchTerm;
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935

    let mut result = FnvHashSet::default();
    let mut stack = vec![term];
    while let Some(term) = stack.pop() {
        match *term {
            MatchTerm::Var(v) => {
                result.insert(v);
            }
            MatchTerm::Int(_) |
            MatchTerm::Real(_) |
            MatchTerm::Str(_) |
            MatchTerm::Wld => {}
            MatchTerm::Anno(ref t1, ref t2) => {
                stack.push(&**t1);
                stack.push(&**t2);
            }
            MatchTerm::Op(_, ref ts) => {
                for t in ts {
                    stack.push(t);
                }
            }
            MatchTerm::Explode(ref t1, ref t2) => {
                stack.push(&**t1);
                stack.push(&**t2);
            }
            MatchTerm::As(v, ref t) => {
                result.insert(v);
                stack.push(&**t);
            }
            MatchTerm::Cached(_, _) => {}
        }
    }
    result
}

Jeff Smits's avatar
Jeff Smits committed
936 937 938 939 940 941 942 943
#[cfg(test)]
mod test {
    use super::*;
    use aterm::parse::ATermRead;
    use aterm::print::ATermWrite;

    fn string_optimize(program: &'static str) -> String {
        let factory = ATermFactory::new();
944 945 946 947
        let program = factory
            .read_ascii_string(&program)
            .expect("ATerm representation of CTree")
            .0;
Jeff Smits's avatar
Jeff Smits committed
948
        let program: ctree::Module = (&program).try_into().expect("Typed CTree");
949
        let program: ir_v1_ext::Module = program.try_into().expect("Preprocessed CTree");
Jeff Smits's avatar
Jeff Smits committed
950 951 952 953 954 955 956 957 958 959 960 961 962

        let program = program.optimize(&mut ());

        program.to_ascii_string().expect("Printed CTree")
    }

    // Based on example-inputs/term_wrap.str
    #[test]
    fn term_wrap() {
        let input = r#"Specification([Signature([Constructors([OpDecl("Nil",ConstType(Sort("Term",[]))),OpDecl("Cons",FunType([ConstType(Sort("Term",[])),ConstType(Sort("Term",[]))],ConstType(Sort("Term",[]))))])]),Strategies([SDefT("main_0_0",[],[],Scope(["k_0","l_0"],Seq(Match(Var("l_0")),Seq(Match(Var("k_0")),Seq(Build(Var("l_0")),Build(Anno(Op("Cons",[Var("k_0"),Anno(Op("Nil",[]),Op("Nil",[]))]),Op("Nil",[]))))))))])])"#;
        let expected = r#"Specification([Signature([Constructors([OpDecl("Nil",ConstType(Sort("Term",[]))),OpDecl("Cons",FunType([ConstType(Sort("Term",[])),ConstType(Sort("Term",[]))],ConstType(Sort("Term",[]))))])]),Strategies([SDefT("main_0_0",[],[],Scope(["l_0"],Seq(Match(Var("l_0")),Build(Anno(Op("Cons",[Var("l_0"),Anno(Op("Nil",[]),Op("Nil",[]))]),Op("Nil",[]))))))])])"#;
        assert_eq!(expected, string_optimize(input));
    }
963
}