<commit_before>#![feature(asm)]
#![feature(box_syntax)]
#![feature(coerce_unsized)]
#![feature(core_simd)]
#![feature(core_slice_ext)]
#![feature(core_str_ext)]
#![feature(fundamental)]
#![feature(lang_items)]
#![feature(no_std)]
#![feature(raw)]
#![feature(unique)]
#![feature(unsize)]
#![no_std]

use core::mem::size_of;

use common::debug::*;
use common::pio::*;
use common::memory::*;
use common::string::*;
use common::url::*;

use drivers::keyboard::*;
use drivers::mouse::*;
use drivers::pci::*;
use drivers::ps2::*;
use drivers::serial::*;

use graphics::bmp::*;

use programs::filemanager::*;
use programs::session::*;

use schemes::file::*;
use schemes::http::*;
use schemes::memory::*;
use schemes::pci::*;
use schemes::random::*;

mod alloc {
    pub mod boxed;
}

mod common {
    pub mod debug;
    pub mod elf;
    pub mod memory;
    pub mod pci;
    pub mod pio;
    pub mod random;
    pub mod safeptr;
    pub mod string;
    pub mod vector;
    pub mod url;
}

mod drivers {
    pub mod disk;
    pub mod ide;
    pub mod keyboard;
    pub mod mouse;
    pub mod pci;
    pub mod ps2;
    pub mod serial;
}

mod filesystems {
    pub mod unfs;
}

mod graphics {
    pub mod bmp;
    pub mod color;
    pub mod display;
    pub mod point;
    pub mod size;
    pub mod window;
}

mod network {
    pub mod arp;
    pub mod common;
    pub mod ethernet;
    pub mod http;
    pub mod icmp;
    pub mod intel8254x;
    pub mod ipv4;
    pub mod rtl8139;
    pub mod tcp;
    pub mod udp;
}

mod programs {
    pub mod editor;
    pub mod executor;
    pub mod filemanager;
    pub mod session;
    pub mod viewer;
}

mod schemes {
    pub mod file;
    pub mod http;
    pub mod memory;
    pub mod pci;
    pub mod random;
}

mod usb {
    pub mod xhci;
}

static mut session_ptr: *mut Session = 0 as *mut Session;

unsafe fn init(){
    serial_init();

    dd(size_of::<usize>() * 8);
    d(" bits");
    dl();

    page_init();
    cluster_init();

    session_ptr = alloc(size_of::<Session>()) as *mut Session;
    *session_ptr = Session::new();
    let session = &mut *session_ptr;

    session.items.insert(0, box FileManager::new("".to_string()));

    keyboard_init();
    mouse_init();

    session.modules.push(box PS2);
    session.modules.push(box Serial::new(0x3F8, 0x4));

    pci_init(session);

    session.modules.push(box FileScheme);
    session.modules.push(box HTTPScheme);
    session.modules.push(box MemoryScheme);
    session.modules.push(box PCIScheme);
    session.modules.push(box RandomScheme);

    session.on_url_async(&URL::from_string("file:///background.bmp".to_string()), box |response: String|{
        if response.data as usize > 0 {
            (*session_ptr).display.background = BMP::from_data(response.data as usize);
        }
    });
}

#[no_mangle]
pub unsafe fn kernel(interrupt: u32) {
    match interrupt {
        0x20 => (), //timer
        0x21 => (*session_ptr).on_irq(0x1), //keyboard
        0x23 => (*session_ptr).on_irq(0x3), // serial 2 and 4
        0x24 => (*session_ptr).on_irq(0x4), // serial 1 and 3
        0x2B => (*session_ptr).on_irq(0xB), //pci
        0x2C => (*session_ptr).on_irq(0xC), //mouse
        0x2E => (*session_ptr).on_irq(0xE), //disk
        0x2F => (*session_ptr).on_irq(0xF), //disk
        0xFF => { // main loop
            init();

            loop {
                (*session_ptr).on_poll();
                (*session_ptr).redraw();
                asm!("sti");
                asm!("hlt");
                asm!("cli"); // TODO: Allow preempting
            }
        }
        _ => {
            d("I: ");
            dh(interrupt as usize);
            dl();
        }
    }

    if interrupt >= 0x20 && interrupt < 0x30 {
        if interrupt >= 0x28 {
            outb(0xA0, 0x20);
        }

        outb(0x20, 0x20);
    }
}

#[no_mangle]
pub extern "C" fn memmove(dst: *mut u8, src: *const u8, len: isize){
    unsafe {
        if src < dst {
            let mut i = len;
            while i > 0 {
                i -= 1;
                *dst.offset(i) = *src.offset(i);
            }
        }else{
            let mut i = 0;
            while i < len {
                *dst.offset(i) = *src.offset(i);
                i += 1;
            }
        }
    }
}

#[no_mangle]
pub extern "C" fn memset(src: *mut u8, c: i32, len: isize) {
    unsafe {
        let mut i = 0;
        while i < len {
            *src.offset(i) = c as u8;
            i += 1;
        }
    }
}
<commit_msg>Add exception definitions<commit_after>#![feature(asm)]
#![feature(box_syntax)]
#![feature(coerce_unsized)]
#![feature(core_simd)]
#![feature(core_slice_ext)]
#![feature(core_str_ext)]
#![feature(fundamental)]
#![feature(lang_items)]
#![feature(no_std)]
#![feature(raw)]
#![feature(unique)]
#![feature(unsize)]
#![no_std]

use core::mem::size_of;

use common::debug::*;
use common::pio::*;
use common::memory::*;
use common::string::*;
use common::url::*;

use drivers::keyboard::*;
use drivers::mouse::*;
use drivers::pci::*;
use drivers::ps2::*;
use drivers::serial::*;

use graphics::bmp::*;

use programs::filemanager::*;
use programs::session::*;

use schemes::file::*;
use schemes::http::*;
use schemes::memory::*;
use schemes::pci::*;
use schemes::random::*;

mod alloc {
    pub mod boxed;
}

mod common {
    pub mod debug;
    pub mod elf;
    pub mod memory;
    pub mod pci;
    pub mod pio;
    pub mod random;
    pub mod safeptr;
    pub mod string;
    pub mod vector;
    pub mod url;
}

mod drivers {
    pub mod disk;
    pub mod ide;
    pub mod keyboard;
    pub mod mouse;
    pub mod pci;
    pub mod ps2;
    pub mod serial;
}

mod filesystems {
    pub mod unfs;
}

mod graphics {
    pub mod bmp;
    pub mod color;
    pub mod display;
    pub mod point;
    pub mod size;
    pub mod window;
}

mod network {
    pub mod arp;
    pub mod common;
    pub mod ethernet;
    pub mod http;
    pub mod icmp;
    pub mod intel8254x;
    pub mod ipv4;
    pub mod rtl8139;
    pub mod tcp;
    pub mod udp;
}

mod programs {
    pub mod editor;
    pub mod executor;
    pub mod filemanager;
    pub mod session;
    pub mod viewer;
}

mod schemes {
    pub mod file;
    pub mod http;
    pub mod memory;
    pub mod pci;
    pub mod random;
}

mod usb {
    pub mod xhci;
}

static mut session_ptr: *mut Session = 0 as *mut Session;

unsafe fn init(){
    serial_init();

    dd(size_of::<usize>() * 8);
    d(" bits");
    dl();

    page_init();
    cluster_init();

    session_ptr = alloc(size_of::<Session>()) as *mut Session;
    *session_ptr = Session::new();
    let session = &mut *session_ptr;

    session.items.insert(0, box FileManager::new("".to_string()));

    keyboard_init();
    mouse_init();

    session.modules.push(box PS2);
    session.modules.push(box Serial::new(0x3F8, 0x4));

    pci_init(session);

    session.modules.push(box FileScheme);
    session.modules.push(box HTTPScheme);
    session.modules.push(box MemoryScheme);
    session.modules.push(box PCIScheme);
    session.modules.push(box RandomScheme);

    session.on_url_async(&URL::from_string("file:///background.bmp".to_string()), box |response: String|{
        if response.data as usize > 0 {
            (*session_ptr).display.background = BMP::from_data(response.data as usize);
        }
    });
}

#[no_mangle]
pub unsafe fn kernel(interrupt: u32) {
    match interrupt {
        0x20 => (), //timer
        0x21 => (*session_ptr).on_irq(0x1), //keyboard
        0x23 => (*session_ptr).on_irq(0x3), // serial 2 and 4
        0x24 => (*session_ptr).on_irq(0x4), // serial 1 and 3
        0x29 => (*session_ptr).on_irq(0x9), //pci
        0x2A => (*session_ptr).on_irq(0xA), //pci
        0x2B => (*session_ptr).on_irq(0xB), //pci
        0x2C => (*session_ptr).on_irq(0xC), //mouse
        0x2E => (*session_ptr).on_irq(0xE), //disk
        0x2F => (*session_ptr).on_irq(0xF), //disk
        0xFF => { // main loop
            init();

            loop {
                (*session_ptr).on_poll();
                (*session_ptr).redraw();
                asm!("sti");
                asm!("hlt");
                asm!("cli"); // TODO: Allow preempting
            }
        },
        0x0 => {
            d("Divide by zero exception\n");
        },
        0x1 => {
            d("Debug exception\n");
        },
        0x2 => {
            d("Non-maskable interrupt\n");
        },
        0x3 => {
            d("Breakpoint exception\n");
        },
        0x4 => {
            d("Overflow exception\n");
        },
        0x5 => {
            d("Bound range exceeded exception\n");
        },
        0x6 => {
            d("Invalid opcode exception\n");
        },
        0x7 => {
            d("Device not available exception\n");
        },
        0x8 => {
            d("Double fault\n");
        },
        0xA => {
            d("Invalid TSS exception\n");
        },
        0xB => {
            d("Segment not present exception\n");
        },
        0xC => {
            d("Stack-segment fault\n");
        },
        0xD => {
            d("General protection fault\n");
        },
        0xE => {
            d("Page fault\n");
        },
        0x10 => {
            d("x87 floating-point exception\n");
        },
        0x11 => {
            d("Alignment check exception\n");
        },
        0x12 => {
            d("Machine check exception\n");
        },
        0x13 => {
            d("SIMD floating-point exception\n");
        },
        0x14 => {
            d("Virtualization exception\n");
        },
        0x1E => {
            d("Security exception\n");
        },
        _ => {
            d("I: ");
            dh(interrupt as usize);
            dl();
        }
    }

    if interrupt >= 0x20 && interrupt < 0x30 {
        if interrupt >= 0x28 {
            outb(0xA0, 0x20);
        }

        outb(0x20, 0x20);
    }
}

#[no_mangle]
pub extern "C" fn memmove(dst: *mut u8, src: *const u8, len: isize){
    unsafe {
        if src < dst {
            let mut i = len;
            while i > 0 {
                i -= 1;
                *dst.offset(i) = *src.offset(i);
            }
        }else{
            let mut i = 0;
            while i < len {
                *dst.offset(i) = *src.offset(i);
                i += 1;
            }
        }
    }
}

#[no_mangle]
pub extern "C" fn memset(src: *mut u8, c: i32, len: isize) {
    unsafe {
        let mut i = 0;
        while i < len {
            *src.offset(i) = c as u8;
            i += 1;
        }
    }
}
<|endoftext|>


<commit_before>extern crate specs;

use self::specs::{Join, WriteStorage, ReadStorage, System, Fetch};

use model::comp::{Pos, Vel, Acc, Bounds, Friction};
use util::clamp;

pub struct Physics;
impl<'a> System<'a> for Physics {
    #[allow(type_complexity)]
    type SystemData = (WriteStorage<'a, Pos>,
     WriteStorage<'a, Vel>,
     ReadStorage<'a, Acc>,
     ReadStorage<'a, Friction>,
     Fetch<'a, Bounds<Vel>>,
     Fetch<'a, Bounds<Pos>>);

    fn run(&mut self, (mut pos, mut vel, acc, friction, vel_bounds, pos_bounds): Self::SystemData) {
        for (mut vel, acc) in (&mut vel, &acc).join() {
            vel.x = clamp(vel.x + acc.x, vel_bounds.min.x, vel_bounds.max.x);
            vel.y = clamp(vel.y + acc.y, vel_bounds.min.y, vel_bounds.max.y);
        }

        for (mut vel, friction) in (&mut vel, &friction).join() {
            if vel.y == 0 {
                continue;
            }
            let sign = if vel.y < 0 { 1 } else { -1 };
            use std::ops::Deref;
            let friction = *friction.deref();
            let new_vel = sign * friction;
            vel.y += if new_vel > -friction && new_vel < friction {
                0
            } else {
                new_vel
            }
        }

        for (mut pos, vel) in (&mut pos, &vel).join() {
            pos.x = clamp(pos.x + vel.x, pos_bounds.min.x, git pos_bounds.max.x);
            pos.y = clamp(pos.y + vel.y, pos_bounds.min.y, pos_bounds.max.y);
        }
    }
}
<commit_msg>Core: Fix typo<commit_after>extern crate specs;

use self::specs::{Join, WriteStorage, ReadStorage, System, Fetch};

use model::comp::{Pos, Vel, Acc, Bounds, Friction};
use util::clamp;

pub struct Physics;
impl<'a> System<'a> for Physics {
    #[allow(type_complexity)]
    type SystemData = (WriteStorage<'a, Pos>,
     WriteStorage<'a, Vel>,
     ReadStorage<'a, Acc>,
     ReadStorage<'a, Friction>,
     Fetch<'a, Bounds<Vel>>,
     Fetch<'a, Bounds<Pos>>);

    fn run(&mut self, (mut pos, mut vel, acc, friction, vel_bounds, pos_bounds): Self::SystemData) {
        for (mut vel, acc) in (&mut vel, &acc).join() {
            vel.x = clamp(vel.x + acc.x, vel_bounds.min.x, vel_bounds.max.x);
            vel.y = clamp(vel.y + acc.y, vel_bounds.min.y, vel_bounds.max.y);
        }

        for (mut vel, friction) in (&mut vel, &friction).join() {
            if vel.y == 0 {
                continue;
            }
            let sign = if vel.y < 0 { 1 } else { -1 };
            use std::ops::Deref;
            let friction = *friction.deref();
            let new_vel = sign * friction;
            vel.y += if new_vel > -friction && new_vel < friction {
                0
            } else {
                new_vel
            }
        }

        for (mut pos, vel) in (&mut pos, &vel).join() {
            pos.x = clamp(pos.x + vel.x, pos_bounds.min.x, pos_bounds.max.x);
            pos.y = clamp(pos.y + vel.y, pos_bounds.min.y, pos_bounds.max.y);
        }
    }
}
<|endoftext|>


<commit_before>use clap::{ArgMatches};
use std::path::Path;
use db;
use std::fs::File;
use std::io::Read;

use rustc_serialize::{Encodable};
use rustc_serialize::json::{self, Encoder};
use rustc_serialize::json::Json;

use std::collections::HashMap;
use std::result::Result;
use rusqlite::Connection;
use rusqlite::Error;

use dbFsFile;

#[derive(Debug)]
struct Person {
    id: i32,
    name: String,
    data: Option<Vec<u8>>
}

pub fn listy(direcory: &str) {
    let path = Path::new(direcory);
    for entry in path.read_dir().expect("read_dir call failed") {
        if let Ok(entry) = entry {
            println!("aaaa{:?}", entry.path());
        }
    }
}

pub fn job_files_list(direcory: &str)  {
    let path = Path::new(direcory);
    for entry in path.read_dir().expect("read_dir call failed") {
        if let Ok(entry) = entry {
            println!("job_files_list{:?}", entry.path());
        }
    }
}

pub fn listy2(direcory: &str) -> Vec<String>{
    println!("listy2{:?}", direcory);
    let mut items = Vec::<String>::new();

    let path = Path::new(direcory);
    for entry in path.read_dir().expect("read_dir call failed") {
        if let Ok(entry) = entry {
            let path = entry.path();
            if path.is_dir() {
                continue;
            }
            let pb_2 = path.as_path();
            let as_path_buf = pb_2.as_os_str();
            let path = String::new() + as_path_buf.to_str().unwrap() ;
            items.push(path);

        }
    }
    return items;
}

pub fn json_loader_old(name: &str)  {
    let mut f = File::open(name).expect("file not found");

    let mut contents = String::new();
    f.read_to_string(&mut contents).expect("something went wrong reading the file");

    let json = Json::from_str(&contents).unwrap();
    //println!("json={}", json);
    let found = json.find_path(&["provides"]);
    if found != None {
        for item in found {
            println!("provides={}", item);
            let as_a_str = item.to_string();
            //db::insert_provider(&conn, as_a_str);
        }
    }
    let found = json.find_path(&["name"]);
    if found != None {
        for item in found {
            println!("name={}", item);
        }
    }
    let found = json.find_path(&["script"]);
    if found != None {
        for item in found {
            println!("script={}", item);
        }
    }
    let found = json.find_path(&["variables"]);
    if found != None {

        for item in found {
            println!("variables={}", item);
            let bill = item.find_path(&["require_keys"]);
            if bill != None {
                for item2 in bill {
                    println!("variables::require_keys={}", item2);
                }
            }
            let bill = item.find_path(&["provides_keys"]);
            if bill != None {
                for item2 in bill {
                    println!("variables::provides_keys={}", item2);
                }
            }
            let bill = item.find_path(&["require_values"]);
            if bill != None {
                for item2 in bill {
                    let ben = item2.find_path(&[""]);

                    for itme3 in ben {
                        println!("variables::itme3={}", itme3);
                    }
                }
            }
        }

    }
    let found = json.find_path(&["depends"]);
    if found != None {
        for item in found {
            println!("depends={}", item);
        }
    }

}

pub fn loader(name: &str) -> String {
    let mut f = File::open(name).expect("file not found");

    let mut contents = String::new();
    f.read_to_string(&mut contents).expect("something went wrong reading the file");

    return contents;

}

pub fn json_loader_name(conn: &Connection, content: &str)  {
    let mut contents = String::new();
    let json = Json::from_str(&content);

    match json {
        Ok(json) => {
            let found = json.find_path(&["name"]);
            if found != None {
                for item in found {

                    db::insert_job(conn, item.to_string());

                    //println!("name={}", item);
                }
            }
        }
        Err(_)=> {}
    }
    //return json.unwrap();
}

pub fn json_loader_provides_keys(conn: &Connection, content: &str)  {
    let mut contents = String::new();
    let json = Json::from_str(&content);

    match json {
        Ok(json) => {
            let found = json.find_path(&["provides_keys"]);
            if found != None {
                for item in found {
                    let str_item = item.to_string();
                    let str_item_clone1 = str_item.clone();
                    db::insert_provider(conn, item.to_string());

                    //println!("provides_keys={}", item);
                }
            }
        }
        Err(_)=> {}
    }
    //return json.unwrap();
}

pub fn json_loader_require_keys(conn: &Connection, content: &str)  {
    let mut contents = String::new();
    let json = Json::from_str(&content);
    match json {
        Ok(json) => {
            let found = json.find_path(&["require_keys"]);
            if found != None {
                for item in found {

                    db::insert_job_variable_name(conn, item.to_string());

                    //println!("require_keys={}", item);
                }
            }
        }
        Err(_)=> {}
    }
    //return json.unwrap();
}

pub fn deligate(matches : ArgMatches) {

    let conn = db::connect();
    db::create_tables(&conn);

    if let Some(in_v) = matches.values_of("dir-scripts") {
        for in_file in in_v {
            //println!("An input dir-scripts: {}", in_file);
           listy(&in_file);

        }
    }

        // If we specified the multiple() setting we can get all the values
    if let Some(in_v) = matches.values_of("env") {
        for in_file in in_v {
            println!("An input file: {}", in_file);
            job_files_list(&in_file);
        }
    }

    if let Some(in_v) = matches.values_of("dir-jobs") {
        for in_file in in_v {
            let filename = in_file.to_string();
            db::insert_fs_dir(&conn, 0, filename);
        }
    }
    for directory in db::list_fs_dir(&conn) {
        let foo = directory.id;
        let foo_name = directory.name;
        let file_list = listy2(&foo_name);
        for fnccc in file_list {
            println!("An input file: {}", fnccc);
            let s1 = fnccc.clone();
            db::insert_fs_file(&conn, foo, fnccc);
            let mut pk = 10;
            db::pk_fs_file_by_name(&conn, s1, &mut pk);
            println!("ssss: {}", pk);
        }
    }

    let mut scores = HashMap::new();
    for filename in db::list_fs_file(&conn) {
        let mut name = String::from(filename.name);
        let name2 = name.clone();
        let loader_rc = loader(name2.trim());
        scores.insert(name,loader_rc );
    }

    for filename in db::list_fs_file(&conn) {
        let name = filename.name;
        json_loader_name(&conn, &loader(&name));

    }
    for filename in db::list_fs_file(&conn) {
        let name = filename.name;
        json_loader_provides_keys(&conn, &loader(&name));

    }

    for filename in db::list_fs_file(&conn) {
        let name = filename.name;
        json_loader_require_keys(&conn, &loader(&name));

    }

    for filename in db::list_fs_file(&conn) {
        let name = filename.name;
        json_loader_require_keys(&conn, &loader(&name));

    }

    for filename in db::list_provider(&conn) {
        println!("list_provider{:?}", filename);
    }
}

<commit_msg>move to better loader json_loader_elephant_job_pk<commit_after>use clap::{ArgMatches};
use std::path::Path;
use db;
use std::fs::File;
use std::io::Read;
use rustc_serialize;
use rustc_serialize::{Encodable};
use rustc_serialize::json::{self, Encoder};
use rustc_serialize::json::Json;

use std::collections::HashMap;
use std::result::Result;
use rusqlite::Connection;
use rusqlite::Error;

use dbFsFile;

use std::result;

#[derive(Debug)]
struct Person {
    id: i32,
    name: String,
    data: Option<Vec<u8>>
}

pub fn listy(direcory: &str) {
    let path = Path::new(direcory);
    for entry in path.read_dir().expect("read_dir call failed") {
        if let Ok(entry) = entry {
            println!("aaaa{:?}", entry.path());
        }
    }
}

pub fn job_files_list(direcory: &str)  {
    let path = Path::new(direcory);
    for entry in path.read_dir().expect("read_dir call failed") {
        if let Ok(entry) = entry {
            println!("job_files_list{:?}", entry.path());
        }
    }
}

pub fn listy2(direcory: &str) -> Vec<String>{
    println!("listy2{:?}", direcory);
    let mut items = Vec::<String>::new();

    let path = Path::new(direcory);
    for entry in path.read_dir().expect("read_dir call failed") {
        if let Ok(entry) = entry {
            let path = entry.path();
            if path.is_dir() {
                continue;
            }
            let pb_2 = path.as_path();
            let as_path_buf = pb_2.as_os_str();
            let path = String::new() + as_path_buf.to_str().unwrap() ;
            items.push(path);

        }
    }
    return items;
}

pub fn json_loader_old(name: &str)  {
    let mut f = File::open(name).expect("file not found");

    let mut contents = String::new();
    f.read_to_string(&mut contents).expect("something went wrong reading the file");

    let json = Json::from_str(&contents).unwrap();
    //println!("json={}", json);
    let found = json.find_path(&["provides"]);
    if found != None {
        for item in found {
            println!("provides={}", item);
            let as_a_str = item.to_string();
            //db::insert_provider(&conn, as_a_str);
        }
    }
    let found = json.find_path(&["name"]);
    if found != None {
        for item in found {
            println!("name={}", item);
        }
    }
    let found = json.find_path(&["script"]);
    if found != None {
        for item in found {
            println!("script={}", item);
        }
    }
    let found = json.find_path(&["variables"]);
    if found != None {

        for item in found {
            println!("variables={}", item);
            let bill = item.find_path(&["require_keys"]);
            if bill != None {
                for item2 in bill {
                    println!("variables::require_keys={}", item2);
                }
            }
            let bill = item.find_path(&["provides_keys"]);
            if bill != None {
                for item2 in bill {
                    println!("variables::provides_keys={}", item2);
                }
            }
            let bill = item.find_path(&["require_values"]);
            if bill != None {
                for item2 in bill {
                    let ben = item2.find_path(&[""]);

                    for itme3 in ben {
                        println!("variables::itme3={}", itme3);
                    }
                }
            }
        }

    }
    let found = json.find_path(&["depends"]);
    if found != None {
        for item in found {
            println!("depends={}", item);
        }
    }

}

pub fn loader(name: &str) -> String {
    let mut f = File::open(name).expect("file not found");

    let mut contents = String::new();
    f.read_to_string(&mut contents).expect("something went wrong reading the file");

    return contents;

}

fn json_loader_elephant_variable_pk(conn: &Connection, variable_pk :i32, text :&String) -> i32 {
    return variable_pk;
}

fn json_loader_elephant_job_pk(conn: &Connection, text :&String) -> i32 {
    let mut pk_job :i32 = 0;
    let rc = db::pk_job_by_name(conn, &text, &mut pk_job);
    match rc {
        Ok(pk) => {
            return pk_job;
        }
        Err(_) => {
            let doink = db::insert_job(conn, &text);
            if doink.is_err() {
                return 0;
            }
            match doink {
                Ok(pk) => {
                    let doin3k = db::pk_job_by_name(conn, &text, &mut pk_job);
                    match doin3k {
                        Ok(pk) => {
                            return pk_job;
                            }
                        Err(_) => {
                                println!("Failed to select job");
                                return 0;
                            }
                        }
                    }
                Err(_) => {
                    println!("Failed to insert job");
                    return 0;
                }
            }

        }
    }
    return pk_job;
}

pub fn json_loader_elephant(conn: &Connection, json :&rustc_serialize::json::Json) {
    let mut pk_job :i32 = 0;
    let found = json.find_path(&["name"]);
    if found != None {
        for item in found {
            let str_item = item.to_string();
            pk_job = json_loader_elephant_job_pk(conn, &str_item);
            println!("pk_job::name={}", pk_job);
        }
    }

    let found = json.find_path(&["variables"]);
    if found != None {

        for item in found {
            let bill = item.find_path(&["require_keys"]);
            if bill != None {
                for item2 in bill {
                    if item2.is_array() {
                        let ssd = item2.as_array();
                        let sdf = ssd.unwrap();
                        let george = sdf.len();
                        let itemfdsd = sdf.iter();
                        for elem in itemfdsd{
                            println!("variables::require_key={}", elem.to_string());
                        }
                    }
                }
            }
            let bill = item.find_path(&["provides_keys"]);
            if bill != None {
                for item2 in bill {

                    if item2.is_array() {
                        let ssd = item2.as_array();
                        let sdf = ssd.unwrap();
                        let george = sdf.len();
                        let itemfdsd = sdf.iter();
                        for elem in itemfdsd{
                            println!("variables::provide_key={}", elem.to_string());
                        }
                    }
                }
            }
            let bill = item.find_path(&["require_values"]);
            if bill != None {
                for item2 in bill {

                    let ben = item2.find_path(&[""]);

                    for itme3 in ben {
                        println!("variables::itme3={}", itme3);
                    }
                }
            }
        }

    }
    println!("pk_job={}", pk_job);
}

pub fn json_loader_name(conn: &Connection, content: &str)  {
    let mut contents = String::new();
    let json = Json::from_str(&content);
    let mut pk_job :i32 = 0;
    match json {
        Ok(json) => {
            json_loader_elephant(conn, &json);
        }
        Err(_)=> {}
    }
    //return json.unwrap();
}

pub fn json_loader_provides_keys(conn: &Connection, content: &str)  {
    let mut contents = String::new();
    let json = Json::from_str(&content);

    match json {
        Ok(json) => {
            let found = json.find_path(&["provides_keys"]);
            if found != None {
                for item in found {
                    let str_item = item.to_string();
                    let str_item_clone1 = str_item.clone();
                    db::insert_provider(conn, item.to_string());

                    //println!("provides_keys={}", item);
                }
            }
        }
        Err(_)=> {}
    }
    //return json.unwrap();
}

pub fn json_loader_require_keys(conn: &Connection, content: &str)  {
    let mut contents = String::new();
    let json = Json::from_str(&content);
    match json {
        Ok(json) => {
            let found = json.find_path(&["require_keys"]);
            if found != None {
                for item in found {

                    db::insert_job_variable_name(conn, item.to_string());

                    //println!("require_keys={}", item);
                }
            }
        }
        Err(_)=> {}
    }
    //return json.unwrap();
}

pub fn deligate(matches : ArgMatches) {

    let conn = db::connect();
    db::create_tables(&conn);

    if let Some(in_v) = matches.values_of("dir-scripts") {
        for in_file in in_v {
            //println!("An input dir-scripts: {}", in_file);
           listy(&in_file);

        }
    }

        // If we specified the multiple() setting we can get all the values
    if let Some(in_v) = matches.values_of("env") {
        for in_file in in_v {
            println!("An input file: {}", in_file);
            job_files_list(&in_file);
        }
    }

    if let Some(in_v) = matches.values_of("dir-jobs") {
        for in_file in in_v {
            let filename = in_file.to_string();
            db::insert_fs_dir(&conn, 0, filename);
        }
    }
    for directory in db::list_fs_dir(&conn) {
        let foo = directory.id;
        let foo_name = directory.name;
        let file_list = listy2(&foo_name);
        for fnccc in file_list {
            println!("An input file: {}", fnccc);
            let s1 = fnccc.clone();
            db::insert_fs_file(&conn, foo, fnccc);
            let mut pk = 10;
            db::pk_fs_file_by_name(&conn, s1, &mut pk);
            println!("ssss: {}", pk);
        }
    }

    let mut scores = HashMap::new();
    for filename in db::list_fs_file(&conn) {
        let mut name = String::from(filename.name);
        let name2 = name.clone();
        let loader_rc = loader(name2.trim());
        scores.insert(name,loader_rc );
    }

    for filename in db::list_fs_file(&conn) {
        let name = filename.name;
        json_loader_name(&conn, &loader(&name));

    }
    for filename in db::list_fs_file(&conn) {
        let name = filename.name;
        json_loader_provides_keys(&conn, &loader(&name));

    }

    for filename in db::list_fs_file(&conn) {
        let name = filename.name;
        json_loader_require_keys(&conn, &loader(&name));

    }

    for filename in db::list_fs_file(&conn) {
        let name = filename.name;
        json_loader_require_keys(&conn, &loader(&name));

    }

    for filename in db::list_provider(&conn) {
        println!("list_provider{:?}", filename);
    }
}

<|endoftext|>


<commit_before>// Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![cfg(target_os = "macos")]
use libc::{LC_CTYPE, setlocale};
use std::ffi::{CString, CStr};
use std::os::raw::c_char;
use std::ptr::null;
use std::slice;
use std::str;
use std::env;

use objc::runtime::{Class, Object};

pub fn set_locale_environment() {
    let locale_id = unsafe {
        let locale_class = Class::get("NSLocale").unwrap();
        let locale: *const Object = msg_send![locale_class, currentLocale];
        let _ : () = msg_send![locale_class, release];
        // `localeIdentifier` returns extra metadata with the locale (including currency and
        // collator) on newer versions of macOS. This is not a valid locale, so we use
        // `languageCode` and `countryCode`, if they're available (macOS 10.12+):
        // https://developer.apple.com/documentation/foundation/nslocale/1416263-localeidentifier?language=objc
        // https://developer.apple.com/documentation/foundation/nslocale/1643060-countrycode?language=objc
        // https://developer.apple.com/documentation/foundation/nslocale/1643026-languagecode?language=objc
        let is_language_code_supported: bool = msg_send![locale, respondsToSelector:sel!(languageCode)];
        let is_country_code_supported: bool = msg_send![locale, respondsToSelector:sel!(countryCode)];
        let locale_id = if is_language_code_supported && is_country_code_supported {
            let language_code: *const Object = msg_send![locale, languageCode];
            let country_code: *const Object = msg_send![locale, countryCode];
            let language_code_str = nsstring_as_str(language_code).to_owned();
            let _ : () = msg_send![language_code, release];
            let country_code_str = nsstring_as_str(country_code).to_owned();
            let _ : () = msg_send![country_code, release];
            format!("{}_{}.UTF-8", &language_code_str, &country_code_str)
        } else {
            let identifier: *const Object = msg_send![locale, localeIdentifier];
            let identifier_str = nsstring_as_str(identifier).to_owned();
            let _ : () = msg_send![identifier, release];
            identifier_str
        };
        let _ : () = msg_send![locale, release];
        locale_id
    };
    // check if locale_id is valid
    let locale_c_str = CString::new(locale_id.to_owned()).unwrap();
    let locale_ptr = locale_c_str.as_ptr();
    let locale_id = unsafe {
        // save a copy of original setting
        let original = setlocale(LC_CTYPE, null());
        let saved_original = if original.is_null() {
            CString::new("").unwrap()
        } else {
            CStr::from_ptr(original).to_owned()
        };
        // try setting `locale_id`
        let modified = setlocale(LC_CTYPE, locale_ptr);
        let result = if modified.is_null() {
            String::from("")
        } else {
            locale_id
        };
        // restore original setting
        setlocale(LC_CTYPE, saved_original.as_ptr());
        result
    };

    env::set_var("LANG", &locale_id);
}

const UTF8_ENCODING: usize = 4;

unsafe fn nsstring_as_str<'a>(nsstring: *const Object) -> &'a str {
    let cstr: *const c_char = msg_send![nsstring, UTF8String];
    let len: usize = msg_send![nsstring, lengthOfBytesUsingEncoding: UTF8_ENCODING];
    str::from_utf8(slice::from_raw_parts(cstr as *const u8, len)).unwrap()
}

#[cfg(not(target_os = "macos"))]
pub fn set_locale_environment() {}
<commit_msg>Fix locale_id for older versions of OS X (<= 10.11)<commit_after>// Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![cfg(target_os = "macos")]
use libc::{LC_CTYPE, setlocale};
use std::ffi::{CString, CStr};
use std::os::raw::c_char;
use std::ptr::null;
use std::slice;
use std::str;
use std::env;

use objc::runtime::{Class, Object};

pub fn set_locale_environment() {
    let locale_id = unsafe {
        let locale_class = Class::get("NSLocale").unwrap();
        let locale: *const Object = msg_send![locale_class, currentLocale];
        let _ : () = msg_send![locale_class, release];
        // `localeIdentifier` returns extra metadata with the locale (including currency and
        // collator) on newer versions of macOS. This is not a valid locale, so we use
        // `languageCode` and `countryCode`, if they're available (macOS 10.12+):
        // https://developer.apple.com/documentation/foundation/nslocale/1416263-localeidentifier?language=objc
        // https://developer.apple.com/documentation/foundation/nslocale/1643060-countrycode?language=objc
        // https://developer.apple.com/documentation/foundation/nslocale/1643026-languagecode?language=objc
        let is_language_code_supported: bool = msg_send![locale, respondsToSelector:sel!(languageCode)];
        let is_country_code_supported: bool = msg_send![locale, respondsToSelector:sel!(countryCode)];
        let locale_id = if is_language_code_supported && is_country_code_supported {
            let language_code: *const Object = msg_send![locale, languageCode];
            let country_code: *const Object = msg_send![locale, countryCode];
            let language_code_str = nsstring_as_str(language_code).to_owned();
            let _ : () = msg_send![language_code, release];
            let country_code_str = nsstring_as_str(country_code).to_owned();
            let _ : () = msg_send![country_code, release];
            format!("{}_{}.UTF-8", &language_code_str, &country_code_str)
        } else {
            let identifier: *const Object = msg_send![locale, localeIdentifier];
            let identifier_str = nsstring_as_str(identifier).to_owned();
            let _ : () = msg_send![identifier, release];
            identifier_str + ".UTF-8"
        };
        let _ : () = msg_send![locale, release];
        locale_id
    };
    // check if locale_id is valid
    let locale_c_str = CString::new(locale_id.to_owned()).unwrap();
    let locale_ptr = locale_c_str.as_ptr();
    let locale_id = unsafe {
        // save a copy of original setting
        let original = setlocale(LC_CTYPE, null());
        let saved_original = if original.is_null() {
            CString::new("").unwrap()
        } else {
            CStr::from_ptr(original).to_owned()
        };
        // try setting `locale_id`
        let modified = setlocale(LC_CTYPE, locale_ptr);
        let result = if modified.is_null() {
            String::from("")
        } else {
            locale_id
        };
        // restore original setting
        setlocale(LC_CTYPE, saved_original.as_ptr());
        result
    };

    env::set_var("LANG", &locale_id);
}

const UTF8_ENCODING: usize = 4;

unsafe fn nsstring_as_str<'a>(nsstring: *const Object) -> &'a str {
    let cstr: *const c_char = msg_send![nsstring, UTF8String];
    let len: usize = msg_send![nsstring, lengthOfBytesUsingEncoding: UTF8_ENCODING];
    str::from_utf8(slice::from_raw_parts(cstr as *const u8, len)).unwrap()
}

#[cfg(not(target_os = "macos"))]
pub fn set_locale_environment() {}
<|endoftext|>


<commit_before>macro_rules! offset_of(
    ($ty:ty, $field:ident) => {
        &(*(0 as *const $ty)).$field as *const _ as usize
    }
);

macro_rules! container_of (
    ($ptr: expr, $container: ty, $field: ident) => {
        ($ptr as *mut u8).offset(-(offset_of!($container, $field) as isize)) as *mut $container
    }
);

macro_rules! c_str {
    ($s:expr) => {
        concat!($s, "\0").as_ptr() as *const i8
    }
}

#[macro_export]
macro_rules! wlr_log {
    ($verb: expr, $($msg:tt)*) => {{
        //format!($($msg)*)
        use $crate::wlroots_sys::_wlr_log;
        use $crate::wlroots_sys::log_importance_t::*;
        use ::std::ffi::CString;
        unsafe {
            let fmt = CString::new(format!($($msg)*))
                .expect("Could not convert log message to C string");
            let raw = fmt.into_raw();
            _wlr_log($verb, c_str!("[%s:%lu] %s"),
                    c_str!(file!()), line!(), raw);
            // Deallocate string
            CString::from_raw(raw);
        }
    }}
}
<commit_msg>Documented macros<commit_after>/// Gets the offset of a field. Used by container_of!
macro_rules! offset_of(
    ($ty:ty, $field:ident) => {
        &(*(0 as *const $ty)).$field as *const _ as usize
    }
);

/// Gets the parent struct from a pointer.
/// VERY unsafe. The parent struct _must_ be repr(C), and the
/// type passed to this macro _must_ match the type of the parent.
macro_rules! container_of (
    ($ptr: expr, $container: ty, $field: ident) => {
        ($ptr as *mut u8).offset(-(offset_of!($container, $field) as isize)) as *mut $container
    }
);

/// Convert a literal string to a C string.
/// Note: Does not check for internal nulls, nor does it do any conversions on
/// the grapheme clustors. Just passes the bytes as is.
/// So probably only works on ASCII.
macro_rules! c_str {
    ($s:expr) => {
        concat!($s, "\0").as_ptr() as *const i8
    }
}

#[macro_export]
/// Logs a message using wlroots' logging capability.
macro_rules! wlr_log {
    ($verb: expr, $($msg:tt)*) => {{
        //format!($($msg)*)
        use $crate::wlroots_sys::_wlr_log;
        use $crate::wlroots_sys::log_importance_t::*;
        use ::std::ffi::CString;
        unsafe {
            let fmt = CString::new(format!($($msg)*))
                .expect("Could not convert log message to C string");
            let raw = fmt.into_raw();
            _wlr_log($verb, c_str!("[%s:%lu] %s"),
                    c_str!(file!()), line!(), raw);
            // Deallocate string
            CString::from_raw(raw);
        }
    }}
}
<|endoftext|>


<commit_before>//! Flycheck provides the functionality needed to run `cargo check` or
//! another compatible command (f.x. clippy) in a background thread and provide
//! LSP diagnostics based on the output of the command.

use std::{
    fmt,
    io::{self, BufRead, BufReader},
    path::PathBuf,
    process::{self, Command, Stdio},
    time::Duration,
};

use crossbeam_channel::{never, select, unbounded, Receiver, Sender};
use serde::Deserialize;
use stdx::JodChild;

pub use cargo_metadata::diagnostic::{
    Applicability, Diagnostic, DiagnosticCode, DiagnosticLevel, DiagnosticSpan,
    DiagnosticSpanMacroExpansion,
};

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FlycheckConfig {
    CargoCommand {
        command: String,
        target_triple: Option<String>,
        all_targets: bool,
        no_default_features: bool,
        all_features: bool,
        features: Vec<String>,
        extra_args: Vec<String>,
    },
    CustomCommand {
        command: String,
        args: Vec<String>,
    },
}

impl fmt::Display for FlycheckConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FlycheckConfig::CargoCommand { command, .. } => write!(f, "cargo {}", command),
            FlycheckConfig::CustomCommand { command, args } => {
                write!(f, "{} {}", command, args.join(" "))
            }
        }
    }
}

/// Flycheck wraps the shared state and communication machinery used for
/// running `cargo check` (or other compatible command) and providing
/// diagnostics based on the output.
/// The spawned thread is shut down when this struct is dropped.
#[derive(Debug)]
pub struct FlycheckHandle {
    // XXX: drop order is significant
    sender: Sender<Restart>,
    thread: jod_thread::JoinHandle,
}

impl FlycheckHandle {
    pub fn spawn(
        id: usize,
        sender: Box<dyn Fn(Message) + Send>,
        config: FlycheckConfig,
        workspace_root: PathBuf,
    ) -> FlycheckHandle {
        let actor = FlycheckActor::new(id, sender, config, workspace_root);
        let (sender, receiver) = unbounded::<Restart>();
        let thread = jod_thread::spawn(move || actor.run(receiver));
        FlycheckHandle { sender, thread }
    }

    /// Schedule a re-start of the cargo check worker.
    pub fn update(&self) {
        self.sender.send(Restart).unwrap();
    }
}

pub enum Message {
    /// Request adding a diagnostic with fixes included to a file
    AddDiagnostic { workspace_root: PathBuf, diagnostic: Diagnostic },

    /// Request check progress notification to client
    Progress {
        /// Flycheck instance ID
        id: usize,
        progress: Progress,
    },
}

impl fmt::Debug for Message {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Message::AddDiagnostic { workspace_root, diagnostic } => f
                .debug_struct("AddDiagnostic")
                .field("workspace_root", workspace_root)
                .field("diagnostic_code", &diagnostic.code.as_ref().map(|it| &it.code))
                .finish(),
            Message::Progress { id, progress } => {
                f.debug_struct("Progress").field("id", id).field("progress", progress).finish()
            }
        }
    }
}

#[derive(Debug)]
pub enum Progress {
    DidStart,
    DidCheckCrate(String),
    DidFinish(io::Result<()>),
    DidCancel,
}

struct Restart;

struct FlycheckActor {
    id: usize,
    sender: Box<dyn Fn(Message) + Send>,
    config: FlycheckConfig,
    workspace_root: PathBuf,
    /// WatchThread exists to wrap around the communication needed to be able to
    /// run `cargo check` without blocking. Currently the Rust standard library
    /// doesn't provide a way to read sub-process output without blocking, so we
    /// have to wrap sub-processes output handling in a thread and pass messages
    /// back over a channel.
    cargo_handle: Option<CargoHandle>,
}

enum Event {
    Restart(Restart),
    CheckEvent(Option<CargoMessage>),
}

impl FlycheckActor {
    fn new(
        id: usize,
        sender: Box<dyn Fn(Message) + Send>,
        config: FlycheckConfig,
        workspace_root: PathBuf,
    ) -> FlycheckActor {
        FlycheckActor { id, sender, config, workspace_root, cargo_handle: None }
    }
    fn progress(&self, progress: Progress) {
        self.send(Message::Progress { id: self.id, progress });
    }
    fn next_event(&self, inbox: &Receiver<Restart>) -> Option<Event> {
        let check_chan = self.cargo_handle.as_ref().map(|cargo| &cargo.receiver);
        select! {
            recv(inbox) -> msg => msg.ok().map(Event::Restart),
            recv(check_chan.unwrap_or(&never())) -> msg => Some(Event::CheckEvent(msg.ok())),
        }
    }
    fn run(mut self, inbox: Receiver<Restart>) {
        while let Some(event) = self.next_event(&inbox) {
            match event {
                Event::Restart(Restart) => {
                    while let Ok(Restart) = inbox.recv_timeout(Duration::from_millis(50)) {}

                    self.cancel_check_process();

                    let mut command = self.check_command();
                    log::info!("restart flycheck {:?}", command);
                    command.stdout(Stdio::piped()).stderr(Stdio::null()).stdin(Stdio::null());
                    if let Ok(child) = command.spawn().map(JodChild) {
                        self.cargo_handle = Some(CargoHandle::spawn(child));
                        self.progress(Progress::DidStart);
                    }
                }
                Event::CheckEvent(None) => {
                    // Watcher finished, replace it with a never channel to
                    // avoid busy-waiting.
                    let cargo_handle = self.cargo_handle.take().unwrap();
                    let res = cargo_handle.join();
                    if res.is_err() {
                        log::error!(
                            "Flycheck failed to run the following command: {:?}",
                            self.check_command()
                        )
                    }
                    self.progress(Progress::DidFinish(res));
                }
                Event::CheckEvent(Some(message)) => match message {
                    CargoMessage::CompilerArtifact(msg) => {
                        self.progress(Progress::DidCheckCrate(msg.target.name));
                    }

                    CargoMessage::Diagnostic(msg) => {
                        self.send(Message::AddDiagnostic {
                            workspace_root: self.workspace_root.clone(),
                            diagnostic: msg,
                        });
                    }
                },
            }
        }
        // If we rerun the thread, we need to discard the previous check results first
        self.cancel_check_process();
    }
    fn cancel_check_process(&mut self) {
        if self.cargo_handle.take().is_some() {
            self.progress(Progress::DidCancel);
        }
    }
    fn check_command(&self) -> Command {
        let mut cmd = match &self.config {
            FlycheckConfig::CargoCommand {
                command,
                target_triple,
                no_default_features,
                all_targets,
                all_features,
                extra_args,
                features,
            } => {
                let mut cmd = Command::new(toolchain::cargo());
                cmd.arg(command);
                cmd.args(&["--workspace", "--message-format=json", "--manifest-path"])
                    .arg(self.workspace_root.join("Cargo.toml"));

                if let Some(target) = target_triple {
                    cmd.args(&["--target", target.as_str()]);
                }
                if *all_targets {
                    cmd.arg("--all-targets");
                }
                if *all_features {
                    cmd.arg("--all-features");
                } else {
                    if *no_default_features {
                        cmd.arg("--no-default-features");
                    }
                    if !features.is_empty() {
                        cmd.arg("--features");
                        cmd.arg(features.join(" "));
                    }
                }
                cmd.args(extra_args);
                cmd
            }
            FlycheckConfig::CustomCommand { command, args } => {
                let mut cmd = Command::new(command);
                cmd.args(args);
                cmd
            }
        };
        cmd.current_dir(&self.workspace_root);
        cmd
    }

    fn send(&self, check_task: Message) {
        (self.sender)(check_task)
    }
}

struct CargoHandle {
    child: JodChild,
    #[allow(unused)]
    thread: jod_thread::JoinHandle<io::Result<bool>>,
    receiver: Receiver<CargoMessage>,
}

impl CargoHandle {
    fn spawn(mut child: JodChild) -> CargoHandle {
        let child_stdout = child.stdout.take().unwrap();
        let (sender, receiver) = unbounded();
        let actor = CargoActor::new(child_stdout, sender);
        let thread = jod_thread::spawn(move || actor.run());
        CargoHandle { child, thread, receiver }
    }
    fn join(mut self) -> io::Result<()> {
        // It is okay to ignore the result, as it only errors if the process is already dead
        let _ = self.child.kill();
        let exit_status = self.child.wait()?;
        let read_at_least_one_message = self.thread.join()?;
        if !exit_status.success() && !read_at_least_one_message {
            // FIXME: Read the stderr to display the reason, see `read2()` reference in PR comment:
            // https://github.com/rust-analyzer/rust-analyzer/pull/3632#discussion_r395605298
            return Err(io::Error::new(
                io::ErrorKind::Other,
                format!(
                    "Cargo watcher failed, the command produced no valid metadata (exit code: {:?})",
                    exit_status
                ),
            ));
        }
        Ok(())
    }
}

struct CargoActor {
    child_stdout: process::ChildStdout,
    sender: Sender<CargoMessage>,
}

impl CargoActor {
    fn new(child_stdout: process::ChildStdout, sender: Sender<CargoMessage>) -> CargoActor {
        CargoActor { child_stdout, sender }
    }
    fn run(self) -> io::Result<bool> {
        // We manually read a line at a time, instead of using serde's
        // stream deserializers, because the deserializer cannot recover
        // from an error, resulting in it getting stuck, because we try to
        // be resilient against failures.
        //
        // Because cargo only outputs one JSON object per line, we can
        // simply skip a line if it doesn't parse, which just ignores any
        // erroneus output.
        let stdout = BufReader::new(self.child_stdout);
        let mut read_at_least_one_message = false;
        for message in stdout.lines() {
            let message = match message {
                Ok(message) => message,
                Err(err) => {
                    log::error!("Invalid json from cargo check, ignoring ({})", err);
                    continue;
                }
            };

            read_at_least_one_message = true;

            // Try to deserialize a message from Cargo.
            {
                let mut deserializer = serde_json::Deserializer::from_str(&message);
                deserializer.disable_recursion_limit();
                if let Ok(message) = cargo_metadata::Message::deserialize(&mut deserializer) {
                    // Skip certain kinds of messages to only spend time on what's useful
                    match message {
                        cargo_metadata::Message::CompilerArtifact(artifact) if !artifact.fresh => {
                            self.sender.send(CargoMessage::CompilerArtifact(artifact)).unwrap()
                        }
                        cargo_metadata::Message::CompilerMessage(msg) => {
                            self.sender.send(CargoMessage::Diagnostic(msg.message)).unwrap()
                        }

                        cargo_metadata::Message::CompilerArtifact(_)
                        | cargo_metadata::Message::BuildScriptExecuted(_)
                        | cargo_metadata::Message::BuildFinished(_)
                        | cargo_metadata::Message::TextLine(_)
                        | _ => (),
                    }
                }
            }

            // Try to deserialize a Diagnostic directly from Rustc.
            {
                let mut deserializer = serde_json::Deserializer::from_str(&message);
                deserializer.disable_recursion_limit();
                if let Ok(message) = Diagnostic::deserialize(&mut deserializer) {
                    self.sender.send(CargoMessage::Diagnostic(message)).unwrap()
                }
            }
        }
        Ok(read_at_least_one_message)
    }
}

enum CargoMessage {
    CompilerArtifact(cargo_metadata::Artifact),
    Diagnostic(Diagnostic),
}
<commit_msg>Code review feedback.<commit_after>//! Flycheck provides the functionality needed to run `cargo check` or
//! another compatible command (f.x. clippy) in a background thread and provide
//! LSP diagnostics based on the output of the command.

use std::{
    fmt,
    io::{self, BufRead, BufReader},
    path::PathBuf,
    process::{self, Command, Stdio},
    time::Duration,
};

use crossbeam_channel::{never, select, unbounded, Receiver, Sender};
use serde::Deserialize;
use stdx::JodChild;

pub use cargo_metadata::diagnostic::{
    Applicability, Diagnostic, DiagnosticCode, DiagnosticLevel, DiagnosticSpan,
    DiagnosticSpanMacroExpansion,
};

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FlycheckConfig {
    CargoCommand {
        command: String,
        target_triple: Option<String>,
        all_targets: bool,
        no_default_features: bool,
        all_features: bool,
        features: Vec<String>,
        extra_args: Vec<String>,
    },
    CustomCommand {
        command: String,
        args: Vec<String>,
    },
}

impl fmt::Display for FlycheckConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FlycheckConfig::CargoCommand { command, .. } => write!(f, "cargo {}", command),
            FlycheckConfig::CustomCommand { command, args } => {
                write!(f, "{} {}", command, args.join(" "))
            }
        }
    }
}

/// Flycheck wraps the shared state and communication machinery used for
/// running `cargo check` (or other compatible command) and providing
/// diagnostics based on the output.
/// The spawned thread is shut down when this struct is dropped.
#[derive(Debug)]
pub struct FlycheckHandle {
    // XXX: drop order is significant
    sender: Sender<Restart>,
    thread: jod_thread::JoinHandle,
}

impl FlycheckHandle {
    pub fn spawn(
        id: usize,
        sender: Box<dyn Fn(Message) + Send>,
        config: FlycheckConfig,
        workspace_root: PathBuf,
    ) -> FlycheckHandle {
        let actor = FlycheckActor::new(id, sender, config, workspace_root);
        let (sender, receiver) = unbounded::<Restart>();
        let thread = jod_thread::spawn(move || actor.run(receiver));
        FlycheckHandle { sender, thread }
    }

    /// Schedule a re-start of the cargo check worker.
    pub fn update(&self) {
        self.sender.send(Restart).unwrap();
    }
}

pub enum Message {
    /// Request adding a diagnostic with fixes included to a file
    AddDiagnostic { workspace_root: PathBuf, diagnostic: Diagnostic },

    /// Request check progress notification to client
    Progress {
        /// Flycheck instance ID
        id: usize,
        progress: Progress,
    },
}

impl fmt::Debug for Message {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Message::AddDiagnostic { workspace_root, diagnostic } => f
                .debug_struct("AddDiagnostic")
                .field("workspace_root", workspace_root)
                .field("diagnostic_code", &diagnostic.code.as_ref().map(|it| &it.code))
                .finish(),
            Message::Progress { id, progress } => {
                f.debug_struct("Progress").field("id", id).field("progress", progress).finish()
            }
        }
    }
}

#[derive(Debug)]
pub enum Progress {
    DidStart,
    DidCheckCrate(String),
    DidFinish(io::Result<()>),
    DidCancel,
}

struct Restart;

struct FlycheckActor {
    id: usize,
    sender: Box<dyn Fn(Message) + Send>,
    config: FlycheckConfig,
    workspace_root: PathBuf,
    /// WatchThread exists to wrap around the communication needed to be able to
    /// run `cargo check` without blocking. Currently the Rust standard library
    /// doesn't provide a way to read sub-process output without blocking, so we
    /// have to wrap sub-processes output handling in a thread and pass messages
    /// back over a channel.
    cargo_handle: Option<CargoHandle>,
}

enum Event {
    Restart(Restart),
    CheckEvent(Option<CargoMessage>),
}

impl FlycheckActor {
    fn new(
        id: usize,
        sender: Box<dyn Fn(Message) + Send>,
        config: FlycheckConfig,
        workspace_root: PathBuf,
    ) -> FlycheckActor {
        FlycheckActor { id, sender, config, workspace_root, cargo_handle: None }
    }
    fn progress(&self, progress: Progress) {
        self.send(Message::Progress { id: self.id, progress });
    }
    fn next_event(&self, inbox: &Receiver<Restart>) -> Option<Event> {
        let check_chan = self.cargo_handle.as_ref().map(|cargo| &cargo.receiver);
        select! {
            recv(inbox) -> msg => msg.ok().map(Event::Restart),
            recv(check_chan.unwrap_or(&never())) -> msg => Some(Event::CheckEvent(msg.ok())),
        }
    }
    fn run(mut self, inbox: Receiver<Restart>) {
        while let Some(event) = self.next_event(&inbox) {
            match event {
                Event::Restart(Restart) => {
                    while let Ok(Restart) = inbox.recv_timeout(Duration::from_millis(50)) {}

                    self.cancel_check_process();

                    let mut command = self.check_command();
                    log::info!("restart flycheck {:?}", command);
                    command.stdout(Stdio::piped()).stderr(Stdio::null()).stdin(Stdio::null());
                    if let Ok(child) = command.spawn().map(JodChild) {
                        self.cargo_handle = Some(CargoHandle::spawn(child));
                        self.progress(Progress::DidStart);
                    }
                }
                Event::CheckEvent(None) => {
                    // Watcher finished, replace it with a never channel to
                    // avoid busy-waiting.
                    let cargo_handle = self.cargo_handle.take().unwrap();
                    let res = cargo_handle.join();
                    if res.is_err() {
                        log::error!(
                            "Flycheck failed to run the following command: {:?}",
                            self.check_command()
                        )
                    }
                    self.progress(Progress::DidFinish(res));
                }
                Event::CheckEvent(Some(message)) => match message {
                    CargoMessage::CompilerArtifact(msg) => {
                        self.progress(Progress::DidCheckCrate(msg.target.name));
                    }

                    CargoMessage::Diagnostic(msg) => {
                        self.send(Message::AddDiagnostic {
                            workspace_root: self.workspace_root.clone(),
                            diagnostic: msg,
                        });
                    }
                },
            }
        }
        // If we rerun the thread, we need to discard the previous check results first
        self.cancel_check_process();
    }
    fn cancel_check_process(&mut self) {
        if self.cargo_handle.take().is_some() {
            self.progress(Progress::DidCancel);
        }
    }
    fn check_command(&self) -> Command {
        let mut cmd = match &self.config {
            FlycheckConfig::CargoCommand {
                command,
                target_triple,
                no_default_features,
                all_targets,
                all_features,
                extra_args,
                features,
            } => {
                let mut cmd = Command::new(toolchain::cargo());
                cmd.arg(command);
                cmd.args(&["--workspace", "--message-format=json", "--manifest-path"])
                    .arg(self.workspace_root.join("Cargo.toml"));

                if let Some(target) = target_triple {
                    cmd.args(&["--target", target.as_str()]);
                }
                if *all_targets {
                    cmd.arg("--all-targets");
                }
                if *all_features {
                    cmd.arg("--all-features");
                } else {
                    if *no_default_features {
                        cmd.arg("--no-default-features");
                    }
                    if !features.is_empty() {
                        cmd.arg("--features");
                        cmd.arg(features.join(" "));
                    }
                }
                cmd.args(extra_args);
                cmd
            }
            FlycheckConfig::CustomCommand { command, args } => {
                let mut cmd = Command::new(command);
                cmd.args(args);
                cmd
            }
        };
        cmd.current_dir(&self.workspace_root);
        cmd
    }

    fn send(&self, check_task: Message) {
        (self.sender)(check_task)
    }
}

struct CargoHandle {
    child: JodChild,
    #[allow(unused)]
    thread: jod_thread::JoinHandle<io::Result<bool>>,
    receiver: Receiver<CargoMessage>,
}

impl CargoHandle {
    fn spawn(mut child: JodChild) -> CargoHandle {
        let child_stdout = child.stdout.take().unwrap();
        let (sender, receiver) = unbounded();
        let actor = CargoActor::new(child_stdout, sender);
        let thread = jod_thread::spawn(move || actor.run());
        CargoHandle { child, thread, receiver }
    }
    fn join(mut self) -> io::Result<()> {
        // It is okay to ignore the result, as it only errors if the process is already dead
        let _ = self.child.kill();
        let exit_status = self.child.wait()?;
        let read_at_least_one_message = self.thread.join()?;
        if !exit_status.success() && !read_at_least_one_message {
            // FIXME: Read the stderr to display the reason, see `read2()` reference in PR comment:
            // https://github.com/rust-analyzer/rust-analyzer/pull/3632#discussion_r395605298
            return Err(io::Error::new(
                io::ErrorKind::Other,
                format!(
                    "Cargo watcher failed, the command produced no valid metadata (exit code: {:?})",
                    exit_status
                ),
            ));
        }
        Ok(())
    }
}

struct CargoActor {
    child_stdout: process::ChildStdout,
    sender: Sender<CargoMessage>,
}

impl CargoActor {
    fn new(child_stdout: process::ChildStdout, sender: Sender<CargoMessage>) -> CargoActor {
        CargoActor { child_stdout, sender }
    }
    fn run(self) -> io::Result<bool> {
        // We manually read a line at a time, instead of using serde's
        // stream deserializers, because the deserializer cannot recover
        // from an error, resulting in it getting stuck, because we try to
        // be resilient against failures.
        //
        // Because cargo only outputs one JSON object per line, we can
        // simply skip a line if it doesn't parse, which just ignores any
        // erroneus output.
        let stdout = BufReader::new(self.child_stdout);
        let mut read_at_least_one_message = false;
        for message in stdout.lines() {
            let message = match message {
                Ok(message) => message,
                Err(err) => {
                    log::error!("Invalid json from cargo check, ignoring ({})", err);
                    continue;
                }
            };

            read_at_least_one_message = true;

            // Try to deserialize a message from Cargo or Rustc.
            let mut deserializer = serde_json::Deserializer::from_str(&message);
            deserializer.disable_recursion_limit();
            if let Ok(message) = JsonMessage::deserialize(&mut deserializer) {
                match message {
                    // Skip certain kinds of messages to only spend time on what's useful
                    JsonMessage::Cargo(message) => match message {
                        cargo_metadata::Message::CompilerArtifact(artifact) if !artifact.fresh => {
                            self.sender.send(CargoMessage::CompilerArtifact(artifact)).unwrap()
                        }
                        cargo_metadata::Message::CompilerMessage(msg) => {
                            self.sender.send(CargoMessage::Diagnostic(msg.message)).unwrap()
                        }

                        cargo_metadata::Message::CompilerArtifact(_)
                        | cargo_metadata::Message::BuildScriptExecuted(_)
                        | cargo_metadata::Message::BuildFinished(_)
                        | cargo_metadata::Message::TextLine(_)
                        | _ => (),
                    },
                    JsonMessage::Rustc(message) => {
                        self.sender.send(CargoMessage::Diagnostic(message)).unwrap()
                    }
                }
            }
        }
        Ok(read_at_least_one_message)
    }
}

enum CargoMessage {
    CompilerArtifact(cargo_metadata::Artifact),
    Diagnostic(Diagnostic),
}

#[derive(Deserialize)]
#[serde(untagged)]
enum JsonMessage {
    Cargo(cargo_metadata::Message),
    Rustc(Diagnostic),
}
<|endoftext|>


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

/// Predicate for testing the approximate equality of two values.
#[macro_export]
macro_rules! relative_eq {
    ($lhs:expr, $rhs:expr, $($opt:ident = $opt_val:expr),+) => {{
        $crate::Relative::new(&$lhs, &$rhs)$(.$opt($opt_val))+.eq()
    }};
    ($lhs:expr, $rhs:expr) => {{
        $crate::Relative::new(&$lhs, &$rhs).eq()
    }};
}

/// Predicate for testing the approximate inequality of two values.
#[macro_export]
macro_rules! relative_ne {
    ($lhs:expr, $rhs:expr, $($opt:ident = $opt_val:expr),+) => {{
        $crate::Relative::new(&$lhs, &$rhs)$(.$opt($opt_val))+.ne()
    }};
    ($lhs:expr, $rhs:expr) => {{
        $crate::Relative::new(&$lhs, &$rhs).ne()
    }};
}

#[macro_export]
macro_rules! assert_relative_eq {
    ($given:expr, $expected:expr) => {{
        let (given, expected) = (&($given), &($expected));

        if !relative_eq!(given, expected) {
            panic!(
"assert_relative_eq!({}, {})

    left = {:?}
    right = {:?}

",
                stringify!($given), stringify!($expected),
                given, expected,
            );
        }
    }};
    ($given:expr, $expected:expr, $($opt:ident = $opt_val:expr),+) => {{
        let (given, expected) = (&($given), &($expected));

        if !relative_eq!(given, expected, $($opt = $opt_val),+) {
            panic!(
"assert_relative_eq!({}, {}, {})

    left = {:?}
    right = {:?}

",
                stringify!($given), stringify!($expected),
                stringify!($($opt = $opt_val),+),
                given, expected,
            );
        }
    }};
    ($given:expr, $expected:expr,) => {
        assert_relative_eq!($given, $expected)
    };
    ($given:expr, $expected:expr, $($opt:ident = $opt_val:expr,)+) => {
        assert_relative_eq!($given, $expected, $($opt = $opt_val),+)
    };
}

#[macro_export]
macro_rules! assert_relative_ne {
    ($given:expr, $expected:expr) => {{
        let (given, expected) = (&($given), &($expected));

        if !relative_ne!(given, expected) {
            panic!(
"assert_relative_ne!({}, {})

    left = {:?}
    right = {:?}

",
                stringify!($given), stringify!($expected),
                given, expected,
            );
        }
    }};
    ($given:expr, $expected:expr, $($opt:ident = $opt_val:expr),+) => {{
        let (given, expected) = (&($given), &($expected));

        if !relative_ne!(given, expected, $($opt = $opt_val),+) {
            panic!(
"assert_relative_ne!({}, {}, {})

    left = {:?}
    right = {:?}

",
                stringify!($given), stringify!($expected),
                stringify!($($opt = $opt_val),+),
                given, expected,
            );
        }
    }};
    ($given:expr, $expected:expr,) => {
        assert_relative_ne!($given, $expected)
    };
}

/// Predicate for testing the approximate equality of two values using a maximum ULPs (Units
/// in Last Place).
#[macro_export]
macro_rules! ulps_eq {
    ($lhs:expr, $rhs:expr, $($opt:ident = $opt_val:expr),+) => {{
        $crate::Ulps::new(&$lhs, &$rhs)$(.$opt($opt_val))+.eq()
    }};
    ($lhs:expr, $rhs:expr) => {{
        $crate::Ulps::new(&$lhs, &$rhs).eq()
    }};
}

/// Predicate for testing the approximate inequality of two values using a maximum ULPs (Units
/// in Last Place).
#[macro_export]
macro_rules! ulps_ne {
    ($lhs:expr, $rhs:expr, $($opt:ident = $opt_val:expr),+) => {{
        $crate::Ulps::new(&$lhs, &$rhs)$(.$opt($opt_val))+.ne()
    }};
    ($lhs:expr, $rhs:expr) => {{
        $crate::Ulps::new(&$lhs, &$rhs).ne()
    }};
}

#[macro_export]
macro_rules! assert_ulps_eq {
    ($given:expr, $expected:expr) => {{
        let (given, expected) = (&($given), &($expected));

        if !ulps_eq!(given, expected) {
            panic!(
"assert_ulps_eq!({}, {})

    left = {:?}
    right = {:?}

",
                stringify!($given), stringify!($expected),
                given, expected,
            );
        }
    }};
    ($given:expr, $expected:expr, $($opt:ident = $opt_val:expr),+) => {{
        let (given, expected) = (&($given), &($expected));

        if !ulps_eq!(given, expected, $($opt = $opt_val),+) {
            panic!(
"assert_ulps_eq!({}, {}, {})

    left = {:?}
    right = {:?}

",
                stringify!($given), stringify!($expected),
                stringify!($($opt = $opt_val),+),
                given, expected,
            );
        }
    }};
    ($given:expr, $expected:expr,) => {
        assert_ulps_eq!($given, $expected)
    };
    ($given:expr, $expected:expr, $($opt:ident = $opt_val:expr,)+) => {
        assert_ulps_eq!($given, $expected, $($opt = $opt_val),+)
    };
}

#[macro_export]
macro_rules! assert_ulps_ne {
    ($given:expr, $expected:expr) => {{
        let (given, expected) = (&($given), &($expected));

        if !ulps_ne!(given, expected) {
            panic!(
"assert_ulps_ne!({}, {})

    left = {:?}
    right = {:?}

",
                stringify!($given), stringify!($expected),
                given, expected,
            );
        }
    }};
    ($given:expr, $expected:expr, $($opt:ident = $opt_val:expr),+) => {{
        let (given, expected) = (&($given), &($expected));

        if !ulps_ne!(given, expected, $($opt = $opt_val),+) {
            panic!(
"assert_ulps_ne!({}, {}, {})

    left = {:?}
    right = {:?}

",
                stringify!($given), stringify!($expected),
                stringify!($($opt = $opt_val),+),
                given, expected,
            );
        }
    }};
    ($given:expr, $expected:expr,) => {
        assert_ulps_ne!($given, $expected)
    };
}
<commit_msg>improve usability of error messages of macroses<commit_after>// Copyright 2015 Brendan Zabarauskas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/// Predicate for testing the approximate equality of two values.
#[macro_export]
macro_rules! relative_eq {
    ($lhs:expr, $rhs:expr, $($opt:ident = $opt_val:expr),+) => {{
        $crate::Relative::new(&$lhs, &$rhs)$(.$opt($opt_val))+.eq()
    }};
    ($lhs:expr, $rhs:expr) => {{
        $crate::Relative::new(&$lhs, &$rhs).eq()
    }};
}

/// Predicate for testing the approximate inequality of two values.
#[macro_export]
macro_rules! relative_ne {
    ($lhs:expr, $rhs:expr, $($opt:ident = $opt_val:expr),+) => {{
        $crate::Relative::new(&$lhs, &$rhs)$(.$opt($opt_val))+.ne()
    }};
    ($lhs:expr, $rhs:expr) => {{
        $crate::Relative::new(&$lhs, &$rhs).ne()
    }};
}

#[macro_export]
macro_rules! assert_relative_eq {
    ($given:expr, $expected:expr) => {{
        let (given, expected) = (&($given), &($expected));

        if !relative_eq!(given, expected) {
            panic!(
"assert_relative_eq!({}, {})

    left  = {:?}
    right = {:?}

",
                stringify!($given), stringify!($expected),
                given, expected,
            );
        }
    }};
    ($given:expr, $expected:expr, $($opt:ident = $opt_val:expr),+) => {{
        let (given, expected) = (&($given), &($expected));

        if !relative_eq!(given, expected, $($opt = $opt_val),+) {
            panic!(
"assert_relative_eq!({}, {}, {})

    left  = {:?}
    right = {:?}

",
                stringify!($given), stringify!($expected),
                stringify!($($opt = $opt_val),+),
                given, expected,
            );
        }
    }};
    ($given:expr, $expected:expr,) => {
        assert_relative_eq!($given, $expected)
    };
    ($given:expr, $expected:expr, $($opt:ident = $opt_val:expr,)+) => {
        assert_relative_eq!($given, $expected, $($opt = $opt_val),+)
    };
}

#[macro_export]
macro_rules! assert_relative_ne {
    ($given:expr, $expected:expr) => {{
        let (given, expected) = (&($given), &($expected));

        if !relative_ne!(given, expected) {
            panic!(
"assert_relative_ne!({}, {})

    left  = {:?}
    right = {:?}

",
                stringify!($given), stringify!($expected),
                given, expected,
            );
        }
    }};
    ($given:expr, $expected:expr, $($opt:ident = $opt_val:expr),+) => {{
        let (given, expected) = (&($given), &($expected));

        if !relative_ne!(given, expected, $($opt = $opt_val),+) {
            panic!(
"assert_relative_ne!({}, {}, {})

    left  = {:?}
    right = {:?}

",
                stringify!($given), stringify!($expected),
                stringify!($($opt = $opt_val),+),
                given, expected,
            );
        }
    }};
    ($given:expr, $expected:expr,) => {
        assert_relative_ne!($given, $expected)
    };
}

/// Predicate for testing the approximate equality of two values using a maximum ULPs (Units
/// in Last Place).
#[macro_export]
macro_rules! ulps_eq {
    ($lhs:expr, $rhs:expr, $($opt:ident = $opt_val:expr),+) => {{
        $crate::Ulps::new(&$lhs, &$rhs)$(.$opt($opt_val))+.eq()
    }};
    ($lhs:expr, $rhs:expr) => {{
        $crate::Ulps::new(&$lhs, &$rhs).eq()
    }};
}

/// Predicate for testing the approximate inequality of two values using a maximum ULPs (Units
/// in Last Place).
#[macro_export]
macro_rules! ulps_ne {
    ($lhs:expr, $rhs:expr, $($opt:ident = $opt_val:expr),+) => {{
        $crate::Ulps::new(&$lhs, &$rhs)$(.$opt($opt_val))+.ne()
    }};
    ($lhs:expr, $rhs:expr) => {{
        $crate::Ulps::new(&$lhs, &$rhs).ne()
    }};
}

#[macro_export]
macro_rules! assert_ulps_eq {
    ($given:expr, $expected:expr) => {{
        let (given, expected) = (&($given), &($expected));

        if !ulps_eq!(given, expected) {
            panic!(
"assert_ulps_eq!({}, {})

    left  = {:?}
    right = {:?}

",
                stringify!($given), stringify!($expected),
                given, expected,
            );
        }
    }};
    ($given:expr, $expected:expr, $($opt:ident = $opt_val:expr),+) => {{
        let (given, expected) = (&($given), &($expected));

        if !ulps_eq!(given, expected, $($opt = $opt_val),+) {
            panic!(
"assert_ulps_eq!({}, {}, {})

    left  = {:?}
    right = {:?}

",
                stringify!($given), stringify!($expected),
                stringify!($($opt = $opt_val),+),
                given, expected,
            );
        }
    }};
    ($given:expr, $expected:expr,) => {
        assert_ulps_eq!($given, $expected)
    };
    ($given:expr, $expected:expr, $($opt:ident = $opt_val:expr,)+) => {
        assert_ulps_eq!($given, $expected, $($opt = $opt_val),+)
    };
}

#[macro_export]
macro_rules! assert_ulps_ne {
    ($given:expr, $expected:expr) => {{
        let (given, expected) = (&($given), &($expected));

        if !ulps_ne!(given, expected) {
            panic!(
"assert_ulps_ne!({}, {})

    left  = {:?}
    right = {:?}

",
                stringify!($given), stringify!($expected),
                given, expected,
            );
        }
    }};
    ($given:expr, $expected:expr, $($opt:ident = $opt_val:expr),+) => {{
        let (given, expected) = (&($given), &($expected));

        if !ulps_ne!(given, expected, $($opt = $opt_val),+) {
            panic!(
"assert_ulps_ne!({}, {}, {})

    left  = {:?}
    right = {:?}

",
                stringify!($given), stringify!($expected),
                stringify!($($opt = $opt_val),+),
                given, expected,
            );
        }
    }};
    ($given:expr, $expected:expr,) => {
        assert_ulps_ne!($given, $expected)
    };
}
<|endoftext|>


<commit_before>// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

/// The standard logging macro.
///
/// This macro will generically log with the specified `Level` and `format!`
/// based argument list.
///
/// # Examples
///
/// ```rust
/// # #[macro_use]
/// # extern crate log;
/// use log::Level;
///
/// # fn main() {
/// let data = (42, "Forty-two");
/// let private_data = "private";
///
/// log!(Level::Error, "Received errors: {}, {}", data.0, data.1);
/// log!(target: "app_events", Level::Warn, "App warning: {}, {}, {}",
///     data.0, data.1, private_data);
/// # }
/// ```
#[macro_export(local_inner_macros)]
macro_rules! log {
    (target: $target:expr, $lvl:expr, $($arg:tt)+) => ({
        let lvl = $lvl;
        if lvl <= $crate::STATIC_MAX_LEVEL && lvl <= $crate::max_level() {
            $crate::__private_api_log(
                log_format_args!($($arg)+),
                lvl,
                &($target, log_module_path!(), log_file!(), log_line!()),
            );
        }
    });
    ($lvl:expr, $($arg:tt)+) => (log!(target: log_module_path!(), $lvl, $($arg)+))
}

/// Logs a message at the error level.
///
/// # Examples
///
/// ```rust
/// # #[macro_use]
/// # extern crate log;
/// # fn main() {
/// let (err_info, port) = ("No connection", 22);
///
/// error!("Error: {} on port {}", err_info, port);
/// error!(target: "app_events", "App Error: {}, Port: {}", err_info, 22);
/// # }
/// ```
#[macro_export(local_inner_macros)]
macro_rules! error {
    (target: $target:expr, $($arg:tt)*) => (
        log!(target: $target, $crate::Level::Error, $($arg)*);
    );
    ($($arg:tt)*) => (
        log!($crate::Level::Error, $($arg)*);
    )
}

/// Logs a message at the warn level.
///
/// # Examples
///
/// ```rust
/// # #[macro_use]
/// # extern crate log;
/// # fn main() {
/// let warn_description = "Invalid Input";
///
/// warn!("Warning! {}!", warn_description);
/// warn!(target: "input_events", "App received warning: {}", warn_description);
/// # }
/// ```
#[macro_export(local_inner_macros)]
macro_rules! warn {
    (target: $target:expr, $($arg:tt)*) => (
        log!(target: $target, $crate::Level::Warn, $($arg)*);
    );
    ($($arg:tt)*) => (
        log!($crate::Level::Warn, $($arg)*);
    )
}

/// Logs a message at the info level.
///
/// # Examples
///
/// ```rust
/// # #[macro_use]
/// # extern crate log;
/// # fn main() {
/// # struct Connection { port: u32, speed: f32 }
/// let conn_info = Connection { port: 40, speed: 3.20 };
///
/// info!("Connected to port {} at {} Mb/s", conn_info.port, conn_info.speed);
/// info!(target: "connection_events", "Successfull connection, port: {}, speed: {}",
///       conn_info.port, conn_info.speed);
/// # }
/// ```
#[macro_export(local_inner_macros)]
macro_rules! info {
    (target: $target:expr, $($arg:tt)*) => (
        log!(target: $target, $crate::Level::Info, $($arg)*);
    );
    ($($arg:tt)*) => (
        log!($crate::Level::Info, $($arg)*);
    )
}

/// Logs a message at the debug level.
///
/// # Examples
///
/// ```rust
/// # #[macro_use]
/// # extern crate log;
/// # fn main() {
/// # struct Position { x: f32, y: f32 }
/// let pos = Position { x: 3.234, y: -1.223 };
///
/// debug!("New position: x: {}, y: {}", pos.x, pos.y);
/// debug!(target: "app_events", "New position: x: {}, y: {}", pos.x, pos.y);
/// # }
/// ```
#[macro_export(local_inner_macros)]
macro_rules! debug {
    (target: $target:expr, $($arg:tt)*) => (
        log!(target: $target, $crate::Level::Debug, $($arg)*);
    );
    ($($arg:tt)*) => (
        log!($crate::Level::Debug, $($arg)*);
    )
}

/// Logs a message at the trace level.
///
/// # Examples
///
/// ```rust
/// # #[macro_use]
/// # extern crate log;
/// # fn main() {
/// # struct Position { x: f32, y: f32 }
/// let pos = Position { x: 3.234, y: -1.223 };
///
/// trace!("Position is: x: {}, y: {}", pos.x, pos.y);
/// trace!(target: "app_events", "x is {} and y is {}",
///        if pos.x >= 0.0 { "positive" } else { "negative" },
///        if pos.y >= 0.0 { "positive" } else { "negative" });
/// # }
/// ```
#[macro_export(local_inner_macros)]
macro_rules! trace {
    (target: $target:expr, $($arg:tt)*) => (
        log!(target: $target, $crate::Level::Trace, $($arg)*);
    );
    ($($arg:tt)*) => (
        log!($crate::Level::Trace, $($arg)*);
    )
}

/// Determines if a message logged at the specified level in that module will
/// be logged.
///
/// This can be used to avoid expensive computation of log message arguments if
/// the message would be ignored anyway.
///
/// # Examples
///
/// ```rust
/// # #[macro_use]
/// # extern crate log;
/// use log::Level::Debug;
///
/// # fn foo() {
/// if log_enabled!(Debug) {
///     let data = expensive_call();
///     debug!("expensive debug data: {} {}", data.x, data.y);
/// }
/// if log_enabled!(target: "Global", Debug) {
///    let data = expensive_call();
///    debug!(target: "Global", "expensive debug data: {} {}", data.x, data.y);
/// }
/// # }
/// # struct Data { x: u32, y: u32 }
/// # fn expensive_call() -> Data { Data { x: 0, y: 0 } }
/// # fn main() {}
/// ```
#[macro_export]
macro_rules! log_enabled {
    (target: $target:expr, $lvl:expr) => {{
        let lvl = $lvl;
        lvl <= $crate::STATIC_MAX_LEVEL
            && lvl <= $crate::max_level()
            && $crate::__private_api_enabled(lvl, $target)
    }};
    ($lvl:expr) => {
        log_enabled!(target: log_module_path!(), $lvl)
    };
}

// The log macro above cannot invoke format_args directly because it uses
// local_inner_macros. A format_args invocation there would resolve to
// $crate::format_args which does not exist. Instead invoke format_args here
// outside of local_inner_macros so that it resolves (probably) to
// core::format_args or std::format_args. Same for the several macros that
// follow.
//
// This is a workaround until we drop support for pre-1.30 compilers. At that
// point we can remove use of local_inner_macros, use $crate:: when invoking
// local macros, and invoke format_args directly.
#[doc(hidden)]
#[macro_export]
macro_rules! log_format_args {
    ($($args:tt)*) => {
        format_args!($($args)*)
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! log_module_path {
    () => {
        module_path!()
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! log_file {
    () => {
        file!()
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! log_line {
    () => {
        line!()
    };
}
<commit_msg>Make private helper macro names less likely to conflict<commit_after>// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

/// The standard logging macro.
///
/// This macro will generically log with the specified `Level` and `format!`
/// based argument list.
///
/// # Examples
///
/// ```rust
/// # #[macro_use]
/// # extern crate log;
/// use log::Level;
///
/// # fn main() {
/// let data = (42, "Forty-two");
/// let private_data = "private";
///
/// log!(Level::Error, "Received errors: {}, {}", data.0, data.1);
/// log!(target: "app_events", Level::Warn, "App warning: {}, {}, {}",
///     data.0, data.1, private_data);
/// # }
/// ```
#[macro_export(local_inner_macros)]
macro_rules! log {
    (target: $target:expr, $lvl:expr, $($arg:tt)+) => ({
        let lvl = $lvl;
        if lvl <= $crate::STATIC_MAX_LEVEL && lvl <= $crate::max_level() {
            $crate::__private_api_log(
                __log_format_args!($($arg)+),
                lvl,
                &($target, __log_module_path!(), __log_file!(), __log_line!()),
            );
        }
    });
    ($lvl:expr, $($arg:tt)+) => (log!(target: __log_module_path!(), $lvl, $($arg)+))
}

/// Logs a message at the error level.
///
/// # Examples
///
/// ```rust
/// # #[macro_use]
/// # extern crate log;
/// # fn main() {
/// let (err_info, port) = ("No connection", 22);
///
/// error!("Error: {} on port {}", err_info, port);
/// error!(target: "app_events", "App Error: {}, Port: {}", err_info, 22);
/// # }
/// ```
#[macro_export(local_inner_macros)]
macro_rules! error {
    (target: $target:expr, $($arg:tt)*) => (
        log!(target: $target, $crate::Level::Error, $($arg)*);
    );
    ($($arg:tt)*) => (
        log!($crate::Level::Error, $($arg)*);
    )
}

/// Logs a message at the warn level.
///
/// # Examples
///
/// ```rust
/// # #[macro_use]
/// # extern crate log;
/// # fn main() {
/// let warn_description = "Invalid Input";
///
/// warn!("Warning! {}!", warn_description);
/// warn!(target: "input_events", "App received warning: {}", warn_description);
/// # }
/// ```
#[macro_export(local_inner_macros)]
macro_rules! warn {
    (target: $target:expr, $($arg:tt)*) => (
        log!(target: $target, $crate::Level::Warn, $($arg)*);
    );
    ($($arg:tt)*) => (
        log!($crate::Level::Warn, $($arg)*);
    )
}

/// Logs a message at the info level.
///
/// # Examples
///
/// ```rust
/// # #[macro_use]
/// # extern crate log;
/// # fn main() {
/// # struct Connection { port: u32, speed: f32 }
/// let conn_info = Connection { port: 40, speed: 3.20 };
///
/// info!("Connected to port {} at {} Mb/s", conn_info.port, conn_info.speed);
/// info!(target: "connection_events", "Successfull connection, port: {}, speed: {}",
///       conn_info.port, conn_info.speed);
/// # }
/// ```
#[macro_export(local_inner_macros)]
macro_rules! info {
    (target: $target:expr, $($arg:tt)*) => (
        log!(target: $target, $crate::Level::Info, $($arg)*);
    );
    ($($arg:tt)*) => (
        log!($crate::Level::Info, $($arg)*);
    )
}

/// Logs a message at the debug level.
///
/// # Examples
///
/// ```rust
/// # #[macro_use]
/// # extern crate log;
/// # fn main() {
/// # struct Position { x: f32, y: f32 }
/// let pos = Position { x: 3.234, y: -1.223 };
///
/// debug!("New position: x: {}, y: {}", pos.x, pos.y);
/// debug!(target: "app_events", "New position: x: {}, y: {}", pos.x, pos.y);
/// # }
/// ```
#[macro_export(local_inner_macros)]
macro_rules! debug {
    (target: $target:expr, $($arg:tt)*) => (
        log!(target: $target, $crate::Level::Debug, $($arg)*);
    );
    ($($arg:tt)*) => (
        log!($crate::Level::Debug, $($arg)*);
    )
}

/// Logs a message at the trace level.
///
/// # Examples
///
/// ```rust
/// # #[macro_use]
/// # extern crate log;
/// # fn main() {
/// # struct Position { x: f32, y: f32 }
/// let pos = Position { x: 3.234, y: -1.223 };
///
/// trace!("Position is: x: {}, y: {}", pos.x, pos.y);
/// trace!(target: "app_events", "x is {} and y is {}",
///        if pos.x >= 0.0 { "positive" } else { "negative" },
///        if pos.y >= 0.0 { "positive" } else { "negative" });
/// # }
/// ```
#[macro_export(local_inner_macros)]
macro_rules! trace {
    (target: $target:expr, $($arg:tt)*) => (
        log!(target: $target, $crate::Level::Trace, $($arg)*);
    );
    ($($arg:tt)*) => (
        log!($crate::Level::Trace, $($arg)*);
    )
}

/// Determines if a message logged at the specified level in that module will
/// be logged.
///
/// This can be used to avoid expensive computation of log message arguments if
/// the message would be ignored anyway.
///
/// # Examples
///
/// ```rust
/// # #[macro_use]
/// # extern crate log;
/// use log::Level::Debug;
///
/// # fn foo() {
/// if log_enabled!(Debug) {
///     let data = expensive_call();
///     debug!("expensive debug data: {} {}", data.x, data.y);
/// }
/// if log_enabled!(target: "Global", Debug) {
///    let data = expensive_call();
///    debug!(target: "Global", "expensive debug data: {} {}", data.x, data.y);
/// }
/// # }
/// # struct Data { x: u32, y: u32 }
/// # fn expensive_call() -> Data { Data { x: 0, y: 0 } }
/// # fn main() {}
/// ```
#[macro_export]
macro_rules! log_enabled {
    (target: $target:expr, $lvl:expr) => {{
        let lvl = $lvl;
        lvl <= $crate::STATIC_MAX_LEVEL
            && lvl <= $crate::max_level()
            && $crate::__private_api_enabled(lvl, $target)
    }};
    ($lvl:expr) => {
        log_enabled!(target: __log_module_path!(), $lvl)
    };
}

// The log macro above cannot invoke format_args directly because it uses
// local_inner_macros. A format_args invocation there would resolve to
// $crate::format_args which does not exist. Instead invoke format_args here
// outside of local_inner_macros so that it resolves (probably) to
// core::format_args or std::format_args. Same for the several macros that
// follow.
//
// This is a workaround until we drop support for pre-1.30 compilers. At that
// point we can remove use of local_inner_macros, use $crate:: when invoking
// local macros, and invoke format_args directly.
#[doc(hidden)]
#[macro_export]
macro_rules! __log_format_args {
    ($($args:tt)*) => {
        format_args!($($args)*)
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __log_module_path {
    () => {
        module_path!()
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __log_file {
    () => {
        file!()
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __log_line {
    () => {
        line!()
    };
}
<|endoftext|>