<commit_before>//
//   Copyright 2016 Andrew Hunter
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//

//!
//! # DFA compiler
//!
//! The DFA compiler converts NDFAs into DFAs, using a DFA builder.
//!

use std::marker::PhantomData;
use std::collections::HashSet;
use std::collections::HashMap;
use std::iter::*;
use std::cmp::Ordering;

use super::dfa_builder::*;
use super::state_machine::*;

///
/// Builds a deterministic finite automaton from a NDFA
///
pub struct DfaCompiler<InputSymbol: PartialOrd+Clone, OutputSymbol, DfaType, Ndfa: StateMachine<InputSymbol, OutputSymbol>, Builder: DfaBuilder<InputSymbol, OutputSymbol, DfaType>> {
    /// State machine that is to be compiled
    ndfa: Ndfa,

    /// Builder where the state machine should be generated
    builder: Builder,

    // Phantom data to poke Rust's type system (it's too dumb to see that InputSymbol is used in both Ndfa and Builder there via the type constraint)
    #[allow(dead_code)]
    phantom: (PhantomData<InputSymbol>, PhantomData<OutputSymbol>, PhantomData<DfaType>)
}

/// Represents a state in the DFA (one or more states from the source)
#[derive(Eq, PartialEq, Hash, Clone)]
struct DfaState {
    /// List of the states from the NDFA that make up this DFA state (will be ordered if `dedupe` is called)
    source_states: Vec<StateId>
}

impl DfaState {
    /// Creates a DFA state from a set of source states
    fn create(source_states: Vec<StateId>) -> DfaState {
        let mut set = HashSet::new();
        for state in source_states {
            set.insert(state);
        }

        DfaState { source_states: Vec::from_iter(set.into_iter()) }
    }

    /// Removes any duplicate states from source_states
    fn dedupe(&mut self) {
        self.source_states.sort();
        self.source_states.dedup();
    }
}

/// Represents the transitions for a source state
struct DfaTransitions<InputSymbol, OutputSymbol: Ord> {
    /// ID of this state in the resulting DFA
    state_id: StateId,

    /// Transitions for this state (will be unique if `merge_states` is called)
    transitions: Vec<(InputSymbol, DfaState)>,

    /// The output symbols for this state (empty if this is not an accepting state)
    output: Vec<OutputSymbol>
}

impl<InputSymbol: PartialOrd+Clone, OutputSymbol: Ord> DfaTransitions<InputSymbol, OutputSymbol> {
    /// Goes through the transitions in the object and merges the states of any with the same symbol
    fn merge_states(&mut self) {
        if self.transitions.len() > 0 {
            // Order the transitions so that if two transitions have the same input symbol, they are neighbours
            self.transitions.sort_by(|a, b| {
                let &(ref symbol_a, _) = a;
                let &(ref symbol_b, _) = b;

                if let Some(result) = symbol_a.partial_cmp(symbol_b) {
                    result
                } else {
                    // Unordered input symbols won't work well
                    Ordering::Equal
                }
            });

            // For any transition that has a duplicate state, combine it with the previous state
            let mut new_transitions = vec![];
            new_transitions.push(self.transitions[0].clone());

            for transit_idx in 1..self.transitions.len() {
                let len          = new_transitions.len();
                let this_transit = &mut self.transitions[transit_idx];

                if new_transitions[len-1].0 == this_transit.0 {
                    // Same symbol: expand this state
                    new_transitions[len-1].1.source_states.append(&mut this_transit.1.source_states);
                } else {
                    // Different symbol: add new state
                    new_transitions.push(this_transit.clone());
                }
            }

            // Ensure all of the states are sorted and de-duplicated
            for transit in &mut new_transitions {
                transit.1.dedupe();
            }

            // Update the transitions
            self.transitions = new_transitions;
        }
    }

    ///
    /// Finds the output symbol that corresponds to this state
    ///
    /// Rule is that if there is more than one output symbol then the symbol whose value is ordered lowest is the output for this state
    ///
    fn output_symbol(&mut self) -> Option<&OutputSymbol> {
        if self.output.len() > 0 {
            self.output.sort();
            Some(&self.output[0])
        } else {
            None
        }
    }
}

impl<InputSymbol: PartialOrd+Clone, OutputSymbol: Ord+Clone, DfaType, Ndfa: StateMachine<InputSymbol, OutputSymbol>, Builder: DfaBuilder<InputSymbol, OutputSymbol, DfaType>>
    DfaCompiler<InputSymbol, OutputSymbol, DfaType, Ndfa, Builder> {
    ///
    /// Builds a DFA using an NDFA and a builder
    ///
    pub fn build(ndfa: Ndfa, builder: Builder) -> DfaType {
        let compiler = DfaCompiler::new(ndfa, builder);
        compiler.compile()
    }

    ///
    /// Creates a new DFA compiler using a particular builder and NDFA
    ///
    pub fn new(ndfa: Ndfa, builder: Builder) -> Self {
        DfaCompiler { ndfa: ndfa, builder: builder, phantom: (PhantomData, PhantomData, PhantomData) }
    }

    ///
    /// Compiles the NDFA into a DFA
    ///
    pub fn compile(self) -> DfaType {
        // We assume that input symbols are non-overlapping, which is not automatically the case for symbol ranges

        // Work out the state mapping for each input symbol
        let mut states       = vec![];
        let mut known_states = HashMap::new();
        let mut to_process   = vec![];

        // All state machines have state 0 as their starting state
        let state_zero = DfaState::create(vec![0]);

        known_states.insert(state_zero.clone(), 0);
        to_process.push(state_zero);

        while let Some(state) = to_process.pop() {
            // Create a new transitions object for this state
            let mut transitions = vec![];
            let mut output      = vec![];

            for source_state in &state.source_states {
                let source_transitions = self.ndfa.get_transitions_for_state(*source_state);

                for (symbol, state) in source_transitions {
                    transitions.push((symbol, DfaState::create(vec![state])));
                }

                if let Some(source_output) = self.ndfa.output_symbol_for_state(*source_state) {
                    output.push(source_output.clone());
                }
            }

            // Merge it so that we only have one transition per symbol
            let mut dfa_transitions = DfaTransitions { state_id: states.len() as StateId, transitions: transitions, output: output };
            dfa_transitions.merge_states();

            // Process any generated states that are not already in the DFA
            for &(_, ref maybe_new_state) in &dfa_transitions.transitions {
                if !known_states.contains_key(maybe_new_state) {
                    to_process.push(maybe_new_state.clone());
                }
            }

            // Store the new state
            known_states.insert(state.clone(), dfa_transitions.state_id);
            states.push(dfa_transitions);
        }

        // Build the DFA
        let mut builder = self.builder;

        for mut dfa_state in states {
            builder.start_state();

            if let Some(output_symbol) = dfa_state.output_symbol() {
                builder.accept(output_symbol.clone());
            }

            for (symbol, target_state) in dfa_state.transitions {
                builder.transition(symbol, known_states[&target_state]);
            }
        }

        // Generate the final DFA
        builder.build()
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use super::super::regular_pattern::*;
    use super::super::state_machine::*;
    use super::super::symbol_range_dfa::*;
    use super::super::pattern_matcher::*;
    use super::super::symbol_reader::*;

    #[test]
    fn can_create_compiler() {
        let ndfa     = "abc".into_pattern().to_ndfa("success");
        let builder  = SymbolRangeDfaBuilder::new();

        DfaCompiler::new(ndfa, builder);
    }

    #[test]
    fn can_build_dfa() {
        // Generate a state machine from the "abc" pattern
        let ndfa     = "abc".into_pattern().to_ndfa("Success");
        let builder  = SymbolRangeDfaBuilder::new();

        let state_machine = DfaCompiler::build(ndfa, builder);

        // Read back 'abc' manually
        let mut state = More(state_machine.start());
        let mut input = "abc".read_symbols();

        while let More(this_state) = state {
            let next_state =
                if let Some(next_char) = input.next_symbol() {
                    this_state.next(next_char)
                } else {
                    this_state.finish()
                };

            state = next_state;
        }

        // Check for acceptance
        if let Accept(count, output) = state {
            assert!(count == 3);
            assert!(output == &"Success");
        } else {
            assert!(false);
        }
    }
}
<commit_msg>Also test a DFA with two ranges the same<commit_after>//
//   Copyright 2016 Andrew Hunter
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//

//!
//! # DFA compiler
//!
//! The DFA compiler converts NDFAs into DFAs, using a DFA builder.
//!

use std::marker::PhantomData;
use std::collections::HashSet;
use std::collections::HashMap;
use std::iter::*;
use std::cmp::Ordering;

use super::dfa_builder::*;
use super::state_machine::*;

///
/// Builds a deterministic finite automaton from a NDFA
///
pub struct DfaCompiler<InputSymbol: PartialOrd+Clone, OutputSymbol, DfaType, Ndfa: StateMachine<InputSymbol, OutputSymbol>, Builder: DfaBuilder<InputSymbol, OutputSymbol, DfaType>> {
    /// State machine that is to be compiled
    ndfa: Ndfa,

    /// Builder where the state machine should be generated
    builder: Builder,

    // Phantom data to poke Rust's type system (it's too dumb to see that InputSymbol is used in both Ndfa and Builder there via the type constraint)
    #[allow(dead_code)]
    phantom: (PhantomData<InputSymbol>, PhantomData<OutputSymbol>, PhantomData<DfaType>)
}

/// Represents a state in the DFA (one or more states from the source)
#[derive(Eq, PartialEq, Hash, Clone)]
struct DfaState {
    /// List of the states from the NDFA that make up this DFA state (will be ordered if `dedupe` is called)
    source_states: Vec<StateId>
}

impl DfaState {
    /// Creates a DFA state from a set of source states
    fn create(source_states: Vec<StateId>) -> DfaState {
        let mut set = HashSet::new();
        for state in source_states {
            set.insert(state);
        }

        DfaState { source_states: Vec::from_iter(set.into_iter()) }
    }

    /// Removes any duplicate states from source_states
    fn dedupe(&mut self) {
        self.source_states.sort();
        self.source_states.dedup();
    }
}

/// Represents the transitions for a source state
struct DfaTransitions<InputSymbol, OutputSymbol: Ord> {
    /// ID of this state in the resulting DFA
    state_id: StateId,

    /// Transitions for this state (will be unique if `merge_states` is called)
    transitions: Vec<(InputSymbol, DfaState)>,

    /// The output symbols for this state (empty if this is not an accepting state)
    output: Vec<OutputSymbol>
}

impl<InputSymbol: PartialOrd+Clone, OutputSymbol: Ord> DfaTransitions<InputSymbol, OutputSymbol> {
    /// Goes through the transitions in the object and merges the states of any with the same symbol
    fn merge_states(&mut self) {
        if self.transitions.len() > 0 {
            // Order the transitions so that if two transitions have the same input symbol, they are neighbours
            self.transitions.sort_by(|a, b| {
                let &(ref symbol_a, _) = a;
                let &(ref symbol_b, _) = b;

                if let Some(result) = symbol_a.partial_cmp(symbol_b) {
                    result
                } else {
                    // Unordered input symbols won't work well
                    Ordering::Equal
                }
            });

            // For any transition that has a duplicate state, combine it with the previous state
            let mut new_transitions = vec![];
            new_transitions.push(self.transitions[0].clone());

            for transit_idx in 1..self.transitions.len() {
                let len          = new_transitions.len();
                let this_transit = &mut self.transitions[transit_idx];

                if new_transitions[len-1].0 == this_transit.0 {
                    // Same symbol: expand this state
                    new_transitions[len-1].1.source_states.append(&mut this_transit.1.source_states);
                } else {
                    // Different symbol: add new state
                    new_transitions.push(this_transit.clone());
                }
            }

            // Ensure all of the states are sorted and de-duplicated
            for transit in &mut new_transitions {
                transit.1.dedupe();
            }

            // Update the transitions
            self.transitions = new_transitions;
        }
    }

    ///
    /// Finds the output symbol that corresponds to this state
    ///
    /// Rule is that if there is more than one output symbol then the symbol whose value is ordered lowest is the output for this state
    ///
    fn output_symbol(&mut self) -> Option<&OutputSymbol> {
        if self.output.len() > 0 {
            self.output.sort();
            Some(&self.output[0])
        } else {
            None
        }
    }
}

impl<InputSymbol: PartialOrd+Clone, OutputSymbol: Ord+Clone, DfaType, Ndfa: StateMachine<InputSymbol, OutputSymbol>, Builder: DfaBuilder<InputSymbol, OutputSymbol, DfaType>>
    DfaCompiler<InputSymbol, OutputSymbol, DfaType, Ndfa, Builder> {
    ///
    /// Builds a DFA using an NDFA and a builder
    ///
    pub fn build(ndfa: Ndfa, builder: Builder) -> DfaType {
        let compiler = DfaCompiler::new(ndfa, builder);
        compiler.compile()
    }

    ///
    /// Creates a new DFA compiler using a particular builder and NDFA
    ///
    pub fn new(ndfa: Ndfa, builder: Builder) -> Self {
        DfaCompiler { ndfa: ndfa, builder: builder, phantom: (PhantomData, PhantomData, PhantomData) }
    }

    ///
    /// Compiles the NDFA into a DFA
    ///
    pub fn compile(self) -> DfaType {
        // We assume that input symbols are non-overlapping, which is not automatically the case for symbol ranges

        // Work out the state mapping for each input symbol
        let mut states       = vec![];
        let mut known_states = HashMap::new();
        let mut to_process   = vec![];

        // All state machines have state 0 as their starting state
        let state_zero = DfaState::create(vec![0]);

        known_states.insert(state_zero.clone(), 0);
        to_process.push(state_zero);

        while let Some(state) = to_process.pop() {
            // Create a new transitions object for this state
            let mut transitions = vec![];
            let mut output      = vec![];

            for source_state in &state.source_states {
                let source_transitions = self.ndfa.get_transitions_for_state(*source_state);

                for (symbol, state) in source_transitions {
                    transitions.push((symbol, DfaState::create(vec![state])));
                }

                if let Some(source_output) = self.ndfa.output_symbol_for_state(*source_state) {
                    output.push(source_output.clone());
                }
            }

            // Merge it so that we only have one transition per symbol
            let mut dfa_transitions = DfaTransitions { state_id: states.len() as StateId, transitions: transitions, output: output };
            dfa_transitions.merge_states();

            // Process any generated states that are not already in the DFA
            for &(_, ref maybe_new_state) in &dfa_transitions.transitions {
                if !known_states.contains_key(maybe_new_state) {
                    to_process.push(maybe_new_state.clone());
                }
            }

            // Store the new state
            known_states.insert(state.clone(), dfa_transitions.state_id);
            states.push(dfa_transitions);
        }

        // Build the DFA
        let mut builder = self.builder;

        for mut dfa_state in states {
            builder.start_state();

            if let Some(output_symbol) = dfa_state.output_symbol() {
                builder.accept(output_symbol.clone());
            }

            for (symbol, target_state) in dfa_state.transitions {
                builder.transition(symbol, known_states[&target_state]);
            }
        }

        // Generate the final DFA
        builder.build()
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use super::super::regular_pattern::*;
    use super::super::state_machine::*;
    use super::super::symbol_range_dfa::*;
    use super::super::pattern_matcher::*;
    use super::super::symbol_reader::*;

    #[test]
    fn can_create_compiler() {
        let ndfa     = "abc".into_pattern().to_ndfa("success");
        let builder  = SymbolRangeDfaBuilder::new();

        DfaCompiler::new(ndfa, builder);
    }

    #[test]
    fn can_build_dfa() {
        // Generate a state machine from the "abc" pattern
        let ndfa     = "abc".into_pattern().to_ndfa("Success");
        let builder  = SymbolRangeDfaBuilder::new();

        let state_machine = DfaCompiler::build(ndfa, builder);

        // Read back 'abc' manually
        let mut state = More(state_machine.start());
        let mut input = "abc".read_symbols();

        while let More(this_state) = state {
            let next_state =
                if let Some(next_char) = input.next_symbol() {
                    this_state.next(next_char)
                } else {
                    this_state.finish()
                };

            state = next_state;
        }

        // Check for acceptance
        if let Accept(count, output) = state {
            assert!(count == 3);
            assert!(output == &"Success");
        } else {
            assert!(false);
        }
    }

    #[test]
    fn can_build_dfa_with_overlapping_range() {
        // Generate a state machine from the "abc" pattern
        let ndfa     = (MatchRange('b', 'b').append("a")).or(MatchRange('b', 'b').append("b")).to_ndfa("Success");
        let builder  = SymbolRangeDfaBuilder::new();

        let state_machine = DfaCompiler::build(ndfa, builder);

        println!("{:?}", state_machine);

        // Read back 'ba' manually
        let mut state = More(state_machine.start());
        let mut input = "ba".read_symbols();

        while let More(this_state) = state {
            let next_state =
                if let Some(next_char) = input.next_symbol() {
                    this_state.next(next_char)
                } else {
                    this_state.finish()
                };

            state = next_state;
        }

        // Check for acceptance
        if let Accept(count, output) = state {
            assert!(count == 2);
            assert!(output == &"Success");
        } else {
            assert!(false);
        }

        // Read back 'bb' manually
        state = More(state_machine.start());
        input = "bb".read_symbols();

        while let More(this_state) = state {
            let next_state =
                if let Some(next_char) = input.next_symbol() {
                    this_state.next(next_char)
                } else {
                    this_state.finish()
                };

            state = next_state;
        }

        // Check for acceptance
        if let Accept(count, output) = state {
            assert!(count == 2);
            assert!(output == &"Success");
        } else {
            assert!(false);
        }
    }
}
<|endoftext|>


<commit_before>// Copyright 2016 Pierre Talbot (IRCAM)

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! The types of the rules of this grammar must be valid (Bug #75).

pub use self::well_formedness::*;

grammar! well_formedness {

  // a = a "a" / "b"          // ERROR: left recursion

  b = "a" b "b" / "b" b       // OK

  // c = "a" c "b" / c "b"    // ERROR: left recursion

  // d = "a" . / d1           // ERROR: left recursion
  // d1 = d

  // e = "a" . / e1           // ERROR: left recursion
  // e1 = "b" . / e / "c" .

  // f = . / !f1 .            // ERROR: left recursion
  // f1 = . / "a"? f2 / "c" .
  // f2 = "b"* f

  g = . / !g1 .               // OK
  g1 = . / "a"? g2 / "c" .
  g2 = "b"+ g

  h = . / ("a" "b")+ !h1 .    // OK
  h1 = . / "a"? h / "c" .

  // i = . i1               // ERROR: left recursion
  // i1 = i1+

  // j = . j1               // ERROR: left recursion
  // j1 = ("" !j)+

  // m = !""                // ERROR: never succeed
  // n = (!"")*             // ERROR: never succeed

  // w = !(.*)              // ERROR: never succeed

  // o = (!.)*              // ERROR: loop repeat

  // p = ("a" / "b" / "")+  // ERROR loop repeat

  // q = &["a-z"]           // ERROR: loop repeat
  // q2 = q+

  // r = ["a-z"] / "A"*     // ERROR: loop repeat
  // r2 = r+

  s = &["a-z"] "a" / "A"+     // OK
  s2 = s*

  t = ["a-z"]* / "A"+       // ERROR: unreachable branch

  // u = "a" .+ / .* / "Z" .+  // ERROR: unreachable branch

  // v = "a" .+ / "" / "Z" .+  // ERROR: unreachable branch

}
<commit_msg>[Tests] Forgot to comment out a failure test.<commit_after>// Copyright 2016 Pierre Talbot (IRCAM)

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! The types of the rules of this grammar must be valid (Bug #75).

pub use self::well_formedness::*;

grammar! well_formedness {

  // a = a "a" / "b"          // ERROR: left recursion

  b = "a" b "b" / "b" b       // OK

  // c = "a" c "b" / c "b"    // ERROR: left recursion

  // d = "a" . / d1           // ERROR: left recursion
  // d1 = d

  // e = "a" . / e1           // ERROR: left recursion
  // e1 = "b" . / e / "c" .

  // f = . / !f1 .            // ERROR: left recursion
  // f1 = . / "a"? f2 / "c" .
  // f2 = "b"* f

  g = . / !g1 .               // OK
  g1 = . / "a"? g2 / "c" .
  g2 = "b"+ g

  h = . / ("a" "b")+ !h1 .    // OK
  h1 = . / "a"? h / "c" .

  // i = . i1               // ERROR: left recursion
  // i1 = i1+

  // j = . j1               // ERROR: left recursion
  // j1 = ("" !j)+

  // m = !""                // ERROR: never succeed
  // n = (!"")*             // ERROR: never succeed

  // w = !(.*)              // ERROR: never succeed

  // o = (!.)*              // ERROR: loop repeat

  // p = ("a" / "b" / "")+  // ERROR loop repeat

  // q = &["a-z"]           // ERROR: loop repeat
  // q2 = q+

  // r = ["a-z"] / "A"*     // ERROR: loop repeat
  // r2 = r+

  s = &["a-z"] "a" / "A"+     // OK
  s2 = s*

  // t = ["a-z"]* / "A"+       // ERROR: unreachable branch

  // u = "a" .+ / .* / "Z" .+  // ERROR: unreachable branch

  // v = "a" .+ / "" / "Z" .+  // ERROR: unreachable branch

}
<|endoftext|>


<commit_before>use std::io::fs;
use std::io;
use std::os;
use std::str;
use cargo::util::{process, ProcessBuilder};

use support::paths;
use support::{project, cargo_dir, mkdir_recursive, ProjectBuilder, ResultTest};

fn setup() {
}

/// Add an empty file with executable flags (and platform-dependent suffix).
/// TODO: move this to `ProjectBuilder` if other cases using this emerge.
fn fake_executable(proj: ProjectBuilder, dir: &Path, name: &str) -> ProjectBuilder {
    let path = proj.root().join(dir).join(format!("{}{}", name, os::consts::EXE_SUFFIX));
    mkdir_recursive(&Path::new(path.dirname())).assert();
    fs::File::create(&path).assert();
    let io::FileStat{perm, ..} = fs::stat(&path).assert();
    fs::chmod(&path, io::OtherExecute | perm).assert();
    proj
}

/// Copy real cargo exeutable just built to specified location, and
/// prepare to run it.
fn copied_executable_process(proj: &ProjectBuilder, name: &str, dir: &Path) -> ProcessBuilder {
    let name = format!("{}{}", name, os::consts::EXE_SUFFIX);
    let path_src = cargo_dir().join(name.clone());
    let path_dst = proj.root().join(dir).join(name);
    mkdir_recursive(&Path::new(path_dst.dirname())).assert();
    fs::copy(&path_src, &path_dst).assert();
    process(path_dst)
        .cwd(proj.root())
        .env("HOME", Some(paths::home().as_vec()))
}

// We can't entirely obliterate PATH because windows needs it for paths to
// things like libgcc, but we want to filter out everything which has a `cargo`
// installation as we don't want it to muck with the --list tests
fn new_path() -> Vec<Path> {
    let path = os::getenv_as_bytes("PATH").unwrap_or(Vec::new());
    os::split_paths(path).move_iter().filter(|p| {
        !p.join(format!("cargo{}", os::consts::EXE_SUFFIX)).exists()
    }).collect()
}
test!(list_commands_non_overlapping {
    // lib/cargo | cargo-3
    // bin/       | cargo-2
    // PATH       | cargo-1
    // Check if --list searches all 3 targets.
    // Also checks that results are in lexicographic order.
    let proj = project("list-non-overlapping");
    let proj = fake_executable(proj, &Path::new("lib/cargo"), "cargo-3");
    let proj = fake_executable(proj, &Path::new("bin"), "cargo-2");
    let proj = fake_executable(proj, &Path::new("path-test"), "cargo-1");
    let pr = copied_executable_process(&proj, "cargo", &Path::new("bin"));

    let mut path = new_path();
    path.push(proj.root().join("path-test"));
    let path = os::join_paths(path.as_slice()).unwrap();
    let output = pr.arg("-v").arg("--list").env("PATH", Some(path.as_slice()));
    let output = output.exec_with_output().assert();
    let output = str::from_utf8(output.output.as_slice()).assert();
    assert!(output.contains("\n    1\n"), "missing 1: {}", output);
    assert!(output.contains("\n    2\n"), "missing 2: {}", output);
    assert!(output.contains("\n    3\n"), "missing 3: {}", output);
})
<commit_msg>auto merge of #500 : alexcrichton/cargo/fix-flaky-test, r=brson<commit_after>use std::io::fs;
use std::io;
use std::os;
use std::str;
use cargo::util::process;

use support::paths;
use support::{project, cargo_dir, mkdir_recursive, ProjectBuilder, ResultTest};

fn setup() {
}

/// Add an empty file with executable flags (and platform-dependent suffix).
/// TODO: move this to `ProjectBuilder` if other cases using this emerge.
fn fake_executable(proj: ProjectBuilder, dir: &Path, name: &str) -> ProjectBuilder {
    let path = proj.root().join(dir).join(format!("{}{}", name, os::consts::EXE_SUFFIX));
    mkdir_recursive(&Path::new(path.dirname())).assert();
    fs::File::create(&path).assert();
    let io::FileStat{perm, ..} = fs::stat(&path).assert();
    fs::chmod(&path, io::OtherExecute | perm).assert();
    proj
}

// We can't entirely obliterate PATH because windows needs it for paths to
// things like libgcc, but we want to filter out everything which has a `cargo`
// installation as we don't want it to muck with the --list tests
fn new_path() -> Vec<Path> {
    let path = os::getenv_as_bytes("PATH").unwrap_or(Vec::new());
    os::split_paths(path).move_iter().filter(|p| {
        !p.join(format!("cargo{}", os::consts::EXE_SUFFIX)).exists()
    }).collect()
}
test!(list_commands_looks_at_path {
    let proj = project("list-non-overlapping");
    let proj = fake_executable(proj, &Path::new("path-test"), "cargo-1");
    let pr = process(cargo_dir().join("cargo")).cwd(proj.root())
                    .env("HOME", Some(paths::home()));

    let mut path = new_path();
    path.push(proj.root().join("path-test"));
    let path = os::join_paths(path.as_slice()).unwrap();
    let output = pr.arg("-v").arg("--list").env("PATH", Some(path.as_slice()));
    let output = output.exec_with_output().assert();
    let output = str::from_utf8(output.output.as_slice()).assert();
    assert!(output.contains("\n    1\n"), "missing 1: {}", output);
})
<|endoftext|>


<commit_before>extern crate redis;

#[test]
fn test_is_single_arg() {
    use redis::ToRedisArgs;

    let sslice : &[_] = &["foo"][..];
    let nestslice : &[_] = &[sslice][..];
    let nestvec = vec![nestslice];
    let bytes = b"Hello World!";
    let twobytesslice : &[_] = &[bytes, bytes][..];
    let twobytesvec = vec![bytes, bytes];

    assert_eq!("foo".is_single_arg(), true);
    assert_eq!(sslice.is_single_arg(), true);
    assert_eq!(nestslice.is_single_arg(), true);
    assert_eq!(nestvec.is_single_arg(), true);
    assert_eq!(bytes.is_single_arg(), true);
    assert_eq!(twobytesslice.is_single_arg(), false);
    assert_eq!(twobytesvec.is_single_arg(), false);
}

#[test]
fn test_info_dict() {
    use redis::{InfoDict, FromRedisValue, Value};

    let d : InfoDict = FromRedisValue::from_redis_value(&Value::Status(
        "# this is a comment\nkey1:foo\nkey2:42\n".into()
    )).unwrap();

    assert_eq!(d.get("key1"), Some("foo".to_string()));
    assert_eq!(d.get("key2"), Some(42i64));
    assert_eq!(d.get::<String>("key3"), None);
}

#[test]
fn test_i32() {
    use redis::{FromRedisValue, Value, ErrorKind};

    let i = FromRedisValue::from_redis_value(&Value::Status("42".into()));
    assert_eq!(i, Ok(42i32));

    let i = FromRedisValue::from_redis_value(&Value::Int(42));
    assert_eq!(i, Ok(42i32));

    let i = FromRedisValue::from_redis_value(&Value::Data("42".into()));
    assert_eq!(i, Ok(42i32));

    let bad_i : Result<i32, _> = FromRedisValue::from_redis_value(
        &Value::Status("42x".into()));
    assert_eq!(bad_i.unwrap_err().kind(), ErrorKind::TypeError);
}

#[test]
fn test_u32() {
    use redis::{FromRedisValue, Value, ErrorKind};

    let i = FromRedisValue::from_redis_value(&Value::Status("42".into()));
    assert_eq!(i, Ok(42u32));

    let bad_i : Result<i32, _> = FromRedisValue::from_redis_value(
        &Value::Status("-1".into()));
    assert_eq!(bad_i.unwrap_err().kind(), ErrorKind::TypeError);
}

#[test]
fn test_vec() {
    use redis::{FromRedisValue, Value};

    let v = FromRedisValue::from_redis_value(&Value::Bulk(vec![
        Value::Data("1".into()),
        Value::Data("2".into()),
        Value::Data("3".into()),
    ]));

    assert_eq!(v, Ok(vec![1i32, 2, 3]));
}

#[test]
fn test_bool() {
    use redis::{FromRedisValue, Value, ErrorKind};

    let v = FromRedisValue::from_redis_value(&Value::Status("1".into()));
    assert_eq!(v, Ok(true));

    let v = FromRedisValue::from_redis_value(&Value::Status("0".into()));
    assert_eq!(v, Ok(false));

    let v : Result<bool, _> = FromRedisValue::from_redis_value(
        &Value::Status("garbage".into()));
    assert_eq!(v.unwrap_err().kind(), ErrorKind::TypeError);

    let v = FromRedisValue::from_redis_value(&Value::Okay);
    assert_eq!(v, Ok(true));

    let v = FromRedisValue::from_redis_value(&Value::Nil);
    assert_eq!(v, Ok(false));

    let v = FromRedisValue::from_redis_value(&Value::Int(0));
    assert_eq!(v, Ok(false));

    let v = FromRedisValue::from_redis_value(&Value::Int(42));
    assert_eq!(v, Ok(true));
}
<commit_msg>Fixed a broken test<commit_after>extern crate redis;

#[test]
fn test_is_single_arg() {
    use redis::ToRedisArgs;

    let sslice : &[_] = &["foo"][..];
    let nestslice : &[_] = &[sslice][..];
    let nestvec = vec![nestslice];
    let bytes = b"Hello World!";
    let twobytesslice : &[_] = &[bytes, bytes][..];
    let twobytesvec = vec![bytes, bytes];

    assert_eq!("foo".is_single_arg(), true);
    assert_eq!(sslice.is_single_arg(), true);
    assert_eq!(nestslice.is_single_arg(), true);
    assert_eq!(nestvec.is_single_arg(), true);
    assert_eq!(bytes.is_single_arg(), true);
    assert_eq!(twobytesslice.is_single_arg(), false);
    assert_eq!(twobytesvec.is_single_arg(), false);
}

#[test]
fn test_info_dict() {
    use redis::{InfoDict, FromRedisValue, Value};

    let d : InfoDict = FromRedisValue::from_redis_value(&Value::Status(
        "# this is a comment\nkey1:foo\nkey2:42\n".into()
    )).unwrap();

    assert_eq!(d.get("key1"), Some("foo".to_string()));
    assert_eq!(d.get("key2"), Some(42i64));
    assert_eq!(d.get::<String>("key3"), None);
}

#[test]
fn test_i32() {
    use redis::{FromRedisValue, Value, ErrorKind};

    let i = FromRedisValue::from_redis_value(&Value::Status("42".into()));
    assert_eq!(i, Ok(42i32));

    let i = FromRedisValue::from_redis_value(&Value::Int(42));
    assert_eq!(i, Ok(42i32));

    let i = FromRedisValue::from_redis_value(&Value::Data("42".into()));
    assert_eq!(i, Ok(42i32));

    let bad_i : Result<i32, _> = FromRedisValue::from_redis_value(
        &Value::Status("42x".into()));
    assert_eq!(bad_i.unwrap_err().kind(), ErrorKind::TypeError);
}

#[test]
fn test_u32() {
    use redis::{FromRedisValue, Value, ErrorKind};

    let i = FromRedisValue::from_redis_value(&Value::Status("42".into()));
    assert_eq!(i, Ok(42u32));

    let bad_i : Result<u32, _> = FromRedisValue::from_redis_value(
        &Value::Status("-1".into()));
    assert_eq!(bad_i.unwrap_err().kind(), ErrorKind::TypeError);
}

#[test]
fn test_vec() {
    use redis::{FromRedisValue, Value};

    let v = FromRedisValue::from_redis_value(&Value::Bulk(vec![
        Value::Data("1".into()),
        Value::Data("2".into()),
        Value::Data("3".into()),
    ]));

    assert_eq!(v, Ok(vec![1i32, 2, 3]));
}

#[test]
fn test_bool() {
    use redis::{FromRedisValue, Value, ErrorKind};

    let v = FromRedisValue::from_redis_value(&Value::Status("1".into()));
    assert_eq!(v, Ok(true));

    let v = FromRedisValue::from_redis_value(&Value::Status("0".into()));
    assert_eq!(v, Ok(false));

    let v : Result<bool, _> = FromRedisValue::from_redis_value(
        &Value::Status("garbage".into()));
    assert_eq!(v.unwrap_err().kind(), ErrorKind::TypeError);

    let v = FromRedisValue::from_redis_value(&Value::Okay);
    assert_eq!(v, Ok(true));

    let v = FromRedisValue::from_redis_value(&Value::Nil);
    assert_eq!(v, Ok(false));

    let v = FromRedisValue::from_redis_value(&Value::Int(0));
    assert_eq!(v, Ok(false));

    let v = FromRedisValue::from_redis_value(&Value::Int(42));
    assert_eq!(v, Ok(true));
}
<|endoftext|>


<commit_before>use std::io;
use std::str::FromStr;
use std::fmt::Debug;

// TODO(mayah): using char iterator is desired, however, it's unstable.
pub struct Scanner<I> {
    bi: I, // bytes iterator
}

fn is_whitespace(b: u8) -> bool {
    b == b' ' || b == b'\t' || b == b'\r' || b == b'\n'
}

impl<R: io::Read> Scanner<io::Bytes<R>> {
    pub fn new(reader: R) -> Scanner<io::Bytes<R>> {
        Scanner {
            bi: reader.bytes(),
        }
    }

    pub fn next<T>(&mut self) -> Option<T> where T: FromStr + Debug, <T as FromStr>::Err: Debug {
        self.next_token().map(|x| x.parse::<T>().unwrap())
    }

    fn next_token(&mut self) -> Option<String> {
        let mut result: Vec<u8> = Vec::new();
        loop {
            match self.bi.next() {
                None => {
                    if result.len() > 0 {
                        return Some(String::from_utf8(result).unwrap());
                    } else {
                        return None;
                    }
                },
                Some(Ok(c)) => {
                    if is_whitespace(c) {
                        return Some(String::from_utf8(result).unwrap());
                    } else {
                        result.push(c);
                    }
                },
                Some(Err(_)) => {
                    // TODO(mayah): Should return err.
                    return None;
                },
            }
        }
    }
}

pub fn from_stdin() -> Scanner<io::Bytes<io::Stdin>> {
    Scanner::new(io::stdin())
}
<commit_msg>Fix rust scanner implementation.<commit_after>use std::io;
use std::str::FromStr;
use std::fmt::Debug;

// TODO(mayah): using char iterator is desired, however, it's unstable.
pub struct Scanner<I> {
    bi: I, // bytes iterator
}

fn is_whitespace(b: u8) -> bool {
    b == b' ' || b == b'\t' || b == b'\r' || b == b'\n'
}

impl<R: io::Read> Scanner<io::Bytes<R>> {
    pub fn new(reader: R) -> Scanner<io::Bytes<R>> {
        Scanner {
            bi: reader.bytes(),
        }
    }

    pub fn next<T>(&mut self) -> Option<T> where T: FromStr + Debug, <T as FromStr>::Err: Debug {
        self.next_token().map(|x| x.parse::<T>().unwrap())
    }

    fn next_token(&mut self) -> Option<String> {
        let mut result: Vec<u8> = Vec::new();
        loop {
            match self.bi.next() {
                None => {
                    if result.len() > 0 {
                        return Some(String::from_utf8(result).unwrap());
                    } else {
                        return None;
                    }
                },
                Some(Ok(c)) => {
                    if is_whitespace(c) {
                        if result.len() > 0 {
                            return Some(String::from_utf8(result).unwrap());
                        } else {
                            continue;
                        }
                    } else {
                        result.push(c);
                    }
                },
                Some(Err(_)) => {
                    // TODO(mayah): Should return err.
                    return None;
                },
            }
        }
    }
}

pub fn from_stdin() -> Scanner<io::Bytes<io::Stdin>> {
    Scanner::new(io::stdin())
}
<|endoftext|>


<commit_before>extern crate serialize;
extern crate nickel;
extern crate http;

use http::status::{NotFound, BadRequest};
use nickel::{
    Nickel, NickelError, ErrorWithStatusCode, Continue, Halt, Request, Response,
    QueryString, JsonBody, StaticFilesHandler, MiddlewareResult, HttpRouter
};
use std::io::net::ip::Ipv4Addr;
use std::collections::treemap::TreeMap;
use serialize::json::{Json, Object, ToJson};

#[deriving(Decodable, Encodable)]
struct Person {
    firstname: String,
    lastname:  String,
}

impl ToJson for Person {
    fn to_json(&self) -> Json {
        let mut map = TreeMap::new();
        map.insert("first_name".to_string(), self.firstname.to_json());
        map.insert("last_name".to_string(), self.lastname.to_json());
        Object(map)
    }
}

fn main() {
    let mut server = Nickel::new();

    // we would love to use a closure for the handler but it seems to be hard
    // to achieve with the current version of rust.

    //this is an example middleware function that just logs each request
    fn logger(request: &Request, _response: &mut Response) -> MiddlewareResult {
        println!("logging request: {}", request.origin.request_uri);

        // a request is supposed to return a `bool` to indicate whether additional
        // middleware should continue executing or should be stopped.
        Ok(Continue)
    }

    // middleware is optional and can be registered with `utilize`
    server.utilize(logger);

    // this will cause json bodies automatically being parsed
    server.utilize(Nickel::json_body_parser());

    // this will cause the query string to be parsed on each request
    server.utilize(Nickel::query_string());

    let mut router = Nickel::router();

    fn user_handler(request: &Request, _response: &mut Response) -> String {
        format!("This is user: {}", request.param("userid"))
    }

    // go to http://localhost:6767/user/4711 to see this route in action
    router.get("/user/:userid", user_handler);

    fn bar_handler(_request: &Request, response: &mut Response) {
        response.send("This is the /bar handler");
    }

    // go to http://localhost:6767/bar to see this route in action
    router.get("/bar", bar_handler);

    fn simple_wildcard(_request: &Request, response: &mut Response) {
        response.send("This matches /some/crazy/route but not /some/super/crazy/route");
    }

    // go to http://localhost:6767/some/crazy/route to see this route in action
    router.get("/some/*/route", simple_wildcard);

    fn double_wildcard(_request: &Request, _response: &mut Response) -> &'static str {
        "This matches /a/crazy/route and also /a/super/crazy/route"
    }

    // go to http://localhost:6767/a/nice/route or http://localhost:6767/a/super/nice/route to see this route in action
    router.get("/a/**/route", double_wildcard);

    // try it with curl
    // curl 'http://localhost:6767/a/post/request' -H 'Content-Type: application/json;charset=UTF-8'  --data-binary $'{ "firstname": "John","lastname": "Connor" }'
    fn post_handler(request: &Request, _response: &mut Response) -> String {
        let person = request.json_as::<Person>().unwrap();
        format!("Hello {} {}", person.firstname, person.lastname)
    }

    // go to http://localhost:6767/a/post/request to see this route in action
    router.post("/a/post/request", post_handler);

    fn json_response(_request: &Request, _response: &mut Response) -> Json {
        let person = Person {
            firstname: "Pea".to_string(),
            lastname: "Nut".to_string()
        };
        person.to_json()
    }

    // go to http://localhost:6767/api/person/1 to see this route in action
    router.get("/api/person/1", json_response);

    // try calling http://localhost:6767/query?foo=bar
    fn query_handler(request: &Request, _response: &mut Response) -> String {
        format!("Your foo values in the query string are: {}", request.query("foo", "This is only a default value!"))
    }

    router.get("/query", query_handler);

    // try calling http://localhost:6767/strict?state=valid
    // then try calling http://localhost:6767/strict?state=invalid
    fn strict_handler(request: &Request, response: &mut Response) -> MiddlewareResult {
        if request.query("state", "invalid")[0].as_slice() != "valid" {
            Err(NickelError::new("Error Parsing JSON", ErrorWithStatusCode(BadRequest)))
        } else {
            response.send("Congratulations on conforming!");
            Ok(Halt)
        }
    }

    router.get("/strict", strict_handler);

    server.utilize(router);

    // go to http://localhost:6767/thoughtram_logo_brain.png to see static file serving in action
    server.utilize(StaticFilesHandler::new("examples/assets/"));

    //this is how to overwrite the default error handler to handle 404 cases with a custom view
    fn custom_404(err: &NickelError, _req: &Request, response: &mut Response) -> MiddlewareResult {
        match err.kind {
            ErrorWithStatusCode(NotFound) => {
                response.content_type("html")
                        .status_code(NotFound)
                        .send("
Call the police!
");
                Ok(Halt)
            },
            _ => Ok(Continue)
        }
    }

    server.handle_error(custom_404);

    server.listen(Ipv4Addr(127, 0, 0, 1), 6767);
}
<commit_msg>fix(TreeMap): fix TreeMap path<commit_after>extern crate serialize;
extern crate nickel;
extern crate http;

use http::status::{NotFound, BadRequest};
use nickel::{
    Nickel, NickelError, ErrorWithStatusCode, Continue, Halt, Request, Response,
    QueryString, JsonBody, StaticFilesHandler, MiddlewareResult, HttpRouter
};
use std::io::net::ip::Ipv4Addr;
use std::collections::TreeMap;
use serialize::json::{Json, Object, ToJson};

#[deriving(Decodable, Encodable)]
struct Person {
    firstname: String,
    lastname:  String,
}

impl ToJson for Person {
    fn to_json(&self) -> Json {
        let mut map = TreeMap::new();
        map.insert("first_name".to_string(), self.firstname.to_json());
        map.insert("last_name".to_string(), self.lastname.to_json());
        Object(map)
    }
}

fn main() {
    let mut server = Nickel::new();

    // we would love to use a closure for the handler but it seems to be hard
    // to achieve with the current version of rust.

    //this is an example middleware function that just logs each request
    fn logger(request: &Request, _response: &mut Response) -> MiddlewareResult {
        println!("logging request: {}", request.origin.request_uri);

        // a request is supposed to return a `bool` to indicate whether additional
        // middleware should continue executing or should be stopped.
        Ok(Continue)
    }

    // middleware is optional and can be registered with `utilize`
    server.utilize(logger);

    // this will cause json bodies automatically being parsed
    server.utilize(Nickel::json_body_parser());

    // this will cause the query string to be parsed on each request
    server.utilize(Nickel::query_string());

    let mut router = Nickel::router();

    fn user_handler(request: &Request, _response: &mut Response) -> String {
        format!("This is user: {}", request.param("userid"))
    }

    // go to http://localhost:6767/user/4711 to see this route in action
    router.get("/user/:userid", user_handler);

    fn bar_handler(_request: &Request, response: &mut Response) {
        response.send("This is the /bar handler");
    }

    // go to http://localhost:6767/bar to see this route in action
    router.get("/bar", bar_handler);

    fn simple_wildcard(_request: &Request, response: &mut Response) {
        response.send("This matches /some/crazy/route but not /some/super/crazy/route");
    }

    // go to http://localhost:6767/some/crazy/route to see this route in action
    router.get("/some/*/route", simple_wildcard);

    fn double_wildcard(_request: &Request, _response: &mut Response) -> &'static str {
        "This matches /a/crazy/route and also /a/super/crazy/route"
    }

    // go to http://localhost:6767/a/nice/route or http://localhost:6767/a/super/nice/route to see this route in action
    router.get("/a/**/route", double_wildcard);

    // try it with curl
    // curl 'http://localhost:6767/a/post/request' -H 'Content-Type: application/json;charset=UTF-8'  --data-binary $'{ "firstname": "John","lastname": "Connor" }'
    fn post_handler(request: &Request, _response: &mut Response) -> String {
        let person = request.json_as::<Person>().unwrap();
        format!("Hello {} {}", person.firstname, person.lastname)
    }

    // go to http://localhost:6767/a/post/request to see this route in action
    router.post("/a/post/request", post_handler);

    fn json_response(_request: &Request, _response: &mut Response) -> Json {
        let person = Person {
            firstname: "Pea".to_string(),
            lastname: "Nut".to_string()
        };
        person.to_json()
    }

    // go to http://localhost:6767/api/person/1 to see this route in action
    router.get("/api/person/1", json_response);

    // try calling http://localhost:6767/query?foo=bar
    fn query_handler(request: &Request, _response: &mut Response) -> String {
        format!("Your foo values in the query string are: {}", request.query("foo", "This is only a default value!"))
    }

    router.get("/query", query_handler);

    // try calling http://localhost:6767/strict?state=valid
    // then try calling http://localhost:6767/strict?state=invalid
    fn strict_handler(request: &Request, response: &mut Response) -> MiddlewareResult {
        if request.query("state", "invalid")[0].as_slice() != "valid" {
            Err(NickelError::new("Error Parsing JSON", ErrorWithStatusCode(BadRequest)))
        } else {
            response.send("Congratulations on conforming!");
            Ok(Halt)
        }
    }

    router.get("/strict", strict_handler);

    server.utilize(router);

    // go to http://localhost:6767/thoughtram_logo_brain.png to see static file serving in action
    server.utilize(StaticFilesHandler::new("examples/assets/"));

    //this is how to overwrite the default error handler to handle 404 cases with a custom view
    fn custom_404(err: &NickelError, _req: &Request, response: &mut Response) -> MiddlewareResult {
        match err.kind {
            ErrorWithStatusCode(NotFound) => {
                response.content_type("html")
                        .status_code(NotFound)
                        .send("
Call the police!
");
                Ok(Halt)
            },
            _ => Ok(Continue)
        }
    }

    server.handle_error(custom_404);

    server.listen(Ipv4Addr(127, 0, 0, 1), 6767);
}
<|endoftext|>


<commit_before>#![feature(unboxed_closures)]

extern crate synthrs;

use synthrs::synthesizer::{ make_samples, quantize_samples };
use synthrs::filter::{
    convolve, cutoff_from_frequency,
    lowpass_filter, highpass_filter, bandpass_filter, bandreject_filter
};
use synthrs::wave::SineWave;
use synthrs::writer::write_wav;

fn main() {
    // Lowpass/highpass filter convolution example
    let sample = make_samples(1.0, 44100, |t: f64| -> f64 {
        0.33 * (SineWave(6000.0)(t) + SineWave(700.0)(t) + SineWave(80.0)(t))
    });

    let lowpass = lowpass_filter(cutoff_from_frequency(400.0, 44100), 0.01);
    write_wav("out/lowpass.wav", 44100,
        quantize_samples::<i16>(sample.clone()) + quantize_samples::<i16>(convolve(lowpass.clone(), sample.clone()))
    ).ok().expect("failed");

    let highpass = highpass_filter(cutoff_from_frequency(2000.0, 44100), 0.01);
    write_wav("out/highpass.wav", 44100,
        quantize_samples::<i16>(sample.clone()) + quantize_samples::<i16>(convolve(highpass.clone(), sample.clone()))
    ).ok().expect("failed");

    let bandpass = bandpass_filter(
        cutoff_from_frequency(500.0, 44100),
        cutoff_from_frequency(3000.0, 44100),
        0.01
    );
    write_wav("out/bandpass.wav", 44100,
        quantize_samples::<i16>(sample.clone()) + quantize_samples::<i16>(convolve(bandpass.clone(), sample.clone()))
    ).ok().expect("failed");

    let bandreject = bandreject_filter(
        cutoff_from_frequency(400.0, 44100),
        cutoff_from_frequency(2000.0, 44100),
        0.01
    );
    write_wav("out/bandreject.wav", 44100,
        quantize_samples::<i16>(sample.clone()) + quantize_samples::<i16>(convolve(bandreject.clone(), sample.clone()))
    ).ok().expect("failed");
}
<commit_msg>Fix Rust breaking changes<commit_after>#![feature(unboxed_closures)]

extern crate synthrs;

use synthrs::synthesizer::{ make_samples, quantize_samples };
use synthrs::filter::{
    convolve, cutoff_from_frequency,
    lowpass_filter, highpass_filter, bandpass_filter, bandreject_filter
};
use synthrs::wave::SineWave;
use synthrs::writer::write_wav;

fn main() {
    // Lowpass/highpass filter convolution example
    let sample = make_samples(1.0, 44100, |t: f64| -> f64 {
        0.33 * (SineWave(6000.0)(t) + SineWave(700.0)(t) + SineWave(80.0)(t))
    });

    let lowpass = lowpass_filter(cutoff_from_frequency(400.0, 44100), 0.01);
    write_wav("out/lowpass.wav", 44100,
        quantize_samples::<i16>(sample.clone()) + &*quantize_samples::<i16>(convolve(lowpass, sample.clone()))
    ).ok().expect("failed");

    let highpass = highpass_filter(cutoff_from_frequency(2000.0, 44100), 0.01);
    write_wav("out/highpass.wav", 44100,
        quantize_samples::<i16>(sample.clone()) + &*quantize_samples::<i16>(convolve(highpass, sample.clone()))
    ).ok().expect("failed");

    let bandpass = bandpass_filter(
        cutoff_from_frequency(500.0, 44100),
        cutoff_from_frequency(3000.0, 44100),
        0.01
    );
    write_wav("out/bandpass.wav", 44100,
        quantize_samples::<i16>(sample.clone()) + &*quantize_samples::<i16>(convolve(bandpass, sample.clone()))
    ).ok().expect("failed");

    let bandreject = bandreject_filter(
        cutoff_from_frequency(400.0, 44100),
        cutoff_from_frequency(2000.0, 44100),
        0.01
    );
    write_wav("out/bandreject.wav", 44100,
        quantize_samples::<i16>(sample.clone()) + &*quantize_samples::<i16>(convolve(bandreject, sample.clone()))
    ).ok().expect("failed");
}
<|endoftext|>


<commit_before>// Copyright 2013 The Rusp Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::*;

use std::str;
use std::int;
use std::float;

///
/// A position in a source string
///
pub struct Position {
    line: uint,
    col: uint,
}

pub struct ParseFailure {
    description: ~str,
    position: Position,
}

impl ParseFailure {
    fn err<T>(descr: ~str, pos: Position) -> Result<T, ParseFailure> {
        Err(ParseFailure { description: descr, position: pos })
    }
    fn eof<T>(pos: Position) -> Result<T, ParseFailure> {
        ParseFailure::err(~"Unexpected EOF", pos)
    }
}

static EOF : char = 0 as char;

pub struct Parser<'self> {
    priv src_pos: uint,
    priv pos: Position,
    priv src: &'self str,
    priv src_len: uint,
}

pub type ParseResult = Result<@Value, ParseFailure>;

impl<'self> Parser<'self> {
    pub fn new<'r>(src: &'r str) -> Parser<'r> {
        Parser {
            src_pos: 0,
            pos: Position { line: 1, col: 1 },
            src: src,
            src_len: src.len()
        }
    }

    pub fn parse(&mut self) -> ParseResult {
        self.skip_whitespace();
        if self.eat_char('(') {
            self.parse_list()
        } else {
            match self.peek_char() {
                '.' if self.eat_str("..") => Ok(@Symbol(~"..")),
                '0'..'9' | '.' => self.parse_number(),
                't' if self.eat_str("true") => Ok(@Bool(true)),
                'f' if self.eat_str("false") => Ok(@Bool(false)),
                '"' => self.parse_string(),
                ')' => self.fail(~"Unexpected ')'"),
                _ => self.parse_ident()
            }
        }
    }

    pub fn eof(&self) -> bool {
        self.src_pos >= self.src_len
    }

    priv fn parse_list(&mut self) -> ParseResult {
        let mut vals = ~[];
        loop {
            if self.eof() {
                return self.fail(~"Unexpected EOF, expected ')'");
            }

            if self.eat_char(')') {
                return Ok(@List(vals));
            }

            match self.parse() {
                Ok(val) => vals.push(val),
                err => return err
            }

            self.skip_whitespace();
        }
    }

    priv fn parse_number(&mut self) -> ParseResult {
        let mut len = 0;
        let mut seen_point = self.eat_char('.');

        loop {
            match self.src.char_at(self.src_pos+len) {
                '.' if seen_point => return self.fail(~"Unexpected character '.' while parsing number"),
                '.' if !seen_point => {
                    len += 1; // I know that '.' is a single byte
                    seen_point = true;
                }
                '0'..'9' => len += 1, // Same here
                ')' => break,
                c if c.is_whitespace() => break,
                c => {
                    return self.fail(fmt!("Unexpected character '%c' while parsing number", c));
                }
            }
            if (self.src_pos+len) >= self.src_len {
                break
            }
        }

        let slice = self.slice_src(len);
        self.advance_chars(slice.char_len());
        if seen_point {
            let n = float::from_str(slice).unwrap();
            Ok(@Float(n))
        } else {
            let n = int::from_str(slice).unwrap();
            Ok(@Int(n))
        }
    }

    priv fn parse_string(&mut self) -> ParseResult {
        if self.eat_char('"') {
            let mut s = ~"";

            loop {
                match self.peek_char() {
                    '"' => {
                        self.advance_chars(1);
                        return Ok(@Str(s));
                    }
                    '\\' => {
                        self.advance_chars(1);
                        match self.peek_char() {
                            // Minimal list of escape characters, most common ones
                            '0' => s.push_char(0x00 as char),
                            'a' => s.push_char(0x07 as char),
                            'b' => s.push_char(0x08 as char),
                            't' => s.push_char(0x09 as char),
                            'n' => s.push_char(0x0A as char),
                            'v' => s.push_char(0x0B as char),
                            'f' => s.push_char(0x0C as char),
                            'r' => s.push_char(0x0D as char),
                            '"' => s.push_char(0x22 as char),
                            '\''=> s.push_char(0x27 as char),
                            '\\'=> s.push_char(0x5C as char),

                            EOF => return self.fail(~"Unexpected EOF while parsing escape"),
                            _   => loop,
                        }
                        self.advance_chars(1);
                    }
                    EOF => {
                        return self.fail(~"Unexpected EOF while parsing string");
                    }
                    a => {
                        s.push_char(a);
                        self.advance_chars(1);
                    }
                }
            }

        } else {
            fail!("Parser Error, parse_string called at the wrong time");
        }
    }

    priv fn parse_ident(&mut self) -> ParseResult {
        let c = self.peek_char();

        if self.char_is_read_macro(c) {
            return self.eval_read_macro(c);
        }

        let mut ident = ~"";

        loop {
            match self.peek_char() {
                EOF => return self.fail(~"Unexpected EOF while parsing ident"),
                c if self.char_is_read_macro(c) => {
                    return self.fail(fmt!("Unexpected character '%c' while parsing ident", c));
                }
                ')' => return Ok(@Symbol(ident)),
                c if c.is_whitespace() => return Ok(@Symbol(ident)),
                c => ident.push_char(c)
            }
            self.advance_chars(1);
        }
    }

    priv fn skip_whitespace(&mut self) {
        while self.peek_char().is_whitespace() {
            self.advance_chars(1)
        }
    }

    priv fn fail(&self, msg: ~str) -> ParseResult {
        ParseFailure::err(msg, self.pos)
    }

    priv fn slice_src(&self, len: uint) -> &'self str {
        self.src.slice(self.src_pos, self.src_pos+len)
    }

    priv fn peek_char(&self) -> char {
        if self.eof() {
            EOF
        } else {
            self.src.char_at(self.src_pos)
        }
    }

    priv fn eat_char(&mut self, c: char) -> bool {
        if self.peek_char() == c {
            self.advance_chars(1);
            true
        } else {
            false
        }
    }

    priv fn eat_str(&mut self, s: &str) -> bool {
        let slen = s.len();
        if (self.src_pos + slen) >= self.src_len {
            false
        } else {
            let slice = self.slice_src(slen);
            if slice == s {
                self.advance_chars(s.char_len());
                true
            } else {
                false
            }
        }
    }

    priv fn advance_chars(&mut self, n: uint) {
        let mut n = n;
        while n > 0 {
            let str::CharRange {ch:c, next:next} = str::char_range_at(self.src, self.src_pos);
            self.src_pos = next;
            n -= 1;
            self.pos.col += 1;
            if c == '\n' {
                self.pos.col = 1;
                self.pos.line += 1;
            }
        }
    }

    priv fn char_is_read_macro(&mut self, c: char) -> bool {
        match c {
            '\'' | '`' | '#' => true,
            _ => false
        }
    }

    priv fn eval_read_macro(&mut self, _: char) -> ParseResult {
        self.advance_chars(1);
        self.parse()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parser_ok() {
        macro_rules! test(
            ($s:expr) => ({
                let src = $s.clone();
                assert_eq!(Parser::new(src).parse().get().to_str(), src)
            })
        )

        test!(~"1");
        test!(~"(def a (+ 1 2))");
        test!(~"(do (def a 1) (def b 2) (+ a b))");
        test!(~"(list (1 2) 3 (+ 4 5))");

        test!(~"(if true (fn (a b) (+ 1 a b)) (quote (1 2 3)))");

        test!(~"(foo bar \"a b c d\")");

        test!(~"(ö ä å)");
    }

    #[test]
    fn test_parser_err() {
        macro_rules! test(
            ($s:expr) => ({
                let src = $s.clone();
                assert!(Parser::new(src).parse().is_err())
            })
        )

        test!(~"(");
        test!(~")");
        test!(~"\"no closing quote")
    }
}
<commit_msg>Refactor some methods, add test for string escapes<commit_after>// Copyright 2013 The Rusp Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::*;

use std::str;
use std::int;
use std::float;

///
/// A position in a source string
///
pub struct Position {
    line: uint,
    col: uint,
}

pub struct ParseFailure {
    description: ~str,
    position: Position,
}

impl ParseFailure {
    fn err<T>(descr: ~str, pos: Position) -> Result<T, ParseFailure> {
        Err(ParseFailure { description: descr, position: pos })
    }
    fn eof<T>(pos: Position) -> Result<T, ParseFailure> {
        ParseFailure::err(~"Unexpected EOF", pos)
    }
}

static EOF : char = 0 as char;

pub struct Parser<'self> {
    priv src_pos: uint,
    priv pos: Position,
    priv src: &'self str,
    priv src_len: uint,
}

pub type ParseResult = Result<@Value, ParseFailure>;

impl<'self> Parser<'self> {
    pub fn new<'r>(src: &'r str) -> Parser<'r> {
        Parser {
            src_pos: 0,
            pos: Position { line: 1, col: 1 },
            src: src,
            src_len: src.len()
        }
    }

    pub fn parse(&mut self) -> ParseResult {
        self.skip_whitespace();
        if self.eat('(') {
            self.parse_list()
        } else {
            match self.peek() {
                '.' if self.eat_str("..") => Ok(@Symbol(~"..")),
                '0'..'9' | '.' => self.parse_number(),
                't' if self.eat_str("true") => Ok(@Bool(true)),
                'f' if self.eat_str("false") => Ok(@Bool(false)),
                '"' => self.parse_string(),
                ')' => self.fail(~"Unexpected ')'"),
                _ => self.parse_ident()
            }
        }
    }

    pub fn eof(&self) -> bool {
        self.src_pos >= self.src_len
    }

    priv fn parse_list(&mut self) -> ParseResult {
        let mut vals = ~[];
        loop {
            if self.eof() {
                return self.fail(~"Unexpected EOF, expected ')'");
            }

            if self.eat(')') {
                return Ok(@List(vals));
            }

            match self.parse() {
                Ok(val) => vals.push(val),
                err => return err
            }

            self.skip_whitespace();
        }
    }

    priv fn parse_number(&mut self) -> ParseResult {
        let mut len = 0;
        let mut seen_point = self.peek() == '.';

        loop {
            match self.src.char_at(self.src_pos+len) {
                '.' if seen_point => return self.fail(~"Unexpected character '.' while parsing number"),
                '.' if !seen_point => {
                    len += 1; // I know that '.' is a single byte
                    seen_point = true;
                }
                '0'..'9' => len += 1, // Same here
                ')' => break,
                c if c.is_whitespace() => break,
                c => {
                    return self.fail(fmt!("Unexpected character '%c' while parsing number", c));
                }
            }
            if (self.src_pos+len) >= self.src_len {
                break
            }
        }

        let slice = self.slice_src(len);
        self.advance(slice.char_len());
        if seen_point {
            let n = float::from_str(slice).unwrap();
            Ok(@Float(n))
        } else {
            let n = int::from_str(slice).unwrap();
            Ok(@Int(n))
        }
    }

    priv fn parse_string(&mut self) -> ParseResult {
        if self.eat('"') {
            let mut s = ~"";

            loop {
                match self.pop() {
                    '"' => {
                        return Ok(@Str(s));
                    }
                    '\\' => {
                        match self.peek() {
                            // Minimal list of escape characters, most common ones
                            '0' => s.push_char(0x00 as char),
                            'a' => s.push_char(0x07 as char),
                            'b' => s.push_char(0x08 as char),
                            't' => s.push_char(0x09 as char),
                            'n' => s.push_char(0x0A as char),
                            'v' => s.push_char(0x0B as char),
                            'f' => s.push_char(0x0C as char),
                            'r' => s.push_char(0x0D as char),
                            '"' => s.push_char(0x22 as char),
                            '\''=> s.push_char(0x27 as char),
                            '\\'=> s.push_char(0x5C as char),

                            EOF => return self.fail(~"Unexpected EOF while parsing escape"),
                            _   => loop,
                        }
                        self.advance(1);
                    }
                    EOF => {
                        return self.fail(~"Unexpected EOF while parsing string");
                    }
                    a => {
                        s.push_char(a);
                    }
                }
            }

        } else {
            fail!("Parser Error, parse_string called at the wrong time");
        }
    }

    priv fn parse_ident(&mut self) -> ParseResult {
        let c = self.peek();

        if self.char_is_read_macro(c) {
            return self.eval_read_macro(c);
        }

        let mut ident = ~"";

        loop {
            match self.peek() {
                EOF => return self.fail(~"Unexpected EOF while parsing ident"),
                c if self.char_is_read_macro(c) => {
                    return self.fail(fmt!("Unexpected character '%c' while parsing ident", c));
                }
                ')' => return Ok(@Symbol(ident)),
                c if c.is_whitespace() => return Ok(@Symbol(ident)),
                c => ident.push_char(c),
            }
            self.advance(1);
        }
    }

    priv fn skip_whitespace(&mut self) {
        while self.peek().is_whitespace() {
            self.advance(1)
        }
    }

    priv fn fail(&self, msg: ~str) -> ParseResult {
        ParseFailure::err(msg, self.pos)
    }

    priv fn slice_src(&self, len: uint) -> &'self str {
        self.src.slice(self.src_pos, self.src_pos+len)
    }

    priv fn pop(&mut self) -> char {
        let c = self.peek();
        self.advance(1);
        c
    }

    priv fn peek(&self) -> char {
        if self.eof() {
            EOF
        } else {
            self.src.char_at(self.src_pos)
        }
    }

    priv fn eat(&mut self, c: char) -> bool {
        if self.peek() == c {
            self.advance(1);
            true
        } else {
            false
        }
    }

    priv fn eat_str(&mut self, s: &str) -> bool {
        let slen = s.len();
        if (self.src_pos + slen) >= self.src_len {
            false
        } else {
            let slice = self.slice_src(slen);
            if slice == s {
                self.advance(s.char_len());
                true
            } else {
                false
            }
        }
    }

    priv fn advance(&mut self, n: uint) {
        if self.eof() { return; }
        let mut n = n;
        while n > 0 {
            let str::CharRange {ch:c, next:next} = str::char_range_at(self.src, self.src_pos);
            self.src_pos = next;
            n -= 1;
            self.pos.col += 1;
            if c == '\n' {
                self.pos.col = 1;
                self.pos.line += 1;
            }
        }
    }

    priv fn char_is_read_macro(&mut self, c: char) -> bool {
        match c {
            '\'' | '`' | '#' => true,
            _ => false
        }
    }

    priv fn eval_read_macro(&mut self, _: char) -> ParseResult {
        self.advance(1);
        self.parse()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parser_ok() {
        macro_rules! test(
            ($s:expr) => ({
                let src = $s.clone();
                assert_eq!(Parser::new(src).parse().get().to_str(), src)
            })
        )

        test!(~"1");
        test!(~"(def a (+ 1 2))");
        test!(~"(do (def a 1) (def b 2) (+ a b))");
        test!(~"(list (1 2) 3 (+ 4 5))");

        test!(~"(if true (fn (a b) (+ 1 a b)) (quote (1 2 3)))");

        test!(~"(foo bar \"a b c d\")");

        test!(~"(ö ä å)");

        test!(~"\"new-line:\\n\"");
    }

    #[test]
    fn test_parser_err() {
        macro_rules! test(
            ($s:expr) => ({
                let src = $s.clone();
                assert!(Parser::new(src).parse().is_err())
            })
        )

        test!(~"(");
        test!(~")");
        test!(~"\"no closing quote")
    }
}
<|endoftext|>


<commit_before>// examples/blinky.rs
//! Blinks an LED

#![feature(const_fn)]
#![feature(used)]
#![no_std]

// version = "0.2.0"
extern crate cortex_m_rt;

// version = "0.1.0"
#[macro_use]
extern crate cortex_m_rtfm as rtfm;
extern crate bluepill;
extern crate haldriver;

use bluepill::pin::{halPin, Pin, Mode};
use bluepill::frequency;
use bluepill::stm32f103xx::interrupt::Tim3;
use bluepill::stm32f103xx;
use bluepill::timer::{halTimer, Timer};
use rtfm::{Local, P0, P1, T0, T1, TMax};
use haldriver::stepper::ulnXXXX::{Stepper, halStepper, Direction};

// CONFIGURATION
const TICKS: u32 = 400_000;

// RESOURCES
peripherals!(stm32f103xx, {
    GPIOA: Peripheral {
        register_block: Gpioa,
        ceiling: C1,
    },
    RCC: Peripheral {
        register_block: Rcc,
        ceiling: C0,
    },
    TIM3: Peripheral {
        register_block: Tim3,
        ceiling: C1,
    },
    FLASH: Peripheral {
        register_block: Flash,
        ceiling: C0,
    },
});

// INITIALIZATION PHASE
fn init(ref priority: P0, threshold: &TMax) {
    let gpioa = GPIOA.access(priority, threshold);
    let rcc = RCC.access(priority, threshold);
    let tim3 = TIM3.access(priority, threshold);
    let flash = FLASH.access(priority, threshold);
    let timer = Timer::new(&**tim3);
    let in1 = Pin{pin: 1, port: &**gpioa};
    let in2 = Pin{pin: 2, port: &**gpioa};
    let in3 = Pin{pin: 3, port: &**gpioa};
    let in4 = Pin{pin: 4, port: &**gpioa};

    // set clock to 72Mhz
    frequency::init(&rcc, &flash, frequency::Speed::S72Mhz);

    // configure pins for output
    in1.init(&rcc, Mode::OUTPUT);
    in2.init(&rcc, Mode::OUTPUT);
    in3.init(&rcc, Mode::OUTPUT);
    in4.init(&rcc, Mode::OUTPUT);

    // Configure TIM2 for periodic update events
    timer.init(&rcc, TICKS);

    // Start the timer
    timer.resume();
}

// IDLE LOOP
fn idle(_priority: P0, _threshold: T0) -> ! {
    // Sleep
    loop {
        rtfm::wfi();
    }
}

// TASKS
tasks!(stm32f103xx, {
    periodic: Task {
        interrupt: Tim3,
        priority: P1,
        enabled: true,
    },
});

fn periodic(mut task: Tim3, ref priority: P1, ref threshold: T1) {
    // Task local data
    // have to track step manually since you can't persist
    // a stepper between calls to periodic
    static STEP: Local<u16, Tim3> = Local::new(0);

    let tim3 = TIM3.access(priority, threshold);
    let timer = Timer{timer: &**tim3};
    let gpioa = GPIOA.access(priority, threshold);
    let in1 = Pin{pin: 1, port: &**gpioa};
    let in2 = Pin{pin: 2, port: &**gpioa};
    let in3 = Pin{pin: 3, port: &**gpioa};
    let in4 = Pin{pin: 4, port: &**gpioa};

    if timer.clear_update_flag().is_ok() {
        let step = STEP.borrow_mut(&mut task);

        let mut stepper = Stepper{direction: Direction::RIGHT,
            index: *step,
            pin1: &in1,
            pin2: &in2,
            pin3: &in3,
            pin4: &in4,};

        stepper.step();

        if *step < 8 {
            *step += 1;
        } else {
            *step = 0;
        }
    } else {
        // Only reachable through `rtfm::request(periodic)`
        //#[cfg(debug_assertion)]
        //unreachable!()
    }
}
<commit_msg>speed it up again<commit_after>// examples/blinky.rs
//! Blinks an LED

#![feature(const_fn)]
#![feature(used)]
#![no_std]

// version = "0.2.0"
extern crate cortex_m_rt;

// version = "0.1.0"
#[macro_use]
extern crate cortex_m_rtfm as rtfm;
extern crate bluepill;
extern crate haldriver;

use bluepill::pin::{Pin, Mode};
use bluepill::frequency;
use bluepill::stm32f103xx::interrupt::Tim3;
use bluepill::stm32f103xx;
use bluepill::timer::{halTimer, Timer};
use rtfm::{Local, P0, P1, T0, T1, TMax};
use haldriver::stepper::ulnXXXX::{Stepper, halStepper, Direction};

// CONFIGURATION
const TICKS: u32 = 64_000;

// RESOURCES
peripherals!(stm32f103xx, {
    GPIOA: Peripheral {
        register_block: Gpioa,
        ceiling: C1,
    },
    RCC: Peripheral {
        register_block: Rcc,
        ceiling: C0,
    },
    TIM3: Peripheral {
        register_block: Tim3,
        ceiling: C1,
    },
    FLASH: Peripheral {
        register_block: Flash,
        ceiling: C0,
    },
});

// INITIALIZATION PHASE
fn init(ref priority: P0, threshold: &TMax) {
    let gpioa = GPIOA.access(priority, threshold);
    let rcc = RCC.access(priority, threshold);
    let tim3 = TIM3.access(priority, threshold);
    let flash = FLASH.access(priority, threshold);
    let timer = Timer::new(&**tim3);
    let in1 = Pin{pin: 1, port: &**gpioa};
    let in2 = Pin{pin: 2, port: &**gpioa};
    let in3 = Pin{pin: 3, port: &**gpioa};
    let in4 = Pin{pin: 4, port: &**gpioa};

    // set clock to 72Mhz
    frequency::init(&rcc, &flash, frequency::Speed::S32Mhz);

    // configure pins for output
    in1.init(&rcc, Mode::OUTPUT);
    in2.init(&rcc, Mode::OUTPUT);
    in3.init(&rcc, Mode::OUTPUT);
    in4.init(&rcc, Mode::OUTPUT);

    // Configure TIM2 for periodic update events
    timer.init(&rcc, TICKS);

    // Start the timer
    timer.resume();
}

// IDLE LOOP
fn idle(_priority: P0, _threshold: T0) -> ! {
    // Sleep
    loop {
        rtfm::wfi();
    }
}

// TASKS
tasks!(stm32f103xx, {
    periodic: Task {
        interrupt: Tim3,
        priority: P1,
        enabled: true,
    },
});

fn periodic(mut task: Tim3, ref priority: P1, ref threshold: T1) {
    // Task local data
    // have to track step manually since you can't persist
    // a stepper between calls to periodic
    static STEP: Local<u16, Tim3> = Local::new(0);

    let tim3 = TIM3.access(priority, threshold);
    let timer = Timer{timer: &**tim3};
    let gpioa = GPIOA.access(priority, threshold);
    let in1 = Pin{pin: 1, port: &**gpioa};
    let in2 = Pin{pin: 2, port: &**gpioa};
    let in3 = Pin{pin: 3, port: &**gpioa};
    let in4 = Pin{pin: 4, port: &**gpioa};

    if timer.clear_update_flag().is_ok() {
        let step = STEP.borrow_mut(&mut task);

        let mut stepper = Stepper{direction: Direction::RIGHT,
            index: *step,
            pin1: &in1,
            pin2: &in2,
            pin3: &in3,
            pin4: &in4,};

        stepper.step();

        if *step < 8 {
            *step += 1;
        } else {
            *step = 0;
        }
    } else {
        // Only reachable through `rtfm::request(periodic)`
        //#[cfg(debug_assertion)]
        //unreachable!()
    }
}
<|endoftext|>


<commit_before>extern crate enigo;

use enigo::Enigo;
use std::io::Write;

use std::{thread, time};

fn main() {
    let wait_time = time::Duration::from_millis(200);
    let mut enigo = Enigo::new();

    thread::sleep(wait_time);

    // Currently will not fail.
    write!(enigo, "Hello World").unwrap();
}
<commit_msg>fix stream example; write trait only implemented for linux<commit_after>extern crate enigo;

use enigo::Enigo;
use std::io::Write;

use std::{thread, time};

fn main() {
    let wait_time = time::Duration::from_millis(200);
    let mut enigo = Enigo::new();

    thread::sleep(wait_time);

    // Currently will not fail.
    #[cfg(target_os = "linux")]
    write!(enigo, "Hello World").unwrap();
}
<|endoftext|>


<commit_before>use std::fmt::{self, Display, Formatter};
use std::default::Default;
use rlua::{self, Table, Lua, UserData, ToLua, Value};
use super::object::{Object, Objectable};
use super::property::Property;
use super::class::{self, Class};
#[allow(deprecated)]
use rustwlc::xkb::Keysym;
use rustwlc::types::KeyMod;

#[derive(Clone, Debug)]
pub struct ButtonState {
    button: Option<i32>,
    modifiers: KeyMod
}

#[derive(Clone, Debug)]
pub struct Button<'lua>(Table<'lua>);

impl <'lua> Button<'lua> {
    pub fn button(&self) -> rlua::Result<Value<'lua>> {
        let button = self.0.get::<_, ButtonState>("data")?;
        Ok(button.button
            .map(|num| Value::Number(num as f64))
            .unwrap_or(Value::Nil))
    }

    pub fn set_button(&self, new_val: Option<i32>) -> rlua::Result<()> {
        let mut button = self.0.get::<_, ButtonState>("data")?;
        button.button = new_val;
        self.0.set("data", button)?;
        Ok(())
    }

    pub fn modifiers(&self) -> rlua::Result<KeyMod> {
        let button = self.0.get::<_, ButtonState>("data")?;
        Ok(button.modifiers)
    }

    pub fn set_modifiers(&self, mods: Table<'lua>) -> rlua::Result<()> {
        use ::lua::mods_to_rust;
        let mut button = self.0.get::<_, ButtonState>("data")?;
        button.modifiers = mods_to_rust(mods)?;
        self.0.set("data", button)?;
        Ok(())
    }
}

impl <'lua> ToLua<'lua> for Button<'lua> {
    fn to_lua(self, lua: &'lua Lua) -> rlua::Result<Value<'lua>> {
        self.0.to_lua(lua)
    }
}

impl <'lua> Objectable<'lua, Button<'lua>, ButtonState> for Button<'lua> {
    fn _wrap(table: Table<'lua>) -> Button {
        Button(table)
    }

    fn get_table(self) -> Table<'lua> {
        self.0
    }
}

impl Display for ButtonState {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "Button: {:p}", self)
    }
}

impl Default for ButtonState {
    fn default() -> Self {
        ButtonState {
            button: None,
            modifiers: KeyMod::empty()
        }
    }
}

impl UserData for ButtonState {}

/// Makes a new button stored in a table beside its signals
pub fn allocator(lua: &Lua) -> rlua::Result<Object> {
    let meta = lua.create_table();
    let class = class::button_class(lua)?;
    Ok(Button::new(lua, class)?
       .add_to_meta(meta)?
       .build())
}

pub fn new<'lua>(lua: &'lua Lua, _table: Table<'lua>)
                 -> rlua::Result<Object<'lua>> {
    allocator(lua)
}

pub fn init(lua: &Lua) -> rlua::Result<Class> {
    Class::new(lua, Some(allocator), None, None)?
        .method("__call".into(), lua.create_function(new))?
        .property(Property::new("button".into(),
                                Some(lua.create_function(set_button)),
                                Some(lua.create_function(get_button)),
                                Some(lua.create_function(set_button))))?
        .property(Property::new("modifiers".into(),
                                Some(lua.create_function(set_modifiers)),
                                Some(lua.create_function(get_modifiers)),
                                Some(lua.create_function(set_modifiers))))?
        .save_class("__button_class")?
        .build()
}

// TODO Try to see if I can make this pass in an Object,
// or even better a Button

fn set_button<'lua>(_: &'lua Lua, (table, num): (Table, i32))
                    -> rlua::Result<Value<'lua>> {
    let button = Button::cast(table.into())?;
    button.set_button(Some(num))?;
    Ok(Value::Nil)
}

fn get_button<'lua>(_: &'lua Lua, table: Table<'lua>)
                    -> rlua::Result<Value<'lua>> {
    Button::cast(table.into())?.button()
}

fn set_modifiers<'lua>(_: &'lua Lua, (table, modifiers): (Table, Table))
                       -> rlua::Result<Value<'lua>> {
    println!("called here");
    let button = Button::cast(table.into())?;
    button.set_modifiers(modifiers)?;
    Ok(Value::Nil)
}

fn get_modifiers<'lua>(lua: &'lua Lua, table: Table<'lua>)
                    -> rlua::Result<Value<'lua>> {
    use ::lua::mods_to_lua;
    mods_to_lua(lua, Button::cast(table.into())?.modifiers()?).map(Value::Table)
}

#[cfg(test)]
mod test {
    use rlua::{self, Table, Lua};
    use super::super::button;
    use super::super::object;

    #[test]
    fn button_object_test() {
        let lua = Lua::new();
        button::init(&lua).unwrap();
        lua.globals().set("button0", button::allocator(&lua).unwrap());
        lua.globals().set("button1", button::allocator(&lua).unwrap());
        lua.eval(r#"
 assert(button0.button == nil)
 assert(button1.button == nil)
 button0.connect_signal("test", function(button) button.button = 3 end)
 button0.emit_signal("test")
 assert(button1.button == nil)
 assert(button0.button == 3)
 "#,
        None).unwrap()
    }

    #[test]
    fn button_class_test() {
        let lua = Lua::new();
        let button_class = button::init(&lua).unwrap();
        lua.globals().set("button", button_class).unwrap();
        lua.eval(r#"
a_button = button()
assert(a_button.button == nil)
a_button.connect_signal("test", function(button) button.num = 2 end)
a_button.emit_signal("test")
assert(a_button.num == 2)
"#, None).unwrap()
    }

    #[test]
    fn button_property_test() {
        let lua = Lua::new();
        button::init(&lua).unwrap();
        let button_class = button::init(&lua).unwrap();
        assert_eq!(button_class.properties().unwrap().len().unwrap(), 2);
        lua.globals().set("button", button_class).unwrap();
        lua.eval(r#"
a_button = button()
assert(a_button.button == nil)
a_button.button = 5
assert(a_button.button == 5)
"#, None).unwrap()
    }

    #[test]
    fn button_remove_signal_test() {
        let lua = Lua::new();
        let button_class = button::init(&lua).unwrap();
        lua.globals().set("button", button_class).unwrap();
        lua.eval(r#"
button0 = button()
assert(button0.button == nil)
button0.connect_signal("test", function(button) button.button = 3 end)
button0.emit_signal("test")
assert(button0.button == 3)
button0.button = 0
button0.disconnect_signal("test")
button0.emit_signal("test")
assert(button0.button == 0)
"#, None).unwrap()
    }

    #[test]
    fn button_emit_signal_multiple_args() {
        let lua = Lua::new();
        button::init(&lua).unwrap();
        lua.globals().set("a_button", button::allocator(&lua).unwrap());
        lua.eval(r#"
 assert(a_button.button == nil)
 a_button.connect_signal("test", function(button, num) button.button = num end)
 a_button.emit_signal("test", 5)
 assert(a_button.button == 5)
 a_button.emit_signal("test", -1)
 assert(a_button.button == -1)
 a_button.emit_signal("test", nil)
 assert(a_button.button == nil)
 "#, None).unwrap()
    }

    #[test]
    fn button_modifiers_test() {
        use rustwlc::*;
        use self::button::Button;
        use self::object::{Object, Objectable};
        let lua = Lua::new();
        button::init(&lua).unwrap();
        lua.globals().set("a_button", button::allocator(&lua).unwrap());
        let button = Button::cast(lua.globals().get::<_, Table>("a_button")
                                  .unwrap().into()).unwrap();
        assert_eq!(button.modifiers().unwrap(), KeyMod::empty());
        lua.eval::<()>(r#"
a_button.modifiers = { "Caps" }
"#, None).unwrap();
        assert_eq!(button.modifiers().unwrap(), MOD_CAPS);
    }
}

<commit_msg>Fixed old tests that didn't really use UserData<commit_after>use std::fmt::{self, Display, Formatter};
use std::default::Default;
use rlua::{self, Table, Lua, UserData, ToLua, Value};
use super::object::{Object, Objectable};
use super::property::Property;
use super::class::{self, Class};
#[allow(deprecated)]
use rustwlc::xkb::Keysym;
use rustwlc::types::KeyMod;

#[derive(Clone, Debug)]
pub struct ButtonState {
    button: Option<i32>,
    modifiers: KeyMod
}

#[derive(Clone, Debug)]
pub struct Button<'lua>(Table<'lua>);

impl <'lua> Button<'lua> {
    pub fn button(&self) -> rlua::Result<Value<'lua>> {
        let button = self.0.get::<_, ButtonState>("data")?;
        Ok(button.button
            .map(|num| Value::Number(num as f64))
            .unwrap_or(Value::Nil))
    }

    pub fn set_button(&self, new_val: Option<i32>) -> rlua::Result<()> {
        let mut button = self.0.get::<_, ButtonState>("data")?;
        button.button = new_val;
        self.0.set("data", button)?;
        Ok(())
    }

    pub fn modifiers(&self) -> rlua::Result<KeyMod> {
        let button = self.0.get::<_, ButtonState>("data")?;
        Ok(button.modifiers)
    }

    pub fn set_modifiers(&self, mods: Table<'lua>) -> rlua::Result<()> {
        use ::lua::mods_to_rust;
        let mut button = self.0.get::<_, ButtonState>("data")?;
        button.modifiers = mods_to_rust(mods)?;
        self.0.set("data", button)?;
        Ok(())
    }
}

impl <'lua> ToLua<'lua> for Button<'lua> {
    fn to_lua(self, lua: &'lua Lua) -> rlua::Result<Value<'lua>> {
        self.0.to_lua(lua)
    }
}

impl <'lua> Objectable<'lua, Button<'lua>, ButtonState> for Button<'lua> {
    fn _wrap(table: Table<'lua>) -> Button {
        Button(table)
    }

    fn get_table(self) -> Table<'lua> {
        self.0
    }
}

impl Display for ButtonState {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "Button: {:p}", self)
    }
}

impl Default for ButtonState {
    fn default() -> Self {
        ButtonState {
            button: None,
            modifiers: KeyMod::empty()
        }
    }
}

impl UserData for ButtonState {}

/// Makes a new button stored in a table beside its signals
pub fn allocator(lua: &Lua) -> rlua::Result<Object> {
    let meta = lua.create_table();
    let class = class::button_class(lua)?;
    Ok(Button::new(lua, class)?
       .add_to_meta(meta)?
       .build())
}

pub fn new<'lua>(lua: &'lua Lua, _table: Table<'lua>)
                 -> rlua::Result<Object<'lua>> {
    allocator(lua)
}

pub fn init(lua: &Lua) -> rlua::Result<Class> {
    Class::new(lua, Some(allocator), None, None)?
        .method("__call".into(), lua.create_function(new))?
        .property(Property::new("button".into(),
                                Some(lua.create_function(set_button)),
                                Some(lua.create_function(get_button)),
                                Some(lua.create_function(set_button))))?
        .property(Property::new("modifiers".into(),
                                Some(lua.create_function(set_modifiers)),
                                Some(lua.create_function(get_modifiers)),
                                Some(lua.create_function(set_modifiers))))?
        .save_class("__button_class")?
        .build()
}

// TODO Try to see if I can make this pass in an Object,
// or even better a Button

fn set_button<'lua>(_: &'lua Lua, (table, val): (Table, Value))
                    -> rlua::Result<Value<'lua>> {
    use rlua::Value::*;
    let button = Button::cast(table.into())?;
    match val {
        Number(num) => button.set_button(Some(num as _))?,
        Integer(num) => button.set_button(Some(num as _))?,
        _ => button.set_button(None)?
    }
    Ok(Value::Nil)
}

fn get_button<'lua>(_: &'lua Lua, table: Table<'lua>)
                    -> rlua::Result<Value<'lua>> {
    Button::cast(table.into())?.button()
}

fn set_modifiers<'lua>(_: &'lua Lua, (table, modifiers): (Table, Table))
                       -> rlua::Result<Value<'lua>> {
    let button = Button::cast(table.into())?;
    button.set_modifiers(modifiers)?;
    Ok(Value::Nil)
}

fn get_modifiers<'lua>(lua: &'lua Lua, table: Table<'lua>)
                    -> rlua::Result<Value<'lua>> {
    use ::lua::mods_to_lua;
    mods_to_lua(lua, Button::cast(table.into())?.modifiers()?).map(Value::Table)
}

#[cfg(test)]
mod test {
    use rlua::{self, Table, Lua};
    use super::super::button;
    use super::super::object;

    #[test]
    fn button_object_test() {
        let lua = Lua::new();
        button::init(&lua).unwrap();
        lua.globals().set("button0", button::allocator(&lua).unwrap());
        lua.globals().set("button1", button::allocator(&lua).unwrap());
        lua.eval(r#"
assert(button0.button == nil)
assert(button1.button == nil)
button0.connect_signal("test", function(button) button.button = 3 end)
button0.emit_signal("test")
assert(button1.button == nil)
assert(button0.button == 3)
"#, None).unwrap()
    }

    #[test]
    fn button_class_test() {
        let lua = Lua::new();
        let button_class = button::init(&lua).unwrap();
        lua.globals().set("button", button_class).unwrap();
        lua.eval(r#"
a_button = button()
assert(a_button.button == nil)
a_button.connect_signal("test", function(button) button.button = 2 end)
a_button.emit_signal("test")
assert(a_button.button == 2)
"#, None).unwrap()
    }

    #[test]
    fn button_property_test() {
        let lua = Lua::new();
        button::init(&lua).unwrap();
        let button_class = button::init(&lua).unwrap();
        assert_eq!(button_class.properties().unwrap().len().unwrap(), 2);
        lua.globals().set("button", button_class).unwrap();
        lua.eval(r#"
a_button = button()
assert(a_button.button == nil)
a_button.button = 5
assert(a_button.button == 5)
"#, None).unwrap()
    }

    #[test]
    fn button_remove_signal_test() {
        let lua = Lua::new();
        let button_class = button::init(&lua).unwrap();
        lua.globals().set("button", button_class).unwrap();
        lua.eval(r#"
button0 = button()
assert(button0.button == nil)
button0.connect_signal("test", function(button) button.button = 3 end)
button0.emit_signal("test")
assert(button0.button == 3)
button0.button = 0
button0.disconnect_signal("test")
button0.emit_signal("test")
assert(button0.button == 0)
"#, None).unwrap()
    }

    #[test]
    fn button_emit_signal_multiple_args() {
        let lua = Lua::new();
        button::init(&lua).unwrap();
        lua.globals().set("a_button", button::allocator(&lua).unwrap());
        lua.eval(r#"
 assert(a_button.button == nil)
 a_button.connect_signal("test", function(button, num) button.button = num end)
 a_button.emit_signal("test", 5)
 assert(a_button.button == 5)
 a_button.emit_signal("test", -1)
 assert(a_button.button == -1)
 a_button.emit_signal("test", nil)
 assert(a_button.button == nil)
 "#, None).unwrap()
    }

    #[test]
    fn button_modifiers_test() {
        use rustwlc::*;
        use self::button::Button;
        use self::object::{Object, Objectable};
        let lua = Lua::new();
        button::init(&lua).unwrap();
        lua.globals().set("a_button", button::allocator(&lua).unwrap());
        let button = Button::cast(lua.globals().get::<_, Table>("a_button")
                                  .unwrap().into()).unwrap();
        assert_eq!(button.modifiers().unwrap(), KeyMod::empty());
        lua.eval::<()>(r#"
a_button.modifiers = { "Caps" }
"#, None).unwrap();
        assert_eq!(button.modifiers().unwrap(), MOD_CAPS);
    }
}

<|endoftext|>