<commit_before>use rustc::lint::*;
use rustc::ty;
use rustc::hir::*;
use utils::{is_copy, match_def_path, opt_def_id, paths, span_note_and_lint};

/// **What it does:** Checks for calls to `std::mem::drop` with a reference
/// instead of an owned value.
///
/// **Why is this bad?** Calling `drop` on a reference will only drop the
/// reference itself, which is a no-op. It will not call the `drop` method (from
/// the `Drop` trait implementation) on the underlying referenced value, which
/// is likely what was intended.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// let mut lock_guard = mutex.lock();
/// std::mem::drop(&lock_guard) // Should have been drop(lock_guard), mutex
/// still locked
/// operation_that_requires_mutex_to_be_unlocked();
/// ```
declare_clippy_lint! {
    pub DROP_REF,
    correctness,
    "calls to `std::mem::drop` with a reference instead of an owned value"
}

/// **What it does:** Checks for calls to `std::mem::forget` with a reference
/// instead of an owned value.
///
/// **Why is this bad?** Calling `forget` on a reference will only forget the
/// reference itself, which is a no-op. It will not forget the underlying
/// referenced
/// value, which is likely what was intended.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// let x = Box::new(1);
/// std::mem::forget(&x) // Should have been forget(x), x will still be dropped
/// ```
declare_clippy_lint! {
    pub FORGET_REF,
    correctness,
    "calls to `std::mem::forget` with a reference instead of an owned value"
}

/// **What it does:** Checks for calls to `std::mem::drop` with a value
/// that derives the Copy trait
///
/// **Why is this bad?** Calling `std::mem::drop` [does nothing for types that
/// implement Copy](https://doc.rust-lang.org/std/mem/fn.drop.html), since the
/// value will be copied and moved into the function on invocation.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// let x:i32 = 42;   // i32 implements Copy
/// std::mem::drop(x) // A copy of x is passed to the function, leaving the
/// original unaffected
/// ```
declare_clippy_lint! {
    pub DROP_COPY,
    correctness,
    "calls to `std::mem::drop` with a value that implements Copy"
}

/// **What it does:** Checks for calls to `std::mem::forget` with a value that
/// derives the Copy trait
///
/// **Why is this bad?** Calling `std::mem::forget` [does nothing for types that
/// implement Copy](https://doc.rust-lang.org/std/mem/fn.drop.html) since the
/// value will be copied and moved into the function on invocation.
///
/// An alternative, but also valid, explanation is that Copy types do not
/// implement
/// the Drop trait, which means they have no destructors. Without a destructor,
/// there
/// is nothing for `std::mem::forget` to ignore.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// let x:i32 = 42;     // i32 implements Copy
/// std::mem::forget(x) // A copy of x is passed to the function, leaving the
/// original unaffected
/// ```
declare_clippy_lint! {
    pub FORGET_COPY,
    correctness,
    "calls to `std::mem::forget` with a value that implements Copy"
}

const DROP_REF_SUMMARY: &str = "calls to `std::mem::drop` with a reference instead of an owned value. \
                                Dropping a reference does nothing.";
const FORGET_REF_SUMMARY: &str = "calls to `std::mem::forget` with a reference instead of an owned value. \
                                  Forgetting a reference does nothing.";
const DROP_COPY_SUMMARY: &str = "calls to `std::mem::drop` with a value that implements Copy. \
                                 Dropping a copy leaves the original intact.";
const FORGET_COPY_SUMMARY: &str = "calls to `std::mem::forget` with a value that implements Copy. \
                                   Forgetting a copy leaves the original intact.";

#[allow(missing_copy_implementations)]
pub struct Pass;

impl LintPass for Pass {
    fn get_lints(&self) -> LintArray {
        lint_array!(DROP_REF, FORGET_REF, DROP_COPY, FORGET_COPY)
    }
}

impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
    fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
        if_chain! {
            if let ExprCall(ref path, ref args) = expr.node;
            if let ExprPath(ref qpath) = path.node;
            if args.len() == 1;
            if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, path.hir_id));
            then {
                let lint;
                let msg;
                let arg = &args[0];
                let arg_ty = cx.tables.expr_ty(arg);

                if let ty::TyRef(..) = arg_ty.sty {
                    if match_def_path(cx.tcx, def_id, &paths::DROP) {
                        lint = DROP_REF;
                        msg = DROP_REF_SUMMARY.to_string();
                    } else if match_def_path(cx.tcx, def_id, &paths::MEM_FORGET) {
                        lint = FORGET_REF;
                        msg = FORGET_REF_SUMMARY.to_string();
                    } else {
                        return;
                    }
                    span_note_and_lint(cx,
                                       lint,
                                       expr.span,
                                       &msg,
                                       arg.span,
                                       &format!("argument has type {}", arg_ty));
                } else if is_copy(cx, arg_ty) {
                    if match_def_path(cx.tcx, def_id, &paths::DROP) {
                        lint = DROP_COPY;
                        msg = DROP_COPY_SUMMARY.to_string();
                    } else if match_def_path(cx.tcx, def_id, &paths::MEM_FORGET) {
                        lint = FORGET_COPY;
                        msg = FORGET_COPY_SUMMARY.to_string();
                    } else {
                        return;
                    }
                    span_note_and_lint(cx,
                                       lint,
                                       expr.span,
                                       &msg,
                                       arg.span,
                                       &format!("argument has type {}", arg_ty));
                }
            }
        }
    }
}
<commit_msg>Fix missing line comment in drop_ref example<commit_after>use rustc::lint::*;
use rustc::ty;
use rustc::hir::*;
use utils::{is_copy, match_def_path, opt_def_id, paths, span_note_and_lint};

/// **What it does:** Checks for calls to `std::mem::drop` with a reference
/// instead of an owned value.
///
/// **Why is this bad?** Calling `drop` on a reference will only drop the
/// reference itself, which is a no-op. It will not call the `drop` method (from
/// the `Drop` trait implementation) on the underlying referenced value, which
/// is likely what was intended.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// let mut lock_guard = mutex.lock();
/// std::mem::drop(&lock_guard) // Should have been drop(lock_guard), mutex
/// // still locked
/// operation_that_requires_mutex_to_be_unlocked();
/// ```
declare_clippy_lint! {
    pub DROP_REF,
    correctness,
    "calls to `std::mem::drop` with a reference instead of an owned value"
}

/// **What it does:** Checks for calls to `std::mem::forget` with a reference
/// instead of an owned value.
///
/// **Why is this bad?** Calling `forget` on a reference will only forget the
/// reference itself, which is a no-op. It will not forget the underlying
/// referenced
/// value, which is likely what was intended.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// let x = Box::new(1);
/// std::mem::forget(&x) // Should have been forget(x), x will still be dropped
/// ```
declare_clippy_lint! {
    pub FORGET_REF,
    correctness,
    "calls to `std::mem::forget` with a reference instead of an owned value"
}

/// **What it does:** Checks for calls to `std::mem::drop` with a value
/// that derives the Copy trait
///
/// **Why is this bad?** Calling `std::mem::drop` [does nothing for types that
/// implement Copy](https://doc.rust-lang.org/std/mem/fn.drop.html), since the
/// value will be copied and moved into the function on invocation.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// let x:i32 = 42;   // i32 implements Copy
/// std::mem::drop(x) // A copy of x is passed to the function, leaving the
/// original unaffected
/// ```
declare_clippy_lint! {
    pub DROP_COPY,
    correctness,
    "calls to `std::mem::drop` with a value that implements Copy"
}

/// **What it does:** Checks for calls to `std::mem::forget` with a value that
/// derives the Copy trait
///
/// **Why is this bad?** Calling `std::mem::forget` [does nothing for types that
/// implement Copy](https://doc.rust-lang.org/std/mem/fn.drop.html) since the
/// value will be copied and moved into the function on invocation.
///
/// An alternative, but also valid, explanation is that Copy types do not
/// implement
/// the Drop trait, which means they have no destructors. Without a destructor,
/// there
/// is nothing for `std::mem::forget` to ignore.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// let x:i32 = 42;     // i32 implements Copy
/// std::mem::forget(x) // A copy of x is passed to the function, leaving the
/// original unaffected
/// ```
declare_clippy_lint! {
    pub FORGET_COPY,
    correctness,
    "calls to `std::mem::forget` with a value that implements Copy"
}

const DROP_REF_SUMMARY: &str = "calls to `std::mem::drop` with a reference instead of an owned value. \
                                Dropping a reference does nothing.";
const FORGET_REF_SUMMARY: &str = "calls to `std::mem::forget` with a reference instead of an owned value. \
                                  Forgetting a reference does nothing.";
const DROP_COPY_SUMMARY: &str = "calls to `std::mem::drop` with a value that implements Copy. \
                                 Dropping a copy leaves the original intact.";
const FORGET_COPY_SUMMARY: &str = "calls to `std::mem::forget` with a value that implements Copy. \
                                   Forgetting a copy leaves the original intact.";

#[allow(missing_copy_implementations)]
pub struct Pass;

impl LintPass for Pass {
    fn get_lints(&self) -> LintArray {
        lint_array!(DROP_REF, FORGET_REF, DROP_COPY, FORGET_COPY)
    }
}

impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
    fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
        if_chain! {
            if let ExprCall(ref path, ref args) = expr.node;
            if let ExprPath(ref qpath) = path.node;
            if args.len() == 1;
            if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, path.hir_id));
            then {
                let lint;
                let msg;
                let arg = &args[0];
                let arg_ty = cx.tables.expr_ty(arg);

                if let ty::TyRef(..) = arg_ty.sty {
                    if match_def_path(cx.tcx, def_id, &paths::DROP) {
                        lint = DROP_REF;
                        msg = DROP_REF_SUMMARY.to_string();
                    } else if match_def_path(cx.tcx, def_id, &paths::MEM_FORGET) {
                        lint = FORGET_REF;
                        msg = FORGET_REF_SUMMARY.to_string();
                    } else {
                        return;
                    }
                    span_note_and_lint(cx,
                                       lint,
                                       expr.span,
                                       &msg,
                                       arg.span,
                                       &format!("argument has type {}", arg_ty));
                } else if is_copy(cx, arg_ty) {
                    if match_def_path(cx.tcx, def_id, &paths::DROP) {
                        lint = DROP_COPY;
                        msg = DROP_COPY_SUMMARY.to_string();
                    } else if match_def_path(cx.tcx, def_id, &paths::MEM_FORGET) {
                        lint = FORGET_COPY;
                        msg = FORGET_COPY_SUMMARY.to_string();
                    } else {
                        return;
                    }
                    span_note_and_lint(cx,
                                       lint,
                                       expr.span,
                                       &msg,
                                       arg.span,
                                       &format!("argument has type {}", arg_ty));
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>trait User{
    fn test();
    /// empty doc
    //~^ ERROR found a documentation comment that doesn't document anything
}
fn main() {}<commit_msg>tidy test<commit_after>trait User{
    fn test();
    /// empty doc
    //~^ ERROR found a documentation comment that doesn't document anything
}
fn main() {}
<|endoftext|>


<commit_before>extern crate classfile_parser;
extern crate nom;

use classfile_parser::class_parser;
use classfile_parser::constant_info::ConstantInfo;

#[test]
fn test_valid_class() {
    let valid_class = include_bytes!("../java-assets/compiled-classes/BasicClass.class");
    let res = class_parser(valid_class);
    match res {
        Result::Ok((_, c)) => {
            println!("Valid class file, version {},{} const_pool({}), this=const[{}], super=const[{}], interfaces({}), fields({}), methods({}), attributes({}), access({:?})", c.major_version, c.minor_version, c.const_pool_size, c.this_class, c.super_class, c.interfaces_count, c.fields_count, c.methods_count, c.attributes_count, c.access_flags);

            let mut code_const_index = 0;

            println!("Constant pool:");
            for (const_index, const_item) in c.const_pool.iter().enumerate() {
                println!("\t[{}] = {:?}", (const_index + 1), const_item);
                match *const_item {
                    ConstantInfo::Utf8(ref c) => {
                        if c.utf8_string == "Code" {
                            code_const_index = (const_index + 1) as u16;
                        }
                    }
                    _ => {}
                }
            }
            println!("Code index = {}", code_const_index);

            println!("Interfaces:");
            let mut interface_index = 0;
            for i in &c.interfaces {
                println!(
                    "\t[{}] = const[{}] = {:?}",
                    interface_index,
                    i,
                    c.const_pool[(i - 1) as usize]
                );

                interface_index += 1;
            }
            println!("Fields:");
            let mut field_index = 0;
            for f in &c.fields {
                println!(
                    "\t[{}] Name(const[{}] = {:?}) - access({:?})",
                    field_index,
                    f.name_index,
                    c.const_pool[(f.name_index - 1) as usize],
                    f.access_flags
                );
                field_index += 1;
            }
            println!("Methods:");
            let mut method_index = 0;
            for m in &c.methods {
                println!(
                    "\t[{}] Name(const[{}] = {:?}) - access({:?})",
                    method_index,
                    m.name_index,
                    c.const_pool[(m.name_index - 1) as usize],
                    m.access_flags
                );
                method_index += 1;

                for a in &m.attributes {
                    if a.attribute_name_index == code_const_index {
                        println!("\t\tCode attr found, len = {}", a.attribute_length);
                        let code_result =
                            classfile_parser::attribute_info::code_attribute_parser(&a.info);
                        match code_result {
                            Result::Ok((_, code)) => {
                                println!("\t\t\tCode! code_length = {}", code.code_length);
                            }
                            _ => panic!("Not a valid code attr?"),
                        }
                    } else {
                        println!("\t\tAttribute: {:?}", a);
                    }
                }
            }
        }
        _ => panic!("Not a class file"),
    };
}

#[test]
fn test_utf_string_constants() {
    let valid_class = include_bytes!("../java-assets/compiled-classes/UnicodeStrings.class");
    let res = class_parser(valid_class);
    match res {
        Result::Ok((_, c)) => {
            let mut found_utf_maths_string = false;
            let mut found_utf_runes_string = false;
            let mut found_utf_braille_string = false;
            let mut found_utf_modified_string = false;
            let mut found_utf_unpaired_string = false;
            for (const_index, const_item) in c.const_pool.iter().enumerate() {
                println!("\t[{}] = {:?}", (const_index + 1), const_item);
                match *const_item {
                    ConstantInfo::Utf8(ref c) => {
                        if c.utf8_string == "2H₂ + O₂ ⇌ 2H₂O, R = 4.7 kΩ, ⌀ 200 mm" {
                            found_utf_maths_string = true;
                        }
                        if c.utf8_string == "ᚻᛖ ᚳᚹᚫᚦ ᚦᚫᛏ ᚻᛖ ᛒᚢᛞᛖ ᚩᚾ ᚦᚫᛗ ᛚᚪᚾᛞᛖ ᚾᚩᚱᚦᚹᛖᚪᚱᛞᚢᛗ ᚹᛁᚦ ᚦᚪ ᚹᛖᛥᚫ" {
                            found_utf_runes_string = true;
                        }
                        if c.utf8_string
                            == "⡌⠁⠧⠑ ⠼⠁⠒  ⡍⠜⠇⠑⠹⠰⠎ ⡣⠕⠌"
                        {
                            found_utf_braille_string = true;
                        }
                        if c.utf8_string == "\0𠜎" {
                            found_utf_modified_string = true;
                        }
                        if c.utf8_string == "X���X" && c.bytes.len() == 5 {
                            found_utf_unpaired_string = true;
                        }
                    }
                    _ => {}
                }
            }

            assert!(
                found_utf_maths_string
                    & found_utf_runes_string
                    & found_utf_braille_string
                    & found_utf_modified_string
                    & found_utf_unpaired_string,
                "Failed to find unicode strings"
            );
        }
        _ => panic!("Not a class file"),
    }
}

#[test]
fn test_malformed_class() {
    let malformed_class = include_bytes!("../java-assets/compiled-classes/malformed.class");
    let res = class_parser(malformed_class);
    match res {
        Result::Ok((_, _)) => panic!("The file is not valid and shouldn't be parsed"),
        _ => {}
    };
}

// #[test]
// fn test_constant_utf8() {
//     let hello_world_data = &[
//         // 0x01, // tag = 1
//         0x00, 0x0C, // length = 12
//         0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64, 0x21 // 'Hello world!' in UTF8
//     ];
//     let res = const_utf8(hello_world_data);

//     match res {
//         Result::Ok((_, c)) =>
//         match c {
//             Constant::Utf8(ref s) =>
//                  println!("Valid UTF8 const: {}", s.utf8_string),
//             _ => panic!("It's a const, but of what type?")
//         },
//         _ => panic!("Not a UTF type const?"),
//     };
// }
<commit_msg>formatting change due to rustfmt updates<commit_after>extern crate classfile_parser;
extern crate nom;

use classfile_parser::class_parser;
use classfile_parser::constant_info::ConstantInfo;

#[test]
fn test_valid_class() {
    let valid_class = include_bytes!("../java-assets/compiled-classes/BasicClass.class");
    let res = class_parser(valid_class);
    match res {
        Result::Ok((_, c)) => {
            println!("Valid class file, version {},{} const_pool({}), this=const[{}], super=const[{}], interfaces({}), fields({}), methods({}), attributes({}), access({:?})", c.major_version, c.minor_version, c.const_pool_size, c.this_class, c.super_class, c.interfaces_count, c.fields_count, c.methods_count, c.attributes_count, c.access_flags);

            let mut code_const_index = 0;

            println!("Constant pool:");
            for (const_index, const_item) in c.const_pool.iter().enumerate() {
                println!("\t[{}] = {:?}", (const_index + 1), const_item);
                match *const_item {
                    ConstantInfo::Utf8(ref c) => {
                        if c.utf8_string == "Code" {
                            code_const_index = (const_index + 1) as u16;
                        }
                    }
                    _ => {}
                }
            }
            println!("Code index = {}", code_const_index);

            println!("Interfaces:");
            let mut interface_index = 0;
            for i in &c.interfaces {
                println!(
                    "\t[{}] = const[{}] = {:?}",
                    interface_index,
                    i,
                    c.const_pool[(i - 1) as usize]
                );

                interface_index += 1;
            }
            println!("Fields:");
            let mut field_index = 0;
            for f in &c.fields {
                println!(
                    "\t[{}] Name(const[{}] = {:?}) - access({:?})",
                    field_index,
                    f.name_index,
                    c.const_pool[(f.name_index - 1) as usize],
                    f.access_flags
                );
                field_index += 1;
            }
            println!("Methods:");
            let mut method_index = 0;
            for m in &c.methods {
                println!(
                    "\t[{}] Name(const[{}] = {:?}) - access({:?})",
                    method_index,
                    m.name_index,
                    c.const_pool[(m.name_index - 1) as usize],
                    m.access_flags
                );
                method_index += 1;

                for a in &m.attributes {
                    if a.attribute_name_index == code_const_index {
                        println!("\t\tCode attr found, len = {}", a.attribute_length);
                        let code_result =
                            classfile_parser::attribute_info::code_attribute_parser(&a.info);
                        match code_result {
                            Result::Ok((_, code)) => {
                                println!("\t\t\tCode! code_length = {}", code.code_length);
                            }
                            _ => panic!("Not a valid code attr?"),
                        }
                    } else {
                        println!("\t\tAttribute: {:?}", a);
                    }
                }
            }
        }
        _ => panic!("Not a class file"),
    };
}

#[test]
fn test_utf_string_constants() {
    let valid_class = include_bytes!("../java-assets/compiled-classes/UnicodeStrings.class");
    let res = class_parser(valid_class);
    match res {
        Result::Ok((_, c)) => {
            let mut found_utf_maths_string = false;
            let mut found_utf_runes_string = false;
            let mut found_utf_braille_string = false;
            let mut found_utf_modified_string = false;
            let mut found_utf_unpaired_string = false;
            for (const_index, const_item) in c.const_pool.iter().enumerate() {
                println!("\t[{}] = {:?}", (const_index + 1), const_item);
                match *const_item {
                    ConstantInfo::Utf8(ref c) => {
                        if c.utf8_string == "2H₂ + O₂ ⇌ 2H₂O, R = 4.7 kΩ, ⌀ 200 mm" {
                            found_utf_maths_string = true;
                        }
                        if c.utf8_string
                            == "ᚻᛖ ᚳᚹᚫᚦ ᚦᚫᛏ ᚻᛖ ᛒᚢᛞᛖ ᚩᚾ ᚦᚫᛗ ᛚᚪᚾᛞᛖ ᚾᚩᚱᚦᚹᛖᚪᚱᛞᚢᛗ ᚹᛁᚦ ᚦᚪ ᚹᛖᛥᚫ"
                        {
                            found_utf_runes_string = true;
                        }
                        if c.utf8_string == "⡌⠁⠧⠑ ⠼⠁⠒  ⡍⠜⠇⠑⠹⠰⠎ ⡣⠕⠌"
                        {
                            found_utf_braille_string = true;
                        }
                        if c.utf8_string == "\0𠜎" {
                            found_utf_modified_string = true;
                        }
                        if c.utf8_string == "X���X" && c.bytes.len() == 5 {
                            found_utf_unpaired_string = true;
                        }
                    }
                    _ => {}
                }
            }

            assert!(
                found_utf_maths_string
                    & found_utf_runes_string
                    & found_utf_braille_string
                    & found_utf_modified_string
                    & found_utf_unpaired_string,
                "Failed to find unicode strings"
            );
        }
        _ => panic!("Not a class file"),
    }
}

#[test]
fn test_malformed_class() {
    let malformed_class = include_bytes!("../java-assets/compiled-classes/malformed.class");
    let res = class_parser(malformed_class);
    match res {
        Result::Ok((_, _)) => panic!("The file is not valid and shouldn't be parsed"),
        _ => {}
    };
}

// #[test]
// fn test_constant_utf8() {
//     let hello_world_data = &[
//         // 0x01, // tag = 1
//         0x00, 0x0C, // length = 12
//         0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64, 0x21 // 'Hello world!' in UTF8
//     ];
//     let res = const_utf8(hello_world_data);

//     match res {
//         Result::Ok((_, c)) =>
//         match c {
//             Constant::Utf8(ref s) =>
//                  println!("Valid UTF8 const: {}", s.utf8_string),
//             _ => panic!("It's a const, but of what type?")
//         },
//         _ => panic!("Not a UTF type const?"),
//     };
// }
<|endoftext|>


<commit_before>//! Implements some common utilities for the examples

use std::io;
use lua;

pub fn repl(L: &mut lua::State) {
    let mut stdin = io::buffered::BufferedReader::new(io::stdin());
    let stdout = &mut io::stdout() as &mut io::Writer;
    let stderr = &mut io::stderr() as &mut io::Writer;
    loop {
        L.settop(0); // clear the stack
        write!(stdout, "> ");
        stdout.flush();
        let line = io::io_error::cond.trap(|err| {
            if err.kind == io::EndOfFile {
                write!(stdout, "\n");
                // squelch
            } else {
                fail!(err)
            }
        }).inside(|| stdin.read_line());
        let mut line = if line.is_some() { line.unwrap() } else { break };
        if line.starts_with("=") {
            line = format!("return {}", line.slice_from(1));
        }
        match L.loadbuffer(line, "=stdin") {
            Ok(_) => (),
            Err(err) => { writeln!(stderr, "{}", err.to_str()); continue; }
        }
        match L.pcall(0, lua::MULTRET, 0) {
            Ok(_) => (),
            Err(_) => {
                match L.tostring(-1) {
                    Some(msg) => writeln!(stderr, "{}", msg),
                    None => writeln!(stderr, "(error object is not a string)")
                }
            }
        }
        if L.gettop() > 0 {
            L.getglobal("print");
            L.insert(1);
            let nargs = L.gettop()-1;
            match L.pcall(nargs, 0, 0) {
                Ok(_) => (),
                Err(_) => {
                    writeln!(stderr, "error calling 'print' ({})",
                             L.tostring(-1).unwrap_or_default());
                    continue;
                }
            }
        }
    }
}
<commit_msg>Stop trying to catch EndOfFile errors in the examples<commit_after>//! Implements some common utilities for the examples

use std::io;
use std::io::buffered::BufferedReader;
use lua;

pub fn repl(L: &mut lua::State) {
    let mut stdin = BufferedReader::new(io::stdin());
    let stdout = &mut io::stdout() as &mut io::Writer;
    let stderr = &mut io::stderr() as &mut io::Writer;
    while !stdin.eof() {
        L.settop(0); // clear the stack
        write!(stdout, "> ");
        stdout.flush();
        let line = stdin.read_line();
        let mut line = if line.is_some() { line.unwrap() } else { break };
        if line.starts_with("=") {
            line = format!("return {}", line.slice_from(1));
        }
        match L.loadbuffer(line, "=stdin") {
            Ok(_) => (),
            Err(err) => { writeln!(stderr, "{}", err.to_str()); continue; }
        }
        match L.pcall(0, lua::MULTRET, 0) {
            Ok(_) => (),
            Err(_) => {
                match L.tostring(-1) {
                    Some(msg) => writeln!(stderr, "{}", msg),
                    None => writeln!(stderr, "(error object is not a string)")
                }
            }
        }
        if L.gettop() > 0 {
            L.getglobal("print");
            L.insert(1);
            let nargs = L.gettop()-1;
            match L.pcall(nargs, 0, 0) {
                Ok(_) => (),
                Err(_) => {
                    writeln!(stderr, "error calling 'print' ({})",
                             L.tostring(-1).unwrap_or_default());
                    continue;
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>extern crate parity_wasm;

use std::env::args;

use parity_wasm::{interpreter, ModuleInstanceInterface, RuntimeValue};
use parity_wasm::elements::{Internal, External, Type, FunctionType, ValueType};

fn main() {
    let args: Vec<_> = args().collect();
    if args.len() < 3 {
        println!("Usage: {} <wasm file> <exported func> [<arg>...]", args[0]);
        return;
    }
    let func_name = &args[2];
    let (_, program_args) = args.split_at(3);

    // Intrepreter initialization.
    // parity_wasm::ProgramInstance can be parameterized with a custom User error which could be returned from imported functions
    // parity_wasm::DefaultProgramInstance parametrize ProgramInstance with a pre-defined "DummyUserError"
    // Initializes a default "env" module also.
    let program = parity_wasm::DefaultProgramInstance::with_env_params(
        interpreter::EnvParams {
            total_stack: 128*1024,
            total_memory: 2*1024*1024,
            allow_memory_growth: false,
        }
    ).expect("Program instance to load");

    let module = parity_wasm::deserialize_file(&args[1]).expect("File to be deserialized");

    // Extracts call arguments from command-line arguments
    let execution_params = {
        // Export section has an entry with a func_name with an index inside a module
        let export_section = module.export_section().expect("No export section found");
        // It's a section with function declarations (which are references to the type section entries)
        let function_section = module.function_section().expect("No function section found");
        // Type section stores function types which are referenced by function_section entries
        let type_section = module.type_section().expect("No type section found");

        // Given function name used to find export section entry which contains
        // an `internal` field which points to the index in the function index space
        let found_entry = export_section.entries().iter()
            .find(|entry| func_name == entry.field()).expect(&format!("No export with name {} found", func_name));

        // Function index in the function index space (internally-defined + imported)
        let function_index: usize = match found_entry.internal() {
            &Internal::Function(index) => index as usize,
            _ => panic!("Founded export is not a function"),
        };

        // We need to count import section entries (functions only!) to subtract it from function_index
        // and obtain the index within the function section
        let import_section_len: usize = match module.import_section() {
            Some(import) =>
                import.entries().iter().filter(|entry| match entry.external() {
                    &External::Function(_) => true,
                    _ => false,
                    }).count(),
            None => 0,
        };

        // Calculates a function index within module's function section
        let function_index_in_section = function_index - import_section_len;

        // Getting a type reference from a function section entry
        let func_type_ref: usize = function_section.entries()[function_index_in_section].type_ref() as usize;

        // Use the reference to get an actual function type
        let function_type: &FunctionType = match &type_section.types()[func_type_ref] {
            &Type::Function(ref func_type) => func_type,
        };

        // Parses arguments and constructs runtime values in correspondence of their types
        let args: Vec<RuntimeValue> = function_type.params().iter().enumerate().map(|(i, value)| match value {
            &ValueType::I32 => RuntimeValue::I32(program_args[i].parse::<i32>().expect(&format!("Can't parse arg #{} as i32", program_args[i]))),
            &ValueType::I64 => RuntimeValue::I64(program_args[i].parse::<i64>().expect(&format!("Can't parse arg #{} as i64", program_args[i]))),
            &ValueType::F32 => RuntimeValue::F32(program_args[i].parse::<f32>().expect(&format!("Can't parse arg #{} as f32", program_args[i]))),
            &ValueType::F64 => RuntimeValue::F64(program_args[i].parse::<f64>().expect(&format!("Can't parse arg #{} as f64", program_args[i]))),
        }).collect();

        interpreter::ExecutionParams::from(args)
    };

    // Intialize deserialized module. It adds module into It expects 3 parameters:
    // - a name for the module
    // - a module declaration
    // - an optional HashMap of additional external modules (which takes priority over already initialized modules)
    //   to be:
    //   - formally validated
    //   - validated imports against these external modules
    let module = program.add_module("main", module, None).expect("Failed to initialize module");

    println!("Result: {:?}", module.execute_export(func_name, execution_params).expect(""));
}
<commit_msg>comment external parameter<commit_after>extern crate parity_wasm;

use std::env::args;

use parity_wasm::{interpreter, ModuleInstanceInterface, RuntimeValue};
use parity_wasm::elements::{Internal, External, Type, FunctionType, ValueType};

fn main() {
    let args: Vec<_> = args().collect();
    if args.len() < 3 {
        println!("Usage: {} <wasm file> <exported func> [<arg>...]", args[0]);
        return;
    }
    let func_name = &args[2];
    let (_, program_args) = args.split_at(3);

    // Intrepreter initialization.
    // parity_wasm::ProgramInstance can be parameterized with a custom User error to be returned from native modules
    // parity_wasm::DefaultProgramInstance parametrize ProgramInstance with a pre-defined "DummyUserError"
    // Initializes a default "env" module also.
    let program = parity_wasm::DefaultProgramInstance::with_env_params(
        interpreter::EnvParams {
            total_stack: 128*1024,
            total_memory: 2*1024*1024,
            allow_memory_growth: false,
        }
    ).expect("Program instance to load");

    let module = parity_wasm::deserialize_file(&args[1]).expect("File to be deserialized");

    // Extracts call arguments from command-line arguments
    let execution_params = {
        // Export section has an entry with a func_name with an index inside a module
        let export_section = module.export_section().expect("No export section found");
        // It's a section with function declarations (which are references to the type section entries)
        let function_section = module.function_section().expect("No function section found");
        // Type section stores function types which are referenced by function_section entries
        let type_section = module.type_section().expect("No type section found");

        // Given function name used to find export section entry which contains
        // an `internal` field which points to the index in the function index space
        let found_entry = export_section.entries().iter()
            .find(|entry| func_name == entry.field()).expect(&format!("No export with name {} found", func_name));

        // Function index in the function index space (internally-defined + imported)
        let function_index: usize = match found_entry.internal() {
            &Internal::Function(index) => index as usize,
            _ => panic!("Founded export is not a function"),
        };

        // We need to count import section entries (functions only!) to subtract it from function_index
        // and obtain the index within the function section
        let import_section_len: usize = match module.import_section() {
            Some(import) =>
                import.entries().iter().filter(|entry| match entry.external() {
                    &External::Function(_) => true,
                    _ => false,
                    }).count(),
            None => 0,
        };

        // Calculates a function index within module's function section
        let function_index_in_section = function_index - import_section_len;

        // Getting a type reference from a function section entry
        let func_type_ref: usize = function_section.entries()[function_index_in_section].type_ref() as usize;

        // Use the reference to get an actual function type
        let function_type: &FunctionType = match &type_section.types()[func_type_ref] {
            &Type::Function(ref func_type) => func_type,
        };

        // Parses arguments and constructs runtime values in correspondence of their types
        let args: Vec<RuntimeValue> = function_type.params().iter().enumerate().map(|(i, value)| match value {
            &ValueType::I32 => RuntimeValue::I32(program_args[i].parse::<i32>().expect(&format!("Can't parse arg #{} as i32", program_args[i]))),
            &ValueType::I64 => RuntimeValue::I64(program_args[i].parse::<i64>().expect(&format!("Can't parse arg #{} as i64", program_args[i]))),
            &ValueType::F32 => RuntimeValue::F32(program_args[i].parse::<f32>().expect(&format!("Can't parse arg #{} as f32", program_args[i]))),
            &ValueType::F64 => RuntimeValue::F64(program_args[i].parse::<f64>().expect(&format!("Can't parse arg #{} as f64", program_args[i]))),
        }).collect();

        interpreter::ExecutionParams::from(args)
    };

    // Intialize deserialized module. It adds module into It expects 3 parameters:
    // - a name for the module
    // - a module declaration
    // - "main" module doesn't import native module(s) this is why we don't need to provide external native modules here
    // This test shows how to implement native module https://github.com/NikVolf/parity-wasm/blob/master/src/interpreter/tests/basics.rs#L197
    let module = program.add_module("main", module, None).expect("Failed to initialize module");

    println!("Result: {:?}", module.execute_export(func_name, execution_params).expect(""));
}
<|endoftext|>


<commit_before>extern crate suppositions;
#[macro_use]
extern crate log;
extern crate env_logger;

use suppositions::*;
use suppositions::generators::*;

#[test]
fn some_approximation_of_usage() {
    property(vecs(booleans())).check(|l| {
        let rev = l.iter().cloned().rev().collect::<Vec<_>>();
        let rev2 = rev.into_iter().rev().collect::<Vec<_>>();
        return rev2 == l;
    })
}

// In this case, we reverse the last three items.
#[test]
#[should_panic]
fn some_approximation_of_failing_example() {
    env_logger::init().unwrap_or(());
    property(vecs(booleans())).check(|l| {
        let rev = l.iter().cloned().rev().take(3).collect::<Vec<_>>();
        let rev2 = rev.into_iter().rev().collect::<Vec<_>>();
        info!("in:{:?}; out:{:?}; ok? {:?}", l, rev2, &rev2 == &l);
        return rev2 == l;
    })
}

// http://matt.might.net/articles/quick-quickcheck/
#[test]
#[should_panic]
fn mersenne_conjecture() {
    env_logger::init().unwrap_or(());
    fn is_prime(n: u64) -> bool {
        match n {
            0 | 1 => false,
            2 => true,
            n => !(2..n - 1).any(|q| (n % q) == 0),
        }
    }

    // Only check small primes.
    property(u8s().filter(|&n: &u8| n < 16).filter(|&n: &u8| {
        debug!("mersenne_conjecture n: {}", n);
        let primep = is_prime(n as u64);
        debug!("mersenne_conjecture n: {}; prime? {}", n, primep);
        n < 64 && primep
    })).check(|n| is_prime((1u64 << n) - 1))
}

#[test]
#[should_panic]
fn trivial_failure() {
    property((booleans())).check(|_| false)
}

#[test]
fn trivial_pass() {
    property((booleans())).check(|_| true)
}

#[test]
#[should_panic]
fn value_dependent() {
    property(vecs(booleans())).check(|v| {
        println!("Check: {:?}", v);
        !v.into_iter().any(|t| t)
    })
}
<commit_msg>Verify things fail for the right reasons.<commit_after>extern crate suppositions;
#[macro_use]
extern crate log;
extern crate env_logger;

use suppositions::*;
use suppositions::generators::*;

#[test]
fn some_approximation_of_usage() {
    property(vecs(booleans())).check(|l| {
        let rev = l.iter().cloned().rev().collect::<Vec<_>>();
        let rev2 = rev.into_iter().rev().collect::<Vec<_>>();
        return rev2 == l;
    })
}

// In this case, we reverse the last three items.
#[test]
#[should_panic(expected = "Predicate failed for argument ")]
fn some_approximation_of_failing_example() {
    env_logger::init().unwrap_or(());
    property(vecs(booleans())).check(|l| {
        let rev = l.iter().cloned().rev().take(3).collect::<Vec<_>>();
        let rev2 = rev.into_iter().rev().collect::<Vec<_>>();
        info!("in:{:?}; out:{:?}; ok? {:?}", l, rev2, &rev2 == &l);
        return rev2 == l;
    })
}

// http://matt.might.net/articles/quick-quickcheck/
#[test]
#[should_panic(expected = "Predicate failed for argument ")]
fn mersenne_conjecture() {
    env_logger::init().unwrap_or(());
    fn is_prime(n: u64) -> bool {
        match n {
            0 | 1 => false,
            2 => true,
            n => !(2..n - 1).any(|q| (n % q) == 0),
        }
    }

    // Only check small primes.
    property(u8s().filter(|&n: &u8| n < 16).filter(|&n: &u8| {
        debug!("mersenne_conjecture n: {}", n);
        let primep = is_prime(n as u64);
        debug!("mersenne_conjecture n: {}; prime? {}", n, primep);
        n < 64 && primep
    })).check(|n| is_prime((1u64 << n) - 1))
}

#[test]
#[should_panic(expected = "Predicate failed for argument ")]
fn trivial_failure() {
    property((booleans())).check(|_| false)
}

#[test]
fn trivial_pass() {
    property((booleans())).check(|_| true)
}

#[test]
#[should_panic(expected = "Predicate failed for argument ")]
fn value_dependent() {
    property(vecs(booleans())).check(|v| {
        println!("Check: {:?}", v);
        !v.into_iter().any(|t| t)
    })
}
<|endoftext|>


<commit_before>//! A language server scaffold, exposing a synchronous crossbeam-channel based API.
//! This crate handles protocol handshaking and parsing messages, while you
//! control the message dispatch loop yourself.
//!
//! Run with `RUST_LOG=sync_lsp_server=debug` to see all the messages.
//!
//! ```no_run
//! extern crate gen_lsp_server;
//! extern crate lsp_types;
//! extern crate failure;
//! extern crate crossbeam_channel;
//!
//! use crossbeam_channel::{Sender, Receiver};
//! use lsp_types::{ServerCapabilities, InitializeParams, request::{GotoDefinition, GotoDefinitionResponse}};
//! use gen_lsp_server::{run_server, stdio_transport, handle_shutdown, RawMessage, RawResponse};
//!
//! fn main() -> Result<(), failure::Error> {
//!     let (receiver, sender, io_threads) = stdio_transport();
//!     gen_lsp_server::run_server(
//!         ServerCapabilities::default(),
//!         receiver,
//!         sender,
//!         main_loop,
//!     )?;
//!     io_threads.join()?;
//!     Ok(())
//! }
//!
//! fn main_loop(
//!     _params: InitializeParams,
//!     receiver: &Receiver<RawMessage>,
//!     sender: &Sender<RawMessage>,
//! ) -> Result<(), failure::Error> {
//!     for msg in receiver {
//!         match msg {
//!             RawMessage::Request(req) => {
//!                 let req = match handle_shutdown(req, sender) {
//!                     None => return Ok(()),
//!                     Some(req) => req,
//!                 };
//!                 let req = match req.cast::<GotoDefinition>() {
//!                     Ok((id, _params)) => {
//!                         let resp = RawResponse::ok::<GotoDefinition>(
//!                             id,
//!                             &Some(GotoDefinitionResponse::Array(Vec::new())),
//!                         );
//!                         sender.send(RawMessage::Response(resp));
//!                         continue;
//!                     },
//!                     Err(req) => req,
//!                 };
//!                 // ...
//!             }
//!             RawMessage::Response(_resp) => (),
//!             RawMessage::Notification(_not) => (),
//!         }
//!     }
//!     Ok(())
//! }
//! ```

use failure::{bail, format_err};

mod msg;
mod stdio;

use crossbeam_channel::{Receiver, Sender};
use lsp_types::{
    notification::{Exit, Initialized},
    request::{Initialize, Shutdown},
    InitializeParams, InitializeResult, ServerCapabilities,
};

pub type Result<T> = ::std::result::Result<T, failure::Error>;
pub use crate::{
    msg::{ErrorCode, RawMessage, RawNotification, RawRequest, RawResponse, RawResponseError},
    stdio::{stdio_transport, Threads},
};

/// Main entry point: runs the server from initialization to shutdown.
/// To attach server to standard input/output streams, use the `stdio_transport`
/// function to create corresponding `sender` and `receiver` pair.
///
/// `server` should use the `handle_shutdown` function to handle the `Shutdown`
/// request.
pub fn run_server(
    caps: ServerCapabilities,
    receiver: Receiver<RawMessage>,
    sender: Sender<RawMessage>,
    server: impl FnOnce(InitializeParams, &Receiver<RawMessage>, &Sender<RawMessage>) -> Result<()>,
) -> Result<()> {
    log::info!("lsp server initializes");
    let params = initialize(&receiver, &sender, caps)?;
    log::info!("lsp server initialized, serving requests");
    server(params, &receiver, &sender)?;
    log::info!("lsp server waiting for exit notification");
    match receiver.recv() {
        Ok(RawMessage::Notification(n)) => n
            .cast::<Exit>()
            .map_err(|n| format_err!("unexpected notification during shutdown: {:?}", n))?,
        m => bail!("unexpected message during shutdown: {:?}", m),
    }
    log::info!("lsp server shutdown complete");
    Ok(())
}

/// If `req` is `Shutdown`, respond to it and return `None`, otherwise return `Some(req)`
pub fn handle_shutdown(req: RawRequest, sender: &Sender<RawMessage>) -> Option<RawRequest> {
    match req.cast::<Shutdown>() {
        Ok((id, ())) => {
            let resp = RawResponse::ok::<Shutdown>(id, &());
            let _ = sender.send(RawMessage::Response(resp));
            None
        }
        Err(req) => Some(req),
    }
}

fn initialize(
    receiver: &Receiver<RawMessage>,
    sender: &Sender<RawMessage>,
    caps: ServerCapabilities,
) -> Result<InitializeParams> {
    let (id, params) = match receiver.recv() {
        Ok(RawMessage::Request(req)) => match req.cast::<Initialize>() {
            Err(req) => bail!("expected initialize request, got {:?}", req),
            Ok(req) => req,
        },
        msg => bail!("expected initialize request, got {:?}", msg),
    };
    let resp = RawResponse::ok::<Initialize>(id, &InitializeResult { capabilities: caps });
    sender.send(RawMessage::Response(resp)).unwrap();
    match receiver.recv() {
        Ok(RawMessage::Notification(n)) => {
            n.cast::<Initialized>()
                .map_err(|_| format_err!("expected initialized notification"))?;
        }
        _ => bail!("expected initialized notification"),
    }
    Ok(params)
}
<commit_msg>Fixes doctest<commit_after>//! A language server scaffold, exposing a synchronous crossbeam-channel based API.
//! This crate handles protocol handshaking and parsing messages, while you
//! control the message dispatch loop yourself.
//!
//! Run with `RUST_LOG=sync_lsp_server=debug` to see all the messages.
//!
//! ```no_run
//! extern crate gen_lsp_server;
//! extern crate lsp_types;
//! extern crate failure;
//! extern crate crossbeam_channel;
//!
//! use crossbeam_channel::{Sender, Receiver};
//! use lsp_types::{ServerCapabilities, InitializeParams, request::{GotoDefinition, GotoDefinitionResponse}};
//! use gen_lsp_server::{run_server, stdio_transport, handle_shutdown, RawMessage, RawResponse};
//!
//! fn main() -> Result<(), failure::Error> {
//!     let (receiver, sender, io_threads) = stdio_transport();
//!     gen_lsp_server::run_server(
//!         ServerCapabilities::default(),
//!         receiver,
//!         sender,
//!         main_loop,
//!     )?;
//!     io_threads.exit()?;
//!     Ok(())
//! }
//!
//! fn main_loop(
//!     _params: InitializeParams,
//!     receiver: &Receiver<RawMessage>,
//!     sender: &Sender<RawMessage>,
//! ) -> Result<(), failure::Error> {
//!     for msg in receiver {
//!         match msg {
//!             RawMessage::Request(req) => {
//!                 let req = match handle_shutdown(req, sender) {
//!                     None => return Ok(()),
//!                     Some(req) => req,
//!                 };
//!                 let req = match req.cast::<GotoDefinition>() {
//!                     Ok((id, _params)) => {
//!                         let resp = RawResponse::ok::<GotoDefinition>(
//!                             id,
//!                             &Some(GotoDefinitionResponse::Array(Vec::new())),
//!                         );
//!                         sender.send(RawMessage::Response(resp));
//!                         continue;
//!                     },
//!                     Err(req) => req,
//!                 };
//!                 // ...
//!             }
//!             RawMessage::Response(_resp) => (),
//!             RawMessage::Notification(_not) => (),
//!         }
//!     }
//!     Ok(())
//! }
//! ```

use failure::{bail, format_err};

mod msg;
mod stdio;

use crossbeam_channel::{Receiver, Sender};
use lsp_types::{
    notification::{Exit, Initialized},
    request::{Initialize, Shutdown},
    InitializeParams, InitializeResult, ServerCapabilities,
};

pub type Result<T> = ::std::result::Result<T, failure::Error>;
pub use crate::{
    msg::{ErrorCode, RawMessage, RawNotification, RawRequest, RawResponse, RawResponseError},
    stdio::{stdio_transport, Threads},
};

/// Main entry point: runs the server from initialization to shutdown.
/// To attach server to standard input/output streams, use the `stdio_transport`
/// function to create corresponding `sender` and `receiver` pair.
///
/// `server` should use the `handle_shutdown` function to handle the `Shutdown`
/// request.
pub fn run_server(
    caps: ServerCapabilities,
    receiver: Receiver<RawMessage>,
    sender: Sender<RawMessage>,
    server: impl FnOnce(InitializeParams, &Receiver<RawMessage>, &Sender<RawMessage>) -> Result<()>,
) -> Result<()> {
    log::info!("lsp server initializes");
    let params = initialize(&receiver, &sender, caps)?;
    log::info!("lsp server initialized, serving requests");
    server(params, &receiver, &sender)?;
    log::info!("lsp server waiting for exit notification");
    match receiver.recv() {
        Ok(RawMessage::Notification(n)) => n
            .cast::<Exit>()
            .map_err(|n| format_err!("unexpected notification during shutdown: {:?}", n))?,
        m => bail!("unexpected message during shutdown: {:?}", m),
    }
    log::info!("lsp server shutdown complete");
    Ok(())
}

/// If `req` is `Shutdown`, respond to it and return `None`, otherwise return `Some(req)`
pub fn handle_shutdown(req: RawRequest, sender: &Sender<RawMessage>) -> Option<RawRequest> {
    match req.cast::<Shutdown>() {
        Ok((id, ())) => {
            let resp = RawResponse::ok::<Shutdown>(id, &());
            let _ = sender.send(RawMessage::Response(resp));
            None
        }
        Err(req) => Some(req),
    }
}

fn initialize(
    receiver: &Receiver<RawMessage>,
    sender: &Sender<RawMessage>,
    caps: ServerCapabilities,
) -> Result<InitializeParams> {
    let (id, params) = match receiver.recv() {
        Ok(RawMessage::Request(req)) => match req.cast::<Initialize>() {
            Err(req) => bail!("expected initialize request, got {:?}", req),
            Ok(req) => req,
        },
        msg => bail!("expected initialize request, got {:?}", msg),
    };
    let resp = RawResponse::ok::<Initialize>(id, &InitializeResult { capabilities: caps });
    sender.send(RawMessage::Response(resp)).unwrap();
    match receiver.recv() {
        Ok(RawMessage::Notification(n)) => {
            n.cast::<Initialized>()
                .map_err(|_| format_err!("expected initialized notification"))?;
        }
        _ => bail!("expected initialized notification"),
    }
    Ok(params)
}
<|endoftext|>


<commit_before>use serde::Deserialize;
use flexi_logger::{Duplicate, Logger};
use gen_lsp_server::{run_server, stdio_transport};

use ra_lsp_server::{Result, InitializationOptions};
use ra_prof;

fn main() -> Result<()> {
    ::std::env::set_var("RUST_BACKTRACE", "short");
    let logger = Logger::with_env_or_str("error").duplicate_to_stderr(Duplicate::All);
    match ::std::env::var("RA_INTERNAL_MODE") {
        Ok(ref v) if v == "1" => logger.log_to_file().directory("log").start()?,
        _ => logger.start()?,
    };
    let prof_depth = match ::std::env::var("RA_PROFILE_DEPTH") {
        Ok(ref d) => d.parse()?,
        _ => 0,
    };
    let profile_allowed = match ::std::env::var("RA_PROFILE") {
        Ok(ref p) => p.split(";").map(String::from).collect(),
        _ => Vec::new(),
    };
    ra_prof::set_filter(ra_prof::Filter::new(prof_depth, profile_allowed));
    log::info!("lifecycle: server started");
    match ::std::panic::catch_unwind(main_inner) {
        Ok(res) => {
            log::info!("lifecycle: terminating process with {:?}", res);
            res
        }
        Err(_) => {
            log::error!("server panicked");
            failure::bail!("server panicked")
        }
    }
}

fn main_inner() -> Result<()> {
    let (receiver, sender, threads) = stdio_transport();
    let cwd = ::std::env::current_dir()?;
    run_server(ra_lsp_server::server_capabilities(), receiver, sender, |params, r, s| {
        let root = params.root_uri.and_then(|it| it.to_file_path().ok()).unwrap_or(cwd);

        let workspace_roots = params
            .workspace_folders
            .map(|workspaces| {
                workspaces
                    .into_iter()
                    .filter_map(|it| it.uri.to_file_path().ok())
                    .collect::<Vec<_>>()
            })
            .filter(|workspaces| !workspaces.is_empty())
            .unwrap_or_else(|| vec![root]);

        let opts = params
            .initialization_options
            .and_then(|v| InitializationOptions::deserialize(v).ok())
            .unwrap_or(InitializationOptions::default());

        ra_lsp_server::main_loop(workspace_roots, opts, r, s)
    })?;
    log::info!("shutting down IO...");
    threads.join()?;
    log::info!("... IO is down");
    Ok(())
}
<commit_msg>switch to modern paths<commit_after>use serde::Deserialize;
use flexi_logger::{Duplicate, Logger};
use gen_lsp_server::{run_server, stdio_transport};

use ra_lsp_server::{Result, InitializationOptions};
use ra_prof;

fn main() -> Result<()> {
    std::env::set_var("RUST_BACKTRACE", "short");
    let logger = Logger::with_env_or_str("error").duplicate_to_stderr(Duplicate::All);
    match std::env::var("RA_INTERNAL_MODE") {
        Ok(ref v) if v == "1" => logger.log_to_file().directory("log").start()?,
        _ => logger.start()?,
    };
    let prof_depth = match std::env::var("RA_PROFILE_DEPTH") {
        Ok(ref d) => d.parse()?,
        _ => 0,
    };
    let profile_allowed = match std::env::var("RA_PROFILE") {
        Ok(ref p) => p.split(";").map(String::from).collect(),
        _ => Vec::new(),
    };
    ra_prof::set_filter(ra_prof::Filter::new(prof_depth, profile_allowed));
    log::info!("lifecycle: server started");
    match ::std::panic::catch_unwind(main_inner) {
        Ok(res) => {
            log::info!("lifecycle: terminating process with {:?}", res);
            res
        }
        Err(_) => {
            log::error!("server panicked");
            failure::bail!("server panicked")
        }
    }
}

fn main_inner() -> Result<()> {
    let (receiver, sender, threads) = stdio_transport();
    let cwd = std::env::current_dir()?;
    run_server(ra_lsp_server::server_capabilities(), receiver, sender, |params, r, s| {
        let root = params.root_uri.and_then(|it| it.to_file_path().ok()).unwrap_or(cwd);

        let workspace_roots = params
            .workspace_folders
            .map(|workspaces| {
                workspaces
                    .into_iter()
                    .filter_map(|it| it.uri.to_file_path().ok())
                    .collect::<Vec<_>>()
            })
            .filter(|workspaces| !workspaces.is_empty())
            .unwrap_or_else(|| vec![root]);

        let opts = params
            .initialization_options
            .and_then(|v| InitializationOptions::deserialize(v).ok())
            .unwrap_or(InitializationOptions::default());

        ra_lsp_server::main_loop(workspace_roots, opts, r, s)
    })?;
    log::info!("shutting down IO...");
    threads.join()?;
    log::info!("... IO is down");
    Ok(())
}
<|endoftext|>


<commit_before>#![feature(path, io, collections)]
extern crate env_logger;
extern crate handlebars;
extern crate "rustc-serialize" as serialize;

use std::old_io::File;
use std::collections::BTreeMap;

use handlebars::{Handlebars, RenderError, RenderContext, Helper, Context};
use serialize::json::{Json, ToJson};

fn format_helper (c: &Context, h: &Helper, _: &Handlebars, rc: &mut RenderContext) -> Result<String, RenderError> {
    let param = h.params().get(0).unwrap();
    Ok(format!("{} pts", c.navigate(rc.get_path(), param)))
}

fn load_template(name: &str) -> String {
    let path = Path::new(name);
    let display = path.display();

    let mut file = match File::open(&path) {
        Err(why) => panic!("couldn't open {}: {}", display, why.desc),
        Ok(file) => file,
    };

    match file.read_to_string() {
        Err(why) => panic!("couldn't read {}: {}", display, why.desc),
        Ok(string) => string
    }
}

fn make_data () -> BTreeMap<String, Json> {
    let mut data = BTreeMap::new();

    data.insert("year".to_string(), "2015".to_json());

    let mut teams = Vec::new();

    for v in vec![("Jiangsu", 43u16), ("Beijing", 27u16), ("Guangzhou", 22u16), ("Shandong", 12u16)].iter() {
        let (name, score) = *v;
        let mut t = BTreeMap::new();
        t.insert("name".to_string(), name.to_json());
        t.insert("score".to_string(), score.to_json());
        teams.push(t)
    }

    data.insert("teams".to_string(), teams.to_json());
    data
}

fn main() {
    env_logger::init().unwrap();
    let mut handlebars = Handlebars::new();

    let t = load_template("./examples/template.hbs");
    handlebars.register_template_string("table", t)
        .ok().expect("template creation failed");

    handlebars.register_helper("format", Box::new(format_helper));
//    handlebars.register_helper("format", Box::new(FORMAT_HELPER));

    let data = make_data();
    println!("{}", handlebars.render("table", &data).ok().unwrap());
}
<commit_msg>(fix) rustup: feature gate update<commit_after>#![feature(path, io, core)]
extern crate env_logger;
extern crate handlebars;
extern crate "rustc-serialize" as serialize;

use std::old_io::File;
use std::collections::BTreeMap;

use handlebars::{Handlebars, RenderError, RenderContext, Helper, Context};
use serialize::json::{Json, ToJson};

fn format_helper (c: &Context, h: &Helper, _: &Handlebars, rc: &mut RenderContext) -> Result<String, RenderError> {
    let param = h.params().get(0).unwrap();
    Ok(format!("{} pts", c.navigate(rc.get_path(), param)))
}

fn load_template(name: &str) -> String {
    let path = Path::new(name);
    let display = path.display();

    let mut file = match File::open(&path) {
        Err(why) => panic!("couldn't open {}: {}", display, why.desc),
        Ok(file) => file,
    };

    match file.read_to_string() {
        Err(why) => panic!("couldn't read {}: {}", display, why.desc),
        Ok(string) => string
    }
}

fn make_data () -> BTreeMap<String, Json> {
    let mut data = BTreeMap::new();

    data.insert("year".to_string(), "2015".to_json());

    let mut teams = Vec::new();

    for v in vec![("Jiangsu", 43u16), ("Beijing", 27u16), ("Guangzhou", 22u16), ("Shandong", 12u16)].iter() {
        let (name, score) = *v;
        let mut t = BTreeMap::new();
        t.insert("name".to_string(), name.to_json());
        t.insert("score".to_string(), score.to_json());
        teams.push(t)
    }

    data.insert("teams".to_string(), teams.to_json());
    data
}

fn main() {
    env_logger::init().unwrap();
    let mut handlebars = Handlebars::new();

    let t = load_template("./examples/template.hbs");
    handlebars.register_template_string("table", t)
        .ok().expect("template creation failed");

    handlebars.register_helper("format", Box::new(format_helper));
//    handlebars.register_helper("format", Box::new(FORMAT_HELPER));

    let data = make_data();
    println!("{}", handlebars.render("table", &data).ok().unwrap());
}
<|endoftext|>


<commit_before>// Copyright 2021 Google LLC
//
// 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
//
//    https://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 autocxx::subclass::prelude::*;
use autocxx::{c_int, PinMut};
use std::cell::{Ref, RefCell, RefMut};
use std::ops::Deref;
use std::pin::Pin;
use std::rc::Rc;

use crate::ffi;

/// A memory-safe handle to a C++ RenderFrameHost.
///
/// This is a toy, hypothetical, example.
///
/// Creation: in this sample, the only option is to use [`RenderFrameHostHandle::from_id`]
/// which corresponds to the equivalent method in C++ `RenderFrameHost`. Unlike
/// the C++ version, you must pass a WebContents so that Rust wrappers can listen for
/// destruction events.
///
/// The returned handle is memory safe and can be used to access the methods
/// of [`ffi::content::RenderFrameHost`]. To use such a method, you have three options:
/// * If you believe there is no chance that the `RenderFrameHost` has been
///   destroyed, and if the method is const, you can just go ahead and call methods
///   on this object. As it implements [`std::ops::Deref`], that will just work -
///   but your code will panic if the `RenderFrameHost` was already destroyed.
/// * If the method is non-const, you'll have to call `.pin_mut().method()` instead
//    but otherwise this is functionally identical.
/// * If you believe that there is a chance that the `RenderFrameHost` was already
///   destroyed, use [`RenderFrameHostHandle::try_borrow`] or
///   [`RenderFrameHostHandle::try_borrow_mut`]. This will return
///   a guard object which guarantees the existence of the `RenderFrameHost`
///   during its lifetime.
///
/// # Performance characteristics
///
/// The existence of this object registers an observer with the `WebContents`
/// and deregisters it on destruction. That is, of course, an overhead, but
/// that's necessary to keep track of liveness. (A more efficient
/// implementation would use a single observer for multiple such handles - but
/// this is a toy implementation).
///
/// In addition, each time you extract the value from this
/// `RenderFrameHostHandle`, a liveness check is performed. This involves
///
/// If you're going to access the `RenderFrameHost` multiple times, it's
/// advised that you call [`RenderFrameHostHandle::try_borrow`] or
/// [`RenderFrameHostHandle::try_borrow_mut`] and then use
/// the result multiple times. The liveness check for the `RenderFrameHost`
/// will be performed only once at runtime.
///
/// # Destruction of RenderFrameHosts while borrowed
///
/// If you have called [`RenderFrameHostHandle::try_borrow`] (or its mutable
/// equivalent) and still have an outstanding borrow, any code path - via C++
/// - which results it the destruction of the `RenderFrameHost` will result in
/// a runtime panic.
pub struct RenderFrameHostHandle<'wc> {
    obs: Rc<RefCell<RenderFrameHostForWebContents>>,
    web_contents: Pin<&'wc mut ffi::content::WebContents>,
}

impl<'wc> RenderFrameHostHandle<'wc> {
    /// Create a memory-safe handle to a RenderFrameHost using its
    /// process ID and frame ID.
    pub fn from_id(
        render_process_id: c_int,
        render_frame_id: c_int,
        mut web_contents: Pin<&'wc mut ffi::content::WebContents>,
    ) -> Self {
        // Instantiate our WebContentsObserver subclass.
        let obs = RenderFrameHostForWebContents::new_rust_owned(RenderFrameHostForWebContents {
            rfh: ffi::content::RenderFrameHost::FromId(render_process_id, render_frame_id),
            cpp_peer: Default::default(),
        });

        // And now register it.
        // This nasty line will go away when autocxx is a bit more sophisticated.
        let superclass_ptr = cast_to_superclass(obs.as_ref().borrow_mut().peer_mut());

        // But this will remain unsafe. cxx policy is that any raw pointer
        // passed into a C++ function requires an unsafe {} block and that
        // is sensible. We may of course provide an ergonomic Rust wrapper
        // around WebContents which provides safe Rust equivalents
        // (using references or similar rather than pointers) in which case
        // this unsafe block would go away.
        unsafe { web_contents.as_mut().AddObserver(superclass_ptr) };

        Self { obs, web_contents }
    }

    /// Tries to return a mutable reference to the RenderFrameHost.
    /// Because this requires `self` to be `&mut`, and that lifetime is
    /// applied to the returned `RenderFrameHost`, the compiler will prevent
    /// multiple such references existing in Rust at the same time.
    /// This will return `None` if the RenderFrameHost were already destroyed.
    pub fn try_borrow_mut<'a>(
        &'a mut self,
    ) -> Option<impl PinMut<ffi::content::RenderFrameHost> + 'a> {
        let ref_mut = self.obs.as_ref().borrow_mut();
        if ref_mut.rfh.is_null() {
            None
        } else {
            Some(RenderFrameHostRefMut(ref_mut))
        }
    }

    /// Tries to return a reference to the RenderFrameHost.
    /// The compiler will prevent calls to this if anyone has an outstanding
    /// mutable reference from [`RenderFrameHostHandle::try_borrow_mut`].
    /// This will return `None` if the RenderFrameHost were already destroyed.
    #[allow(dead_code)]
    pub fn try_borrow<'a>(&'a self) -> Option<impl AsRef<ffi::content::RenderFrameHost> + 'a> {
        let ref_non_mut = self.obs.as_ref().borrow();
        if ref_non_mut.rfh.is_null() {
            None
        } else {
            Some(RenderFrameHostRef(ref_non_mut))
        }
    }
}

impl<'wc> Drop for RenderFrameHostHandle<'wc> {
    fn drop(&mut self) {
        // Unregister our observer.
        let superclass_ptr = cast_to_superclass(self.obs.as_ref().borrow_mut().peer_mut());
        unsafe { self.web_contents.as_mut().RemoveObserver(superclass_ptr) };
    }
}

impl<'wc> AsRef<ffi::content::RenderFrameHost> for RenderFrameHostHandle<'wc> {
    fn as_ref(&self) -> &ffi::content::RenderFrameHost {
        let ref_non_mut = self.obs.as_ref().borrow();
        // Safety: the .rfh field is guaranteed to be a RenderFrameHost
        // and we are observing its lifetime so it will be reset to null
        // if destroyed.
        unsafe { ref_non_mut.rfh.as_ref() }.expect("This RenderFrameHost was already destroyed")
    }
}

impl<'wc> PinMut<ffi::content::RenderFrameHost> for RenderFrameHostHandle<'wc> {
    fn pin_mut(&mut self) -> Pin<&mut ffi::content::RenderFrameHost> {
        let ref_mut = self.obs.as_ref().borrow_mut();
        // Safety: the .rfh field is guaranteed to be a RenderFrameHost
        // and we are observing its lifetime so it will be reset to null
        // if destroyed.
        unsafe { ref_mut.rfh.as_mut().map(|p| Pin::new_unchecked(p)) }
            .expect("This RenderFrameHost was already destroyed")
    }
}

impl<'wc> Deref for RenderFrameHostHandle<'wc> {
    type Target = ffi::content::RenderFrameHost;
    fn deref(&self) -> &Self::Target {
        self.as_ref()
    }
}

#[doc(hidden)]
struct RenderFrameHostRefMut<'a>(RefMut<'a, RenderFrameHostForWebContents>);

#[doc(hidden)]
struct RenderFrameHostRef<'a>(Ref<'a, RenderFrameHostForWebContents>);

impl<'a> AsRef<ffi::content::RenderFrameHost> for RenderFrameHostRef<'a> {
    fn as_ref(&self) -> &ffi::content::RenderFrameHost {
        // Safety:
        // Creation precondition is that self.0.rfh is not null
        // and it can't be destroyed whilst this borrow exists.
        unsafe { self.0.rfh.as_ref().unwrap() }
    }
}

impl<'a> PinMut<ffi::content::RenderFrameHost> for RenderFrameHostRefMut<'a> {
    fn pin_mut(&mut self) -> Pin<&mut ffi::content::RenderFrameHost> {
        // Safety:
        // Creation precondition is that self.0.rfh is not null
        // and it can't be destroyed whilst this borrow exists.
        unsafe { Pin::new_unchecked(self.0.rfh.as_mut().unwrap()) }
    }
}

impl<'a> AsRef<ffi::content::RenderFrameHost> for RenderFrameHostRefMut<'a> {
    fn as_ref(&self) -> &ffi::content::RenderFrameHost {
        // Safety:
        // Creation precondition is that self.0.rfh is not null
        // and it can't be destroyed whilst this borrow exists.
        unsafe { self.0.rfh.as_ref().unwrap() }
    }
}

impl<'a> Deref for RenderFrameHostRef<'a> {
    type Target = ffi::content::RenderFrameHost;
    fn deref(&self) -> &Self::Target {
        self.as_ref()
    }
}

impl<'a> Deref for RenderFrameHostRefMut<'a> {
    type Target = ffi::content::RenderFrameHost;
    fn deref(&self) -> &Self::Target {
        self.as_ref()
    }
}

#[is_subclass(superclass("content::WebContentsObserver"))]
#[doc(hidden)]
pub struct RenderFrameHostForWebContents {
    rfh: *mut ffi::content::RenderFrameHost,
}

impl ffi::content::WebContentsObserver_methods for RenderFrameHostForWebContents {
    unsafe fn RenderFrameDeleted(&mut self, destroyed_rfh: *mut ffi::content::RenderFrameHost) {
        if self.rfh == destroyed_rfh {
            self.rfh = std::ptr::null_mut()
        }
    }
}

fn cast_to_superclass(
    obs: Pin<&mut ffi::RenderFrameHostForWebContentsCpp>,
) -> *mut ffi::content::WebContentsObserver {
    // This horrid code will all go away once we implement
    // https://github.com/google/autocxx/issues/592; safe wrappers will
    // be automatically generated to allow upcasting to superclasses.
    let subclass_obs_ptr =
        unsafe { Pin::into_inner_unchecked(obs) } as *mut ffi::RenderFrameHostForWebContentsCpp;
    unsafe {
        std::mem::transmute::<
            *mut ffi::RenderFrameHostForWebContentsCpp,
            *mut ffi::content::WebContentsObserver,
        >(subclass_obs_ptr)
    }
}
<commit_msg>Update render_frame_host.rs<commit_after>// Copyright 2021 Google LLC
//
// 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
//
//    https://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 autocxx::subclass::prelude::*;
use autocxx::{c_int, PinMut};
use std::cell::{Ref, RefCell, RefMut};
use std::ops::Deref;
use std::pin::Pin;
use std::rc::Rc;

use crate::ffi;

/// A memory-safe handle to a C++ RenderFrameHost.
///
/// This is a toy, hypothetical, example.
///
/// Creation: in this sample, the only option is to use [`RenderFrameHostHandle::from_id`]
/// which corresponds to the equivalent method in C++ `RenderFrameHost`. Unlike
/// the C++ version, you must pass a WebContents so that Rust wrappers can listen for
/// destruction events.
///
/// The returned handle is memory safe and can be used to access the methods
/// of [`ffi::content::RenderFrameHost`]. To use such a method, you have three options:
/// * If you believe there is no chance that the `RenderFrameHost` has been
///   destroyed, and if the method is const, you can just go ahead and call methods
///   on this object. As it implements [`std::ops::Deref`], that will just work -
///   but your code will panic if the `RenderFrameHost` was already destroyed.
/// * If the method is non-const, you'll have to call `.pin_mut().method()` instead
//    but otherwise this is functionally identical.
/// * If you believe that there is a chance that the `RenderFrameHost` was already
///   destroyed, use [`RenderFrameHostHandle::try_borrow`] or
///   [`RenderFrameHostHandle::try_borrow_mut`]. This will return
///   a guard object which guarantees the existence of the `RenderFrameHost`
///   during its lifetime.
///
/// # Performance characteristics
///
/// The existence of this object registers an observer with the `WebContents`
/// and deregisters it on destruction. That is, of course, an overhead, but
/// that's necessary to keep track of liveness. (A more efficient
/// implementation would use a single observer for multiple such handles - but
/// this is a toy implementation).
///
/// In addition, each time you extract the value from this
/// `RenderFrameHostHandle`, a liveness check is performed. This involves
///
/// If you're going to access the `RenderFrameHost` multiple times, it's
/// advised that you call [`RenderFrameHostHandle::try_borrow`] or
/// [`RenderFrameHostHandle::try_borrow_mut`] and then use
/// the result multiple times. The liveness check for the `RenderFrameHost`
/// will be performed only once at runtime.
///
/// # Destruction of RenderFrameHosts while borrowed
///
/// If you have called [`RenderFrameHostHandle::try_borrow`] (or its mutable
/// equivalent) and still have an outstanding borrow, any code path - via C++
/// - which results it the destruction of the `RenderFrameHost` will result in
/// a runtime panic.
pub struct RenderFrameHostHandle<'wc> {
    obs: Rc<RefCell<RenderFrameHostForWebContents>>,
    web_contents: Pin<&'wc mut ffi::content::WebContents>,
}

impl<'wc> RenderFrameHostHandle<'wc> {
    /// Create a memory-safe handle to a RenderFrameHost using its
    /// process ID and frame ID.
    pub fn from_id(
        render_process_id: c_int,
        render_frame_id: c_int,
        mut web_contents: Pin<&'wc mut ffi::content::WebContents>,
    ) -> Self {
        // Instantiate our WebContentsObserver subclass.
        let obs = RenderFrameHostForWebContents::new_rust_owned(RenderFrameHostForWebContents {
            rfh: ffi::content::RenderFrameHost::FromId(render_process_id, render_frame_id),
            cpp_peer: Default::default(),
        });

        // And now register it.
        // This nasty line will go away when autocxx is a bit more sophisticated.
        let superclass_ptr = cast_to_superclass(obs.as_ref().borrow_mut().peer_mut());

        // But this will remain unsafe. cxx policy is that any raw pointer
        // passed into a C++ function requires an unsafe {} block and that
        // is sensible. We may of course provide an ergonomic Rust wrapper
        // around WebContents which provides safe Rust equivalents
        // (using references or similar rather than pointers) in which case
        // this unsafe block would go away.
        unsafe { web_contents.as_mut().AddObserver(superclass_ptr) };

        Self { obs, web_contents }
    }

    /// Tries to return a mutable reference to the RenderFrameHost.
    /// Because this requires `self` to be `&mut`, and that lifetime is
    /// applied to the returned `RenderFrameHost`, the compiler will prevent
    /// multiple such references existing in Rust at the same time.
    /// This will return `None` if the RenderFrameHost were already destroyed.
    pub fn try_borrow_mut<'a>(
        &'a mut self,
    ) -> Option<impl PinMut<ffi::content::RenderFrameHost> + 'a> {
        let ref_mut = self.obs.as_ref().borrow_mut();
        if ref_mut.rfh.is_null() {
            None
        } else {
            Some(RenderFrameHostRefMut(ref_mut))
        }
    }

    /// Tries to return a reference to the RenderFrameHost.
    /// The compiler will prevent calls to this if anyone has an outstanding
    /// mutable reference from [`RenderFrameHostHandle::try_borrow_mut`].
    /// This will return `None` if the RenderFrameHost were already destroyed.
    #[allow(dead_code)]
    pub fn try_borrow<'a>(&'a self) -> Option<impl AsRef<ffi::content::RenderFrameHost> + 'a> {
        let ref_non_mut = self.obs.as_ref().borrow();
        if ref_non_mut.rfh.is_null() {
            None
        } else {
            Some(RenderFrameHostRef(ref_non_mut))
        }
    }
}

impl<'wc> Drop for RenderFrameHostHandle<'wc> {
    fn drop(&mut self) {
        // Unregister our observer.
        let superclass_ptr = cast_to_superclass(self.obs.as_ref().borrow_mut().peer_mut());
        unsafe { self.web_contents.as_mut().RemoveObserver(superclass_ptr) };
    }
}

impl<'wc> AsRef<ffi::content::RenderFrameHost> for RenderFrameHostHandle<'wc> {
    fn as_ref(&self) -> &ffi::content::RenderFrameHost {
        let ref_non_mut = self.obs.as_ref().borrow();
        // Safety: the .rfh field is guaranteed to be a RenderFrameHost
        // and we are observing its lifetime so it will be reset to null
        // if destroyed.
        unsafe { ref_non_mut.rfh.as_ref() }.expect("This RenderFrameHost was already destroyed")
    }
}

impl<'wc> PinMut<ffi::content::RenderFrameHost> for RenderFrameHostHandle<'wc> {
    fn pin_mut(&mut self) -> Pin<&mut ffi::content::RenderFrameHost> {
        let ref_mut = self.obs.as_ref().borrow_mut();
        // Safety: the .rfh field is guaranteed to be a RenderFrameHost
        // and we are observing its lifetime so it will be reset to null
        // if destroyed.
        unsafe { ref_mut.rfh.as_mut().map(|p| Pin::new_unchecked(p)) }
            .expect("This RenderFrameHost was already destroyed")
    }
}

impl<'wc> Deref for RenderFrameHostHandle<'wc> {
    type Target = ffi::content::RenderFrameHost;
    fn deref(&self) -> &Self::Target {
        self.as_ref()
    }
}

#[doc(hidden)]
struct RenderFrameHostRefMut<'a>(RefMut<'a, RenderFrameHostForWebContents>);

#[doc(hidden)]
struct RenderFrameHostRef<'a>(Ref<'a, RenderFrameHostForWebContents>);

impl<'a> AsRef<ffi::content::RenderFrameHost> for RenderFrameHostRef<'a> {
    fn as_ref(&self) -> &ffi::content::RenderFrameHost {
        // Safety:
        // Creation precondition is that self.0.rfh is not null
        // and it can't be destroyed whilst this borrow exists.
        unsafe { self.0.rfh.as_ref().unwrap() }
    }
}

impl<'a> PinMut<ffi::content::RenderFrameHost> for RenderFrameHostRefMut<'a> {
    fn pin_mut(&mut self) -> Pin<&mut ffi::content::RenderFrameHost> {
        // Safety:
        // Creation precondition is that self.0.rfh is not null
        // and it can't be destroyed whilst this borrow exists.
        unsafe { Pin::new_unchecked(self.0.rfh.as_mut().unwrap()) }
    }
}

impl<'a> AsRef<ffi::content::RenderFrameHost> for RenderFrameHostRefMut<'a> {
    fn as_ref(&self) -> &ffi::content::RenderFrameHost {
        // Safety:
        // Creation precondition is that self.0.rfh is not null
        // and it can't be destroyed whilst this borrow exists.
        unsafe { self.0.rfh.as_ref().unwrap() }
    }
}

impl<'a> Deref for RenderFrameHostRef<'a> {
    type Target = ffi::content::RenderFrameHost;
    fn deref(&self) -> &Self::Target {
        self.as_ref()
    }
}

impl<'a> Deref for RenderFrameHostRefMut<'a> {
    type Target = ffi::content::RenderFrameHost;
    fn deref(&self) -> &Self::Target {
        self.as_ref()
    }
}

#[is_subclass(superclass("content::WebContentsObserver"))]
#[doc(hidden)]
pub struct RenderFrameHostForWebContents {
    rfh: *mut ffi::content::RenderFrameHost,
}

impl ffi::content::WebContentsObserver_methods for RenderFrameHostForWebContents {
    unsafe fn RenderFrameDeleted(&mut self, destroyed_rfh: *mut ffi::content::RenderFrameHost) {
        if self.rfh == destroyed_rfh {
            self.rfh = std::ptr::null_mut()
        }
    }
}

fn cast_to_superclass(
    obs: Pin<&mut ffi::RenderFrameHostForWebContentsCpp>,
) -> *mut ffi::content::WebContentsObserver {
    // This horrid code will all go away once we implement
    // https://github.com/google/autocxx/issues/592; safe wrappers will
    // be automatically generated to allow upcasting to superclasses.
    // NB this code is probably actually _wrong_ too meanwhile; we need to cast
    // on the C++ side.
    let subclass_obs_ptr =
        unsafe { Pin::into_inner_unchecked(obs) } as *mut ffi::RenderFrameHostForWebContentsCpp;
    unsafe {
        std::mem::transmute::<
            *mut ffi::RenderFrameHostForWebContentsCpp,
            *mut ffi::content::WebContentsObserver,
        >(subclass_obs_ptr)
    }
}
<|endoftext|>


<commit_before>#![no_main]

#[macro_use] extern crate libfuzzer_sys;
extern crate toml_edit;

use toml_edit::Document;

fuzz_target!(|data| {
    if let Ok(data) = std::str::from_utf8(data) {
        let doc = data.parse::<Document>();
        assert!(doc.is_ok());
        let doc = doc.unwrap();
        assert_eq!(doc.to_string(), data);
    }
});
<commit_msg>fix(fuzz): generated data is not always valid toml<commit_after>#![no_main]

#[macro_use] extern crate libfuzzer_sys;
extern crate toml_edit;

use toml_edit::Document;

fuzz_target!(|data| {
    if let Ok(data) = std::str::from_utf8(data) {
        let doc = data.parse::<Document>();
        if let Ok(doc) = doc {
            assert_eq!(doc.to_string(), data);
        }
    }
});
<|endoftext|>


<commit_before>//! A synchronous client for the PostgreSQL database.
//!
//! # Example
//!
//! ```no_run
//! use postgres::{Client, NoTls};
//!
//! # fn main() -> Result<(), postgres::Error> {
//! let mut client = Client::connect("host=localhost user=postgres", NoTls)?;
//!
//! client.simple_query("
//!     CREATE TABLE person (
//!         id      SERIAL PRIMARY KEY,
//!         name    TEXT NOT NULL,
//!         data    BYTEA
//!     )
//! ")?;
//!
//! let name = "Ferris";
//! let data = None::<&[u8]>;
//! client.execute(
//!     "INSERT INTO person (name, data) VALUES ($1, $2)",
//!     &[&name, &data],
//! )?;
//!
//! for row in client.query("SELECT id, name, data FROM person", &[])? {
//!     let id: i32 = row.get(0);
//!     let name: &str = row.get(1);
//!     let data: Option<&[u8]> = row.get(2);
//!
//!     println!("found person: {} {} {:?}", id, name, data);
//! }
//! # Ok(())
//! # }
//! ```
//!
//! # Implementation
//!
//! This crate is a lightweight wrapper over tokio-postgres. The `tokio_postgres::Connection` is spawned onto an
//! executor, and the `tokio_postgres::Client` is wrapped in the `postgres::Client`, which simply waits on the futures
//! the nonblocking client creates.
//!
//! # Runtime
//!
//! A client can be constructed directly from a `tokio-postgres` client via a `From` implementation, but the `runtime`
//! Cargo feature (enabled by default) provides a more convenient interface. By default, connections will be spawned
//! onto a static tokio `Runtime`, but a custom `Executor` can also be used instead.
//!
//! # SSL/TLS support
//!
//! TLS support is implemented via external libraries. `Client::connect` and `Config::connect` take a TLS implementation
//! as an argument. The `NoTls` type in this crate can be used when TLS is not required. Otherwise, the
//! `postgres-openssl` and `postgres-native-tls` crates provide implementations backed by the `openssl` and `native-tls`
//! crates, respectively.
#![doc(html_root_url = "https://docs.rs/postgres/0.16.0-rc.2")]
#![warn(clippy::all, rust_2018_idioms, missing_docs)]

#[cfg(feature = "runtime")]
use lazy_static::lazy_static;
#[cfg(feature = "runtime")]
use tokio::runtime::{self, Runtime};

#[cfg(feature = "runtime")]
pub use tokio_postgres::Socket;
pub use tokio_postgres::{error, row, tls, types, Column, Portal, SimpleQueryMessage, Statement};

pub use crate::client::*;
#[cfg(feature = "runtime")]
pub use crate::config::Config;
pub use crate::copy_out_reader::*;
#[doc(no_inline)]
pub use crate::error::Error;
pub use crate::query_iter::*;
pub use crate::query_portal_iter::*;
#[doc(no_inline)]
pub use crate::row::{Row, SimpleQueryRow};
pub use crate::simple_query_iter::*;
#[doc(no_inline)]
pub use crate::tls::NoTls;
pub use crate::to_statement::*;
pub use crate::transaction::*;

mod client;
#[cfg(feature = "runtime")]
pub mod config;
mod copy_out_reader;
mod query_iter;
mod query_portal_iter;
mod simple_query_iter;
mod to_statement;
mod transaction;

#[cfg(feature = "runtime")]
#[cfg(test)]
mod test;

#[cfg(feature = "runtime")]
lazy_static! {
    static ref RUNTIME: Runtime = runtime::Builder::new()
        .name_prefix("postgres-")
        .build()
        .unwrap();
}
<commit_msg>Reexport macros from tokio-postgres<commit_after>//! A synchronous client for the PostgreSQL database.
//!
//! # Example
//!
//! ```no_run
//! use postgres::{Client, NoTls};
//!
//! # fn main() -> Result<(), postgres::Error> {
//! let mut client = Client::connect("host=localhost user=postgres", NoTls)?;
//!
//! client.simple_query("
//!     CREATE TABLE person (
//!         id      SERIAL PRIMARY KEY,
//!         name    TEXT NOT NULL,
//!         data    BYTEA
//!     )
//! ")?;
//!
//! let name = "Ferris";
//! let data = None::<&[u8]>;
//! client.execute(
//!     "INSERT INTO person (name, data) VALUES ($1, $2)",
//!     &[&name, &data],
//! )?;
//!
//! for row in client.query("SELECT id, name, data FROM person", &[])? {
//!     let id: i32 = row.get(0);
//!     let name: &str = row.get(1);
//!     let data: Option<&[u8]> = row.get(2);
//!
//!     println!("found person: {} {} {:?}", id, name, data);
//! }
//! # Ok(())
//! # }
//! ```
//!
//! # Implementation
//!
//! This crate is a lightweight wrapper over tokio-postgres. The `tokio_postgres::Connection` is spawned onto an
//! executor, and the `tokio_postgres::Client` is wrapped in the `postgres::Client`, which simply waits on the futures
//! the nonblocking client creates.
//!
//! # Runtime
//!
//! A client can be constructed directly from a `tokio-postgres` client via a `From` implementation, but the `runtime`
//! Cargo feature (enabled by default) provides a more convenient interface. By default, connections will be spawned
//! onto a static tokio `Runtime`, but a custom `Executor` can also be used instead.
//!
//! # SSL/TLS support
//!
//! TLS support is implemented via external libraries. `Client::connect` and `Config::connect` take a TLS implementation
//! as an argument. The `NoTls` type in this crate can be used when TLS is not required. Otherwise, the
//! `postgres-openssl` and `postgres-native-tls` crates provide implementations backed by the `openssl` and `native-tls`
//! crates, respectively.
#![doc(html_root_url = "https://docs.rs/postgres/0.16.0-rc.2")]
#![warn(clippy::all, rust_2018_idioms, missing_docs)]

#[cfg(feature = "runtime")]
use lazy_static::lazy_static;
#[cfg(feature = "runtime")]
use tokio::runtime::{self, Runtime};

#[cfg(feature = "runtime")]
pub use tokio_postgres::Socket;
pub use tokio_postgres::{
    accepts, error, row, tls, to_sql_checked, types, Column, Portal, SimpleQueryMessage, Statement,
};

pub use crate::client::*;
#[cfg(feature = "runtime")]
pub use crate::config::Config;
pub use crate::copy_out_reader::*;
#[doc(no_inline)]
pub use crate::error::Error;
pub use crate::query_iter::*;
pub use crate::query_portal_iter::*;
#[doc(no_inline)]
pub use crate::row::{Row, SimpleQueryRow};
pub use crate::simple_query_iter::*;
#[doc(no_inline)]
pub use crate::tls::NoTls;
pub use crate::to_statement::*;
pub use crate::transaction::*;

mod client;
#[cfg(feature = "runtime")]
pub mod config;
mod copy_out_reader;
mod query_iter;
mod query_portal_iter;
mod simple_query_iter;
mod to_statement;
mod transaction;

#[cfg(feature = "runtime")]
#[cfg(test)]
mod test;

#[cfg(feature = "runtime")]
lazy_static! {
    static ref RUNTIME: Runtime = runtime::Builder::new()
        .name_prefix("postgres-")
        .build()
        .unwrap();
}
<|endoftext|>


<commit_before>use std::{error::Error, fs, path::Path};

use hyper::{
    service::{make_service_fn, service_fn},
    Body, Response, Server,
};
use hyperlocal::UnixServerExt;

const PHRASE: &'static str = "It's a Unix system. I know this.";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
    let path = Path::new("/tmp/hyperlocal.sock");

    if path.exists() {
        fs::remove_file(path)?;
    }

    let make_service = make_service_fn(|_| async {
        Ok::<_, hyper::Error>(service_fn(|_req| async {
            Ok::<_, hyper::Error>(Response::new(Body::from(PHRASE)))
        }))
    });

    Server::bind_unix(path)?.serve(make_service).await?;

    Ok(())
}
<commit_msg>address clippy err<commit_after>use std::{error::Error, fs, path::Path};

use hyper::{
    service::{make_service_fn, service_fn},
    Body, Response, Server,
};
use hyperlocal::UnixServerExt;

const PHRASE: &str = "It's a Unix system. I know this.";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
    let path = Path::new("/tmp/hyperlocal.sock");

    if path.exists() {
        fs::remove_file(path)?;
    }

    let make_service = make_service_fn(|_| async {
        Ok::<_, hyper::Error>(service_fn(|_req| async {
            Ok::<_, hyper::Error>(Response::new(Body::from(PHRASE)))
        }))
    });

    Server::bind_unix(path)?.serve(make_service).await?;

    Ok(())
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2017 Boucher, Antoni <bouanto@zoho.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#![feature(proc_macro)]

extern crate gtk;
#[macro_use]
extern crate relm;
extern crate relm_attributes;
#[macro_use]
extern crate relm_derive;

use gtk::{Inhibit, WidgetExt};
use relm::Widget;
use relm_attributes::widget;

use self::Msg::*;

#[derive(Msg)]
pub enum LabelMsg {
}

#[derive(Clone)]
pub struct LabelModel {
    counter: i32,
}

#[widget]
impl Widget for Label {
    fn model() -> LabelModel {
        LabelModel {
            counter: 0,
        }
    }

    fn init_view(&self) {
        self.label.set_text("Test");
    }

    fn update(&mut self, _event: LabelMsg, _model: &mut LabelModel) {
        self.label.set_text("");
    }

    view! {
        #[name="label"]
        gtk::Label {
            text: &model.counter.to_string(),
        }
    }
}

#[derive(Msg)]
pub enum Msg {
    Quit,
}

#[widget]
impl Widget for Win {
    fn model() -> () {
    }

    fn update(&mut self, event: Msg, _model: &mut ()) {
        match event {
            Quit => gtk::main_quit(),
        }
    }

    view! {
        gtk::Window {
            Label,
            delete_event(_, _) => (Quit, Inhibit(false)),
        }
    }
}

fn main() {
    relm::run::<Win>().unwrap();
}
<commit_msg>Move method<commit_after>/*
 * Copyright (c) 2017 Boucher, Antoni <bouanto@zoho.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#![feature(proc_macro)]

extern crate gtk;
#[macro_use]
extern crate relm;
extern crate relm_attributes;
#[macro_use]
extern crate relm_derive;

use gtk::{Inhibit, WidgetExt};
use relm::Widget;
use relm_attributes::widget;

use self::Msg::*;

#[derive(Msg)]
pub enum LabelMsg {
}

#[derive(Clone)]
pub struct LabelModel {
    counter: i32,
}

#[widget]
impl Widget for Label {
    fn init_view(&self) {
        self.label.set_text("Test");
    }

    fn model() -> LabelModel {
        LabelModel {
            counter: 0,
        }
    }

    fn update(&mut self, _event: LabelMsg, _model: &mut LabelModel) {
        self.label.set_text("");
    }

    view! {
        #[name="label"]
        gtk::Label {
            text: &model.counter.to_string(),
        }
    }
}

#[derive(Msg)]
pub enum Msg {
    Quit,
}

#[widget]
impl Widget for Win {
    fn model() -> () {
    }

    fn update(&mut self, event: Msg, _model: &mut ()) {
        match event {
            Quit => gtk::main_quit(),
        }
    }

    view! {
        gtk::Window {
            Label,
            delete_event(_, _) => (Quit, Inhibit(false)),
        }
    }
}

fn main() {
    relm::run::<Win>().unwrap();
}
<|endoftext|>