text:
pub use self::EntryFnType::*;
pub use self::CrateType::*;
pub use self::Passes::*;
pub use self::OptLevel::*;
pub use self::OutputType::*;
pub use self::DebugInfoLevel::*;

use session::{early_error, early_warn, Session};
use session::search_paths::SearchPaths;

use rustc_back::target::Target;
use lint;
use metadata::cstore;

use syntax::ast;
use syntax::ast::{IntTy, UintTy};
use syntax::attr;
use syntax::attr::AttrMetaMethods;
use syntax::diagnostic::{ColorConfig, Auto, Always, Never, SpanHandler};
use syntax::parse;
use syntax::parse::token::InternedString;
use syntax::feature_gate::UnstableFeatures;

use getopts;
use std::collections::HashMap;
use std::env;
use std::fmt;
use std::path::PathBuf;

use llvm;

pub struct Config {
    pub target: Target,
    pub int_type: IntTy,
    pub uint_type: UintTy,
}

#[derive(Clone, Copy, PartialEq)]
pub enum OptLevel {
    No, // -O0
    Less, // -O1
    Default, // -O2
    Aggressive // -O3
}

#[derive(Clone, Copy, PartialEq)]
pub enum DebugInfoLevel {
    NoDebugInfo,
    LimitedDebugInfo,
    FullDebugInfo,
}

#[derive(Clone, Copy, PartialEq, PartialOrd, Ord, Eq)]
pub enum OutputType {
    OutputTypeBitcode,
    OutputTypeAssembly,
    OutputTypeLlvmAssembly,
    OutputTypeObject,
    OutputTypeExe,
    OutputTypeDepInfo,
}

#[derive(Clone)]
pub struct Options {
    // The crate config requested for the session, which may be combined
    // with additional crate configurations during the compile process
    pub crate_types: Vec<CrateType>,

    pub gc: bool,
    pub optimize: OptLevel,
    pub debug_assertions: bool,
    pub debuginfo: DebugInfoLevel,
    pub lint_opts: Vec<(String, lint::Level)>,
    pub lint_cap: Option<lint::Level>,
    pub describe_lints: bool,
    pub output_types: Vec<OutputType>,
    // This was mutable for rustpkg, which updates search paths based on the
    // parsed code. It remains mutable in case its replacements wants to use
    // this.
    pub search_paths: SearchPaths,
    pub libs: Vec<(String, cstore::NativeLibraryKind)>,
    pub maybe_sysroot: Option<PathBuf>,
    pub target_triple: String,
    // User-specified cfg meta items. The compiler itself will add additional
    // items to the crate config, and during parsing the entire crate config
    // will be added to the crate AST node.  This should not be used for
    // anything except building the full crate config prior to parsing.
    pub cfg: ast::CrateConfig,
    pub test: bool,
    pub parse_only: bool,
    pub no_trans: bool,
    pub treat_err_as_bug: bool,
    pub no_analysis: bool,
    pub debugging_opts: DebuggingOptions,
    /// Whether to write dependency files. It's (enabled, optional filename).
    pub write_dependency_info: (bool, Option<PathBuf>),
    pub prints: Vec<PrintRequest>,
    pub cg: CodegenOptions,
    pub color: ColorConfig,
    pub show_span: Option<String>,
    pub externs: HashMap<String, Vec<String>>,
    pub crate_name: Option<String>,
    /// An optional name to use as the crate for std during std injection,
    /// written `extern crate std = "name"`. Default to "std". Used by
    /// out-of-tree drivers.
    pub alt_std_name: Option<String>,
    /// Indicates how the compiler should treat unstable features
    pub unstable_features: UnstableFeatures
}

#[derive(Clone, PartialEq, Eq)]
pub enum PrintRequest {
    FileNames,
    Sysroot,
    CrateName,
}

pub enum Input {
    /// Load source from file
    File(PathBuf),
    /// The string is the source
    Str(String)
}

impl Input {
    pub fn filestem(&self) -> String {
        match *self {
            Input::File(ref ifile) => ifile.file_stem().unwrap()
                                           .to_str().unwrap().to_string(),
            Input::Str(_) => "rust_out".to_string(),
        }
    }
}

#[derive(Clone)]
pub struct OutputFilenames {
    pub out_directory: PathBuf,
    pub out_filestem: String,
    pub single_output_file: Option<PathBuf>,
    pub extra: String,
}

impl OutputFilenames {
    pub fn path(&self, flavor: OutputType) -> PathBuf {
        match self.single_output_file {
            Some(ref path) => return path.clone(),
            None => {}
        }
        self.temp_path(flavor)
    }

    pub fn temp_path(&self, flavor: OutputType) -> PathBuf {
        let base = self.out_directory.join(&self.filestem());
        match flavor {
            OutputTypeBitcode => base.with_extension("bc"),
            OutputTypeAssembly => base.with_extension("s"),
            OutputTypeLlvmAssembly => base.with_extension("ll"),
            OutputTypeObject => base.with_extension("o"),
            OutputTypeDepInfo => base.with_extension("d"),
            OutputTypeExe => base,
        }
    }

    pub fn with_extension(&self, extension: &str) -> PathBuf {
        self.out_directory.join(&self.filestem()).with_extension(extension)
    }

    pub fn filestem(&self) -> String {
        format!("{}{}", self.out_filestem, self.extra)
    }
}

pub fn host_triple() -> &'static str {
    // Get the host triple out of the build environment. This ensures that our
    // idea of the host triple is the same as for the set of libraries we've
    // actually built.  We can't just take LLVM's host triple because they
    // normalize all ix86 architectures to i386.
    //
    // Instead of grabbing the host triple (for the current host), we grab (at
    // compile time) the target triple that this rustc is built with and
    // calling that (at runtime) the host triple.
    (option_env!("CFG_COMPILER_HOST_TRIPLE")).
        expect("CFG_COMPILER_HOST_TRIPLE")
}

/// Some reasonable defaults
pub fn basic_options() -> Options {
    Options {
        crate_types: Vec::new(),
        gc: false,
        optimize: No,
        debuginfo: NoDebugInfo,
        lint_opts: Vec::new(),
        lint_cap: None,
        describe_lints: false,
        output_types: Vec::new(),
        search_paths: SearchPaths::new(),
        maybe_sysroot: None,
        target_triple: host_triple().to_string(),
        cfg: Vec::new(),
        test: false,
        parse_only: false,
        no_trans: false,
        treat_err_as_bug: false,
        no_analysis: false,
        debugging_opts: basic_debugging_options(),
        write_dependency_info: (false, None),
        prints: Vec::new(),
        cg: basic_codegen_options(),
        color: Auto,
        show_span: None,
        externs: HashMap::new(),
        crate_name: None,
        alt_std_name: None,
        libs: Vec::new(),
        unstable_features: UnstableFeatures::Disallow,
        debug_assertions: true,
    }
}

// The type of entry function, so
// users can have their own entry
// functions that don't start a
// scheduler
#[derive(Copy, Clone, PartialEq)]
pub enum EntryFnType {
    EntryMain,
    EntryStart,
    EntryNone,
}

#[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug)]
pub enum CrateType {
    CrateTypeExecutable,
    CrateTypeDylib,
    CrateTypeRlib,
    CrateTypeStaticlib,
}

#[derive(Clone)]
pub enum Passes {
    SomePasses(Vec<String>),
    AllPasses,
}

impl Passes {
    pub fn is_empty(&self) -> bool {
        match *self {
            SomePasses(ref v) => v.is_empty(),
            AllPasses => false,
        }
    }
}

/// Declare a macro that will define all CodegenOptions/DebuggingOptions fields and parsers all
/// at once. The goal of this macro is to define an interface that can be
/// programmatically used by the option parser in order to initialize the struct
/// without hardcoding field names all over the place.
///
/// The goal is to invoke this macro once with the correct fields, and then this
/// macro generates all necessary code. The main gotcha of this macro is the
/// cgsetters module which is a bunch of generated code to parse an option into
/// its respective field in the struct. There are a few hand-written parsers for
/// parsing specific types of values in this module.
macro_rules! options {
    ($struct_name:ident, $setter_name:ident, $defaultfn:ident,
     $buildfn:ident, $prefix:expr, $outputname:expr,
     $stat:ident, $mod_desc:ident, $mod_set:ident,
     $($opt:ident : $t:ty = ($init:expr, $parse:ident, $desc:expr)),* ,) =>
(
    #[derive(Clone)]
    pub struct $struct_name { $(pub $opt: $t),* }

    pub fn $defaultfn() -> $struct_name {
        $struct_name { $($opt: $init),* }
    }

    pub fn $buildfn(matches: &getopts::Matches) -> $struct_name
    {
        let mut op = $defaultfn();
        for option in matches.opt_strs($prefix) {
            let mut iter = option.splitn(2, '=');
            let key = iter.next().unwrap();
            let value = iter.next();
            let option_to_lookup = key.replace("-", "_");
            let mut found = false;
            for &(candidate, setter, opt_type_desc, _) in $stat {
                if option_to_lookup != candidate { continue }
                if !setter(&mut op, value) {
                    match (value, opt_type_desc) {
                        (Some(..), None) => {
                            early_error(&format!("{} option `{}` takes no \
                                                 value", $outputname, key))
                        }
                        (None, Some(type_desc)) => {
                            early_error(&format!("{0} option `{1}` requires \
                                                 {2} ({3} {1}=<value>)",
                                                $outputname, key,
                                                type_desc, $prefix))
                        }
                        (Some(value), Some(type_desc)) => {
                            early_error(&format!("incorrect value `{}` for {} \
                                                 option `{}` - {} was expected",
                                                 value, $outputname,
                                                 key, type_desc))
                        }
                        (None, None) => unreachable!()
                    }
                }
                found = true;
                break;
            }
            if !found {
                early_error(&format!("unknown {} option: `{}`",
                                    $outputname, key));
            }
        }
        return op;
    }

    pub type $setter_name = fn(&mut $struct_name, v: Option<&str>) -> bool;
    pub const $stat: &'static [(&'static str, $setter_name,
                                     Option<&'static str>, &'static str)] =
        &[ $( (stringify!($opt), $mod_set::$opt, $mod_desc::$parse, $desc) ),* ];

    #[allow(non_upper_case_globals, dead_code)]
    mod $mod_desc {
        pub const parse_bool: Option<&'static str> = None;
        pub const parse_opt_bool: Option<&'static str> =
            Some("one of: `y`, `yes`, `on`, `n`, `no`, or `off`");
        pub const parse_string: Option<&'static str> = Some("a string");
        pub const parse_opt_string: Option<&'static str> = Some("a string");
        pub const parse_list: Option<&'static str> = Some("a space-separated list of strings");
        pub const parse_opt_list: Option<&'static str> = Some("a space-separated list of strings");
        pub const parse_uint: Option<&'static str> = Some("a number");
        pub const parse_passes: Option<&'static str> =
            Some("a space-separated list of passes, or `all`");
        pub const parse_opt_uint: Option<&'static str> =
            Some("a number");
    }

    #[allow(dead_code)]
    mod $mod_set {
        use super::{$struct_name, Passes, SomePasses, AllPasses};

        $(
            pub fn $opt(cg: &mut $struct_name, v: Option<&str>) -> bool {
                $parse(&mut cg.$opt, v)
            }
        )*

        fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
            match v {
                Some(..) => false,
                None => { *slot = true; true }
            }
        }

        fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
            match v {
                Some(s) => {
                    match s {
                        "n" | "no" | "off" => {
                            *slot = Some(false);
                        }
                        "y" | "yes" | "on" => {
                            *slot = Some(true);
                        }
                        _ => { return false; }
                    }

                    true
                },
                None => { *slot = Some(true); true }
            }
        }

        fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
            match v {
                Some(s) => { *slot = Some(s.to_string()); true },
                None => false,
            }
        }

        fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
            match v {
                Some(s) => { *slot = s.to_string(); true },
                None => false,
            }
        }

        fn parse_list(slot: &mut Vec<String>, v: Option<&str>)
                      -> bool {
            match v {
                Some(s) => {
                    for s in s.split_whitespace() {
                        slot.push(s.to_string());
                    }
                    true
                },
                None => false,
            }
        }

        fn parse_opt_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
                      -> bool {
            match v {
                Some(s) => {
                    let v = s.split_whitespace().map(|s| s.to_string()).collect();
                    *slot = Some(v);
                    true
                },
                None => false,
            }
        }

        fn parse_uint(slot: &mut usize, v: Option<&str>) -> bool {
            match v.and_then(|s| s.parse().ok()) {
                Some(i) => { *slot = i; true },
                None => false
            }
        }

        fn parse_opt_uint(slot: &mut Option<usize>, v: Option<&str>) -> bool {
            match v {
                Some(s) => { *slot = s.parse().ok(); slot.is_some() }
                None => { *slot = None; true }
            }
        }

        fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
            match v {
                Some("all") => {
                    *slot = AllPasses;
                    true
                }
                v => {
                    let mut passes = vec!();
                    if parse_list(&mut passes, v) {
                        *slot = SomePasses(passes);
                        true
                    } else {
                        false
                    }
                }
            }
        }
    }
) }

options! {CodegenOptions, CodegenSetter, basic_codegen_options,
         build_codegen_options, "C", "codegen",
         CG_OPTIONS, cg_type_desc, cgsetters,
    ar: Option<String> = (None, parse_opt_string,
        "tool to assemble archives with"),
    linker: Option<String> = (None, parse_opt_string,
        "system linker to link outputs with"),
    link_args: Option<Vec<String>> = (None, parse_opt_list,
        "extra arguments to pass to the linker (space separated)"),
    lto: bool = (false, parse_bool,
        "perform LLVM link-time optimizations"),
    target_cpu: Option<String> = (None, parse_opt_string,
        "select target processor (llc -mcpu=help for details)"),
    target_feature: String = ("".to_string(), parse_string,
        "target specific attributes (llc -mattr=help for details)"),
    passes: Vec<String> = (Vec::new(), parse_list,
        "a list of extra LLVM passes to run (space separated)"),
    llvm_args: Vec<String> = (Vec::new(), parse_list,
        "a list of arguments to pass to llvm (space separated)"),
    save_temps: bool = (false, parse_bool,
        "save all temporary output files during compilation"),
    rpath: bool = (false, parse_bool,
        "set rpath values in libs/exes"),
    no_prepopulate_passes: bool = (false, parse_bool,
        "don't pre-populate the pass manager with a list of passes"),
    no_vectorize_loops: bool = (false, parse_bool,
        "don't run the loop vectorization optimization passes"),
    no_vectorize_slp: bool = (false, parse_bool,
        "don't run LLVM's SLP vectorization pass"),
    soft_float: bool = (false, parse_bool,
        "generate software floating point library calls"),
    prefer_dynamic: bool = (false, parse_bool,
        "prefer dynamic linking to static linking"),
    no_integrated_as: bool = (false, parse_bool,
        "use an external assembler rather than LLVM's integrated one"),
    no_redzone: Option<bool> = (None, parse_opt_bool,
        "disable the use of the redzone"),
    relocation_model: Option<String> = (None, parse_opt_string,
         "choose the relocation model to use (llc -relocation-model for details)"),
    code_model: Option<String> = (None, parse_opt_string,
         "choose the code model to use (llc -code-model for details)"),
    metadata: Vec<String> = (Vec::new(), parse_list,
         "metadata to mangle symbol names with"),
    extra_filename: String = ("".to_string(), parse_string,
         "extra data to put in each output filename"),
    codegen_units: usize = (1, parse_uint,
        "divide crate into N units to optimize in parallel"),
    remark: Passes = (SomePasses(Vec::new()), parse_passes,
        "print remarks for these optimization passes (space separated, or \"all\")"),
    no_stack_check: bool = (false, parse_bool,
        "disable checks for stack exhaustion (a memory-safety hazard!)"),
    debuginfo: Option<usize> = (None, parse_opt_uint,
        "debug info emission level, 0 = no debug info, 1 = line tables only, \
         2 = full debug info with variable and type information"),
    opt_level: Option<usize> = (None, parse_opt_uint,
        "Optimize with possible levels 0-3"),
    debug_assertions: Option<bool> = (None, parse_opt_bool,
        "explicitly enable the cfg(debug_assertions) directive"),
}

options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
         build_debugging_options, "Z", "debugging",
         DB_OPTIONS, db_type_desc, dbsetters,
    verbose: bool = (false, parse_bool,
        "in general, enable more debug printouts"),
    time_passes: bool = (false, parse_bool,
        "measure time of each rustc pass"),
    count_llvm_insns: bool = (false, parse_bool,
        "count where LLVM instrs originate"),
    time_llvm_passes: bool = (false, parse_bool,
        "measure time of each LLVM pass"),
    trans_stats: bool = (false, parse_bool,
        "gather trans statistics"),
    asm_comments: bool = (false, parse_bool,
        "generate comments into the assembly (may change behavior)"),
    no_verify: bool = (false, parse_bool,
        "skip LLVM verification"),
    borrowck_stats: bool = (false, parse_bool,
        "gather borrowck statistics"),
    no_landing_pads: bool = (false, parse_bool,
        "omit landing pads for unwinding"),
    debug_llvm: bool = (false, parse_bool,
        "enable debug output from LLVM"),
    count_type_sizes: bool = (false, parse_bool,
        "count the sizes of aggregate types"),
    meta_stats: bool = (false, parse_bool,
        "gather metadata statistics"),
    print_link_args: bool = (false, parse_bool,
        "Print the arguments passed to the linker"),
    gc: bool = (false, parse_bool,
        "Garbage collect shared data (experimental)"),
    print_llvm_passes: bool = (false, parse_bool,
        "Prints the llvm optimization passes being run"),
    ast_json: bool = (false, parse_bool,
        "Print the AST as JSON and halt"),
    ast_json_noexpand: bool = (false, parse_bool,
        "Print the pre-expansion AST as JSON and halt"),
    ls: bool = (false, parse_bool,
        "List the symbols defined by a library crate"),
    save_analysis: bool = (false, parse_bool,
        "Write syntax and type analysis information in addition to normal output"),
    print_move_fragments: bool = (false, parse_bool,
        "Print out move-fragment data for every fn"),
    flowgraph_print_loans: bool = (false, parse_bool,
        "Include loan analysis data in --pretty flowgraph output"),
    flowgraph_print_moves: bool = (false, parse_bool,
        "Include move analysis data in --pretty flowgraph output"),
    flowgraph_print_assigns: bool = (false, parse_bool,
        "Include assignment analysis data in --pretty flowgraph output"),
    flowgraph_print_all: bool = (false, parse_bool,
        "Include all dataflow analysis data in --pretty flowgraph output"),
    print_region_graph: bool = (false, parse_bool,
         "Prints region inference graph. \
          Use with RUST_REGION_GRAPH=help for more info"),
    parse_only: bool = (false, parse_bool,
          "Parse only; do not compile, assemble, or link"),
    no_trans: bool = (false, parse_bool,
          "Run all passes except translation; no output"),
    treat_err_as_bug: bool = (false, parse_bool,
          "Treat all errors that occur as bugs"),
    no_analysis: bool = (false, parse_bool,
          "Parse and expand the source, but run no analysis"),
    extra_plugins: Vec<String> = (Vec::new(), parse_list,
        "load extra plugins"),
    unstable_options: bool = (false, parse_bool,
          "Adds unstable command line options to rustc interface"),
    print_enum_sizes: bool = (false, parse_bool,
          "Print the size of enums and their variants"),
    force_overflow_checks: Option<bool> = (None, parse_opt_bool,
          "Force overflow checks on or off"),
    force_dropflag_checks: Option<bool> = (None, parse_opt_bool,
          "Force drop flag checks on or off"),
    trace_macros: bool = (false, parse_bool,
          "For every macro invocation, print its name and arguments"),
    disable_nonzeroing_move_hints: bool = (false, parse_bool,
          "Force nonzeroing move optimization off"),
}

pub fn default_lib_output() -> CrateType {
    CrateTypeRlib
}

pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
    use syntax::parse::token::intern_and_get_ident as intern;

    let end = &sess.target.target.target_endian;
    let arch = &sess.target.target.arch;
    let wordsz = &sess.target.target.target_pointer_width;
    let os = &sess.target.target.target_os;
    let env = &sess.target.target.target_env;

    let fam = match sess.target.target.options.is_like_windows {
        true  => InternedString::new("windows"),
        false => InternedString::new("unix")
    };

    let mk = attr::mk_name_value_item_str;
    let mut ret = vec![ // Target bindings.
         attr::mk_word_item(fam.clone()),
         mk(InternedString::new("target_os"), intern(os)),
         mk(InternedString::new("target_family"), fam),
         mk(InternedString::new("target_arch"), intern(arch)),
         mk(InternedString::new("target_endian"), intern(end)),
         mk(InternedString::new("target_pointer_width"), intern(wordsz)),
         mk(InternedString::new("target_env"), intern(env)),
    ];
    if sess.opts.debug_assertions {
        ret.push(attr::mk_word_item(InternedString::new("debug_assertions")));
    }
    return ret;
}

pub fn append_configuration(cfg: &mut ast::CrateConfig,
                            name: InternedString) {
    if !cfg.iter().any(|mi| mi.name() == name) {
        cfg.push(attr::mk_word_item(name))
    }
}

pub fn build_configuration(sess: &Session) -> ast::CrateConfig {
    // Combine the configuration requested by the session (command line) with
    // some default and generated configuration items
    let default_cfg = default_configuration(sess);
    let mut user_cfg = sess.opts.cfg.clone();
    // If the user wants a test runner, then add the test cfg
    if sess.opts.test {
        append_configuration(&mut user_cfg, InternedString::new("test"))
    }
    let mut v = user_cfg.into_iter().collect::<Vec<_>>();
    v.push_all(&default_cfg[..]);
    v
}

pub fn build_target_config(opts: &Options, sp: &SpanHandler) -> Config {
    let target = match Target::search(&opts.target_triple) {
        Ok(t) => t,
        Err(e) => {
            sp.handler().fatal(&format!("Error loading target specification: {}", e));
        }
    };

    let (int_type, uint_type) = match &target.target_pointer_width[..] {
        "32" => (ast::TyI32, ast::TyU32),
        "64" => (ast::TyI64, ast::TyU64),
        w    => sp.handler().fatal(&format!("target specification was invalid: unrecognized \
                                             target-pointer-width {}", w))
    };

    Config {
        target: target,
        int_type: int_type,
        uint_type: uint_type,
    }
}

/// Returns the "short" subset of the stable rustc command line options.
pub fn short_optgroups() -> Vec<getopts::OptGroup> {
    rustc_short_optgroups().into_iter()
        .filter(|g|g.is_stable())
        .map(|g|g.opt_group)
        .collect()
}

/// Returns all of the stable rustc command line options.
pub fn optgroups() -> Vec<getopts::OptGroup> {
    rustc_optgroups().into_iter()
        .filter(|g|g.is_stable())
        .map(|g|g.opt_group)
        .collect()
}

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum OptionStability { Stable, Unstable }

#[derive(Clone, PartialEq, Eq)]
pub struct RustcOptGroup {
    pub opt_group: getopts::OptGroup,
    pub stability: OptionStability,
}

impl RustcOptGroup {
    pub fn is_stable(&self) -> bool {
        self.stability == OptionStability::Stable
    }

    fn stable(g: getopts::OptGroup) -> RustcOptGroup {
        RustcOptGroup { opt_group: g, stability: OptionStability::Stable }
    }

    fn unstable(g: getopts::OptGroup) -> RustcOptGroup {
        RustcOptGroup { opt_group: g, stability: OptionStability::Unstable }
    }
}

// The `opt` local module holds wrappers around the `getopts` API that
// adds extra rustc-specific metadata to each option; such metadata
// is exposed by .  The public
// functions below ending with `_u` are the functions that return
// *unstable* options, i.e. options that are only enabled when the
// user also passes the `-Z unstable-options` debugging flag.
mod opt {
    // The `fn opt_u` etc below are written so that we can use them
    // in the future; do not warn about them not being used right now.
    #![allow(dead_code)]

    use getopts;
    use super::RustcOptGroup;

    pub type R = RustcOptGroup;
    pub type S<'a> = &'a str;

    fn stable(g: getopts::OptGroup) -> R { RustcOptGroup::stable(g) }
    fn unstable(g: getopts::OptGroup) -> R { RustcOptGroup::unstable(g) }

    // FIXME (pnkfelix): We default to stable since the current set of
    // options is defacto stable.  However, it would be good to revise the
    // code so that a stable option is the thing that takes extra effort
    // to encode.

    pub fn     opt(a: S, b: S, c: S, d: S) -> R { stable(getopts::optopt(a, b, c, d)) }
    pub fn   multi(a: S, b: S, c: S, d: S) -> R { stable(getopts::optmulti(a, b, c, d)) }
    pub fn    flag(a: S, b: S, c: S)       -> R { stable(getopts::optflag(a, b, c)) }
    pub fn flagopt(a: S, b: S, c: S, d: S) -> R { stable(getopts::optflagopt(a, b, c, d)) }
    pub fn flagmulti(a: S, b: S, c: S)     -> R { stable(getopts::optflagmulti(a, b, c)) }

    pub fn     opt_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optopt(a, b, c, d)) }
    pub fn   multi_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optmulti(a, b, c, d)) }
    pub fn    flag_u(a: S, b: S, c: S)       -> R { unstable(getopts::optflag(a, b, c)) }
    pub fn flagopt_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optflagopt(a, b, c, d)) }
    pub fn flagmulti_u(a: S, b: S, c: S)     -> R { unstable(getopts::optflagmulti(a, b, c)) }
}

/// Returns the "short" subset of the rustc command line options,
/// including metadata for each option, such as whether the option is
/// part of the stable long-term interface for rustc.
pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
    vec![
        opt::flag("h", "help", "Display this message"),
        opt::multi("", "cfg", "Configure the compilation environment", "SPEC"),
        opt::multi("L", "",   "Add a directory to the library search path",
                   "[KIND=]PATH"),
        opt::multi("l", "",   "Link the generated crate(s) to the specified native
                             library NAME. The optional KIND can be one of,
                             static, dylib, or framework. If omitted, dylib is
                             assumed.", "[KIND=]NAME"),
        opt::multi("", "crate-type", "Comma separated list of types of crates
                                    for the compiler to emit",
                   "[bin|lib|rlib|dylib|staticlib]"),
        opt::opt("", "crate-name", "Specify the name of the crate being built",
               "NAME"),
        opt::multi("", "emit", "Comma separated list of types of output for \
                              the compiler to emit",
                 "[asm|llvm-bc|llvm-ir|obj|link|dep-info]"),
        opt::multi("", "print", "Comma separated list of compiler information to \
                               print on stdout",
                 "[crate-name|file-names|sysroot]"),
        opt::flagmulti("g",  "",  "Equivalent to -C debuginfo=2"),
        opt::flagmulti("O", "", "Equivalent to -C opt-level=2"),
        opt::opt("o", "", "Write output to <filename>", "FILENAME"),
        opt::opt("",  "out-dir", "Write output to compiler-chosen filename \
                                in <dir>", "DIR"),
        opt::opt("", "explain", "Provide a detailed explanation of an error \
                               message", "OPT"),
        opt::flag("", "test", "Build a test harness"),
        opt::opt("", "target", "Target triple cpu-manufacturer-kernel[-os] \
                              to compile for (see chapter 3.4 of \
                              http://www.sourceware.org/autobook/
                              for details)",
               "TRIPLE"),
        opt::multi("W", "warn", "Set lint warnings", "OPT"),
        opt::multi("A", "allow", "Set lint allowed", "OPT"),
        opt::multi("D", "deny", "Set lint denied", "OPT"),
        opt::multi("F", "forbid", "Set lint forbidden", "OPT"),
        opt::multi("", "cap-lints", "Set the most restrictive lint level. \
                                     More restrictive lints are capped at this \
                                     level", "LEVEL"),
        opt::multi("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
        opt::flag("V", "version", "Print version info and exit"),
        opt::flag("v", "verbose", "Use verbose output"),
    ]
}

/// Returns all rustc command line options, including metadata for
/// each option, such as whether the option is part of the stable
/// long-term interface for rustc.
pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
    let mut opts = rustc_short_optgroups();
    opts.push_all(&[
        opt::multi("", "extern", "Specify where an external rust library is \
                                located",
                 "NAME=PATH"),
        opt::opt("", "sysroot", "Override the system root", "PATH"),
        opt::multi("Z", "", "Set internal debugging options", "FLAG"),
        opt::opt("", "color", "Configure coloring of output:
            auto   = colorize, if output goes to a tty (default);
            always = always colorize output;
            never  = never colorize output", "auto|always|never"),

        opt::flagopt_u("", "pretty",
                   "Pretty-print the input instead of compiling;
                   valid types are: `normal` (un-annotated source),
                   `expanded` (crates expanded),
                   `typed` (crates expanded, with type annotations), or
                   `expanded,identified` (fully parenthesized, AST nodes with IDs).",
                 "TYPE"),
        opt::flagopt_u("", "unpretty",
                     "Present the input source, unstable (and less-pretty) variants;
                      valid types are any of the types for `--pretty`, as well as:
                      `flowgraph=<nodeid>` (graphviz formatted flowgraph for node), or
                      `everybody_loops` (all function bodies replaced with `loop {}`).",
                     "TYPE"),
        opt::opt_u("", "show-span", "Show spans for compiler debugging", "expr|pat|ty"),
    ]);
    opts
}

// Convert strings provided as --cfg [cfgspec] into a crate_cfg
pub fn parse_cfgspecs(cfgspecs: Vec<String> ) -> ast::CrateConfig {
    cfgspecs.into_iter().map(|s| {
        parse::parse_meta_from_source_str("cfgspec".to_string(),
                                          s.to_string(),
                                          Vec::new(),
                                          &parse::ParseSess::new())
    }).collect::<ast::CrateConfig>()
}

pub fn build_session_options(matches: &getopts::Matches) -> Options {
    let unparsed_crate_types = matches.opt_strs("crate-type");
    let crate_types = parse_crate_types_from_list(unparsed_crate_types)
        .unwrap_or_else(|e| early_error(&e[..]));

    let mut lint_opts = vec!();
    let mut describe_lints = false;

    for &level in &[lint::Allow, lint::Warn, lint::Deny, lint::Forbid] {
        for lint_name in matches.opt_strs(level.as_str()) {
            if lint_name == "help" {
                describe_lints = true;
            } else {
                lint_opts.push((lint_name.replace("-", "_"), level));
            }
        }
    }

    let lint_cap = matches.opt_str("cap-lints").map(|cap| {
        lint::Level::from_str(&cap).unwrap_or_else(|| {
            early_error(&format!("unknown lint level: `{}`", cap))
        })
    });

    let debugging_opts = build_debugging_options(matches);

    let parse_only = debugging_opts.parse_only;
    let no_trans = debugging_opts.no_trans;
    let treat_err_as_bug = debugging_opts.treat_err_as_bug;
    let no_analysis = debugging_opts.no_analysis;

    if debugging_opts.debug_llvm {
        unsafe { llvm::LLVMSetDebug(1); }
    }

    let mut output_types = Vec::new();
    if !debugging_opts.parse_only && !no_trans {
        let unparsed_output_types = matches.opt_strs("emit");
        for unparsed_output_type in &unparsed_output_types {
            for part in unparsed_output_type.split(',') {
                let output_type = match part {
                    "asm" => OutputTypeAssembly,
                    "llvm-ir" => OutputTypeLlvmAssembly,
                    "llvm-bc" => OutputTypeBitcode,
                    "obj" => OutputTypeObject,
                    "link" => OutputTypeExe,
                    "dep-info" => OutputTypeDepInfo,
                    _ => {
                        early_error(&format!("unknown emission type: `{}`",
                                            part))
                    }
                };
                output_types.push(output_type)
            }
        }
    };
    output_types.sort();
    output_types.dedup();
    if output_types.is_empty() {
        output_types.push(OutputTypeExe);
    }

    let cg = build_codegen_options(matches);

    let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m));
    let target = matches.opt_str("target").unwrap_or(
        host_triple().to_string());
    let opt_level = {
        if matches.opt_present("O") {
            if cg.opt_level.is_some() {
                early_error("-O and -C opt-level both provided");
            }
            Default
        } else {
            match cg.opt_level {
                None => No,
                Some(0) => No,
                Some(1) => Less,
                Some(2) => Default,
                Some(3) => Aggressive,
                Some(arg) => {
                    early_error(&format!("optimization level needs to be \
                                          between 0-3 (instead was `{}`)",
                                         arg));
                }
            }
        }
    };
    let debug_assertions = cg.debug_assertions.unwrap_or(opt_level == No);
    let gc = debugging_opts.gc;
    let debuginfo = if matches.opt_present("g") {
        if cg.debuginfo.is_some() {
            early_error("-g and -C debuginfo both provided");
        }
        FullDebugInfo
    } else {
        match cg.debuginfo {
            None | Some(0) => NoDebugInfo,
            Some(1) => LimitedDebugInfo,
            Some(2) => FullDebugInfo,
            Some(arg) => {
                early_error(&format!("debug info level needs to be between \
                                      0-2 (instead was `{}`)",
                                     arg));
            }
        }
    };

    let mut search_paths = SearchPaths::new();
    for s in &matches.opt_strs("L") {
        search_paths.add_path(&s[..]);
    }

    let libs = matches.opt_strs("l").into_iter().map(|s| {
        let mut parts = s.splitn(2, '=');
        let kind = parts.next().unwrap();
        let (name, kind) = match (parts.next(), kind) {
            (None, name) |
            (Some(name), "dylib") => (name, cstore::NativeUnknown),
            (Some(name), "framework") => (name, cstore::NativeFramework),
            (Some(name), "static") => (name, cstore::NativeStatic),
            (_, s) => {
                early_error(&format!("unknown library kind `{}`, expected \
                                     one of dylib, framework, or static",
                                    s));
            }
        };
        (name.to_string(), kind)
    }).collect();

    let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
    let test = matches.opt_present("test");
    let write_dependency_info = (output_types.contains(&OutputTypeDepInfo), None);

    let prints = matches.opt_strs("print").into_iter().map(|s| {
        match &*s {
            "crate-name" => PrintRequest::CrateName,
            "file-names" => PrintRequest::FileNames,
            "sysroot" => PrintRequest::Sysroot,
            req => {
                early_error(&format!("unknown print request `{}`", req))
            }
        }
    }).collect::<Vec<_>>();

    if !cg.remark.is_empty() && debuginfo == NoDebugInfo {
        early_warn("-C remark will not show source locations without \
                    --debuginfo");
    }

    let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
        Some("auto")   => Auto,
        Some("always") => Always,
        Some("never")  => Never,

        None => Auto,

        Some(arg) => {
            early_error(&format!("argument for --color must be auto, always \
                                 or never (instead was `{}`)",
                                arg))
        }
    };

    let mut externs = HashMap::new();
    for arg in &matches.opt_strs("extern") {
        let mut parts = arg.splitn(2, '=');
        let name = match parts.next() {
            Some(s) => s,
            None => early_error("--extern value must not be empty"),
        };
        let location = match parts.next() {
            Some(s) => s,
            None => early_error("--extern value must be of the format `foo=bar`"),
        };

        externs.entry(name.to_string()).or_insert(vec![]).push(location.to_string());
    }

    let crate_name = matches.opt_str("crate-name");

    Options {
        crate_types: crate_types,
        gc: gc,
        optimize: opt_level,
        debuginfo: debuginfo,
        lint_opts: lint_opts,
        lint_cap: lint_cap,
        describe_lints: describe_lints,
        output_types: output_types,
        search_paths: search_paths,
        maybe_sysroot: sysroot_opt,
        target_triple: target,
        cfg: cfg,
        test: test,
        parse_only: parse_only,
        no_trans: no_trans,
        treat_err_as_bug: treat_err_as_bug,
        no_analysis: no_analysis,
        debugging_opts: debugging_opts,
        write_dependency_info: write_dependency_info,
        prints: prints,
        cg: cg,
        color: color,
        show_span: None,
        externs: externs,
        crate_name: crate_name,
        alt_std_name: None,
        libs: libs,
        unstable_features: get_unstable_features_setting(),
        debug_assertions: debug_assertions,
    }
}

pub fn get_unstable_features_setting() -> UnstableFeatures {
    // Whether this is a feature-staged build, i.e. on the beta or stable channel
    let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
    // The secret key needed to get through the rustc build itself by
    // subverting the unstable features lints
    let bootstrap_secret_key = option_env!("CFG_BOOTSTRAP_KEY");
    // The matching key to the above, only known by the build system
    let bootstrap_provided_key = env::var("RUSTC_BOOTSTRAP_KEY").ok();
    match (disable_unstable_features, bootstrap_secret_key, bootstrap_provided_key) {
        (_, Some(ref s), Some(ref p)) if s == p => UnstableFeatures::Cheat,
        (true, _, _) => UnstableFeatures::Disallow,
        (false, _, _) => UnstableFeatures::Allow
    }
}

pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> {

    let mut crate_types: Vec<CrateType> = Vec::new();
    for unparsed_crate_type in &list_list {
        for part in unparsed_crate_type.split(',') {
            let new_part = match part {
                "lib"       => default_lib_output(),
                "rlib"      => CrateTypeRlib,
                "staticlib" => CrateTypeStaticlib,
                "dylib"     => CrateTypeDylib,
                "bin"       => CrateTypeExecutable,
                _ => {
                    return Err(format!("unknown crate type: `{}`",
                                       part));
                }
            };
            if !crate_types.contains(&new_part) {
                crate_types.push(new_part)
            }
        }
    }

    return Ok(crate_types);
}

impl fmt::Display for CrateType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            CrateTypeExecutable => "bin".fmt(f),
            CrateTypeDylib => "dylib".fmt(f),
            CrateTypeRlib => "rlib".fmt(f),
            CrateTypeStaticlib => "staticlib".fmt(f)
        }
    }
}

#[cfg(test)]
mod tests {

    use session::config::{build_configuration, optgroups, build_session_options};
    use session::build_session;

    use getopts::getopts;
    use syntax::attr;
    use syntax::attr::AttrMetaMethods;
    use syntax::diagnostics;

    // When the user supplies --test we should implicitly supply --cfg test
    #[test]
    fn test_switch_implies_cfg_test() {
        let matches =
            &match getopts(&["--test".to_string()], &optgroups()) {
              Ok(m) => m,
              Err(f) => panic!("test_switch_implies_cfg_test: {}", f)
            };
        let registry = diagnostics::registry::Registry::new(&[]);
        let sessopts = build_session_options(matches);
        let sess = build_session(sessopts, None, registry);
        let cfg = build_configuration(&sess);
        assert!((attr::contains_name(&cfg[..], "test")));
    }

    // When the user supplies --test and --cfg test, don't implicitly add
    // another --cfg test
    #[test]
    fn test_switch_implies_cfg_test_unless_cfg_test() {
        let matches =
            &match getopts(&["--test".to_string(), "--cfg=test".to_string()],
                           &optgroups()) {
              Ok(m) => m,
              Err(f) => {
                panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f)
              }
            };
        let registry = diagnostics::registry::Registry::new(&[]);
        let sessopts = build_session_options(matches);
        let sess = build_session(sessopts, None, registry);
        let cfg = build_configuration(&sess);
        let mut test_items = cfg.iter().filter(|m| m.name() == "test");
        assert!(test_items.next().is_some());
        assert!(test_items.next().is_none());
    }

    #[test]
    fn test_can_print_warnings() {
        {
            let matches = getopts(&[
                "-Awarnings".to_string()
            ], &optgroups()).unwrap();
            let registry = diagnostics::registry::Registry::new(&[]);
            let sessopts = build_session_options(&matches);
            let sess = build_session(sessopts, None, registry);
            assert!(!sess.can_print_warnings);
        }

        {
            let matches = getopts(&[
                "-Awarnings".to_string(),
                "-Dwarnings".to_string()
            ], &optgroups()).unwrap();
            let registry = diagnostics::registry::Registry::new(&[]);
            let sessopts = build_session_options(&matches);
            let sess = build_session(sessopts, None, registry);
            assert!(sess.can_print_warnings);
        }

        {
            let matches = getopts(&[
                "-Adead_code".to_string()
            ], &optgroups()).unwrap();
            let registry = diagnostics::registry::Registry::new(&[]);
            let sessopts = build_session_options(&matches);
            let sess = build_session(sessopts, None, registry);
            assert!(sess.can_print_warnings);
        }
    }
}


text:
namespace content {

// Exposes methods for creating FileSystemAccessEntries. All these methods need
// to be called on the UI thread.
class CONTENT_EXPORT FileSystemAccessEntryFactory
    : public base::RefCountedThreadSafe<FileSystemAccessEntryFactory,
                                        BrowserThread::DeleteOnUIThread> {
 public:
  using UserAction = FileSystemAccessPermissionContext::UserAction;
  using PathType = FileSystemAccessPermissionContext::PathType;

  // Context from which a created handle is going to be used. This is used for
  // security and permission checks. Pass in the URL most relevant as the url
  // parameter. This url will be used for verifications later for SafeBrowsing
  // and Quarantine Service if used for writes.
  struct CONTENT_EXPORT BindingContext {
    BindingContext(const blink::StorageKey& storage_key,
                   const GURL& url,
                   GlobalRenderFrameHostId frame_id)
        : storage_key(storage_key), url(url), frame_id(frame_id) {}
    BindingContext(const blink::StorageKey& storage_key,
                   const GURL& url,
                   int worker_process_id)
        : storage_key(storage_key),
          url(url),
          frame_id(worker_process_id, MSG_ROUTING_NONE) {}
    blink::StorageKey storage_key;
    GURL url;
    GlobalRenderFrameHostId frame_id;
    bool is_worker() const { return !frame_id; }
    int process_id() const { return frame_id.child_id; }
  };

  // Creates a new FileSystemAccessEntryPtr from the path to a file. Assumes the
  // passed in path is valid and represents a file.
  virtual blink::mojom::FileSystemAccessEntryPtr CreateFileEntryFromPath(
      const BindingContext& binding_context,
      PathType path_type,
      const base::FilePath& file_path,
      UserAction user_action) = 0;

  // Creates a new FileSystemAccessEntryPtr from the path to a directory.
  // Assumes the passed in path is valid and represents a directory.
  virtual blink::mojom::FileSystemAccessEntryPtr CreateDirectoryEntryFromPath(
      const BindingContext& binding_context,
      PathType path_type,
      const base::FilePath& directory_path,
      UserAction user_action) = 0;

  // Resolve a FileSystemAccessTransferToken to its FileSystemURL. Invokes the
  // callback with a absl::nullopt if the token isn't valid or can't be found
  // (e.g. a compromised renderer crafts an invalid token).
  using ResolveTransferTokenCallback =
      base::OnceCallback<void(absl::optional<storage::FileSystemURL>)>;
  virtual void ResolveTransferToken(
      mojo::PendingRemote<blink::mojom::FileSystemAccessTransferToken>
          transfer_token,
      ResolveTransferTokenCallback callback) = 0;

 protected:
  friend struct BrowserThread::DeleteOnThread<BrowserThread::UI>;
  friend class base::DeleteHelper<FileSystemAccessEntryFactory>;
  virtual ~FileSystemAccessEntryFactory() {}
};

}  // namespace content

#endif  // CONTENT_PUBLIC_BROWSER_FILE_SYSTEM_ACCESS_ENTRY_FACTORY_H_

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"fmt"
	"os"
	"io/ioutil"
	cyhcrypto "cyh/crypto"
	"crypto/ecdsa"
	"crypto/rand"
	"crypto/sha256"
	"crypto/elliptic"
)

func main () {
	prv_filename := "./ec_p256.prv"
	pub_filename := "./ec_p256.pub"
	createNewKeyPair(prv_filename, pub_filename)

	msg := []byte("hogehoge")
	signature := sign(prv_filename, msg)

	result_ok := verify(pub_filename, msg, signature)
	fmt.Println(result_ok)

	msg_ng := []byte("hogehog")
	result_ng := verify(pub_filename, msg_ng, signature)
	fmt.Println(result_ng)
}

func createNewKeyPair(prv_filename string, pub_filename string) {
	// generate and save ecdsa private key.
	new_ecprv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	new_ecprv_pem, err := cyhcrypto.CreateECPrivateKeyPEM(new_ecprv)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	err = ioutil.WriteFile(prv_filename, new_ecprv_pem, 0600)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// save ecdsa public key.
	new_ecpub_pem, err := cyhcrypto.CreateECPublicKeyPEM(&new_ecprv.PublicKey)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	err = ioutil.WriteFile(pub_filename, new_ecpub_pem, 0600)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func sign(prv_key_filename string, msg []byte) []byte {
	// load ecdsa private key from file
	prv_data, err := ioutil.ReadFile(prv_key_filename)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	ecprv, err := cyhcrypto.LoadECPrivateKey(prv_data)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// sign to message
	msg_hasher := sha256.New()
	_, _ = msg_hasher.Write(msg)
	hashed := msg_hasher.Sum(nil)
	r, s, err := ecdsa.Sign(rand.Reader, ecprv, hashed)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	signature, err := cyhcrypto.EncodeSignature(r, s)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	return signature
}

func verify(pub_key_filename string, msg []byte, signature []byte) bool {
	// load ecdsa public key from file
	pub_data, err := ioutil.ReadFile(pub_key_filename)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	ecpub, err := cyhcrypto.LoadECPublicKey(pub_data)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// verify signature
	v_msg_hasher := sha256.New()
	_, _ = v_msg_hasher.Write(msg)
	v_hashed := v_msg_hasher.Sum(nil)

	sig_r, sig_s, err := cyhcrypto.DecodeSignature(signature)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	result := ecdsa.Verify(ecpub, v_hashed, sig_r, sig_s)

	return result
}


text:
<?php

declare(strict_types=1);

namespace OAuth2Framework\Component\Server\Tests\Stub;

use Jose\Checker\SubjectChecker as Base;

final class SubjectChecker extends Base
{
    /**
     * {@inheritdoc}
     */
    protected function isSubjectAllowed($subject): bool
    {
        return in_array($subject, ['SUB1', 'SUB2']);
    }
}


text:
package com.linecorp.armeria.server;

import static java.util.Objects.requireNonNull;

import com.linecorp.armeria.common.RpcRequest;
import com.linecorp.armeria.common.RpcResponse;

/**
 * A decorating {@link RpcService} which implements its {@link #serve(ServiceRequestContext, RpcRequest)}
 * method using a given function.
 *
 * @see RpcService#decorate(DecoratingRpcServiceFunction)
 */
final class FunctionalDecoratingRpcService extends SimpleDecoratingRpcService {

    private final DecoratingRpcServiceFunction function;

    /**
     * Creates a new instance with the specified function.
     */
    FunctionalDecoratingRpcService(RpcService delegate, DecoratingRpcServiceFunction function) {
        super(delegate);
        this.function = requireNonNull(function, "function");
    }

    @Override
    public RpcResponse serve(ServiceRequestContext ctx, RpcRequest req) throws Exception {
        return function.serve((RpcService) unwrap(), ctx, req);
    }

    @Override
    public String toString() {
        return FunctionalDecoratingRpcService.class.getSimpleName() + '(' + unwrap() + ", " + function + ')';
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<citations>
	<bibl><title level="j">Bioorganic & Medicinal Chemistry Letters</title> <biblScope type="vol">23</biblScope> (<date>2013</date>) <biblScope type="pp">1588–1591</biblScope></bibl>
</citations>


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.blogspot.na5cent.connectdb.query;

import com.blogspot.na5cent.connectdb.C3DBConfig;
import com.blogspot.na5cent.connectdb.util.ClassUtils;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 *
 * @author anonymous
 */
public class Procedures {

    private final String sqlCode;
    private final List<ParameterHolder> params;

    private static final Map<Class, Integer> typeMapping = new HashMap<>();

    static {
        typeMapping.put(String.class, java.sql.Types.VARCHAR);
        typeMapping.put(Integer.class, java.sql.Types.INTEGER);
        typeMapping.put(Double.class, java.sql.Types.DOUBLE);
        typeMapping.put(Date.class, java.sql.Types.DATE);
        typeMapping.put(Boolean.class, java.sql.Types.BOOLEAN);
    }

    private Procedures(String sqlCode) {
        this.sqlCode = sqlCode;
        params = new LinkedList<>();
    }

    public static Procedures call(String sqlCode) {
        return new Procedures(sqlCode);
    }

    public Procedures withParam(Object value) {
        params.add(new ParameterHolder(
                ParameterType.IN,
                value,
                null
        ));

        return this;
    }

    public Procedures withOutput(OutputCallback callback) {
        params.add(new ParameterHolder(
                ParameterType.OUT,
                null,
                callback
        ));

        return this;
    }

    private void setParameters(CallableStatement statement) throws Exception {
        for (int i = 0; i < params.size(); i++) {
            ParameterHolder holder = params.get(i);
            if (holder.getType() == ParameterType.IN) {
                statement.setObject(i + 1, holder.getValue());
            } else {
                Integer sqlType = holder.getSqlType();
                if (sqlType != null) {
                    statement.registerOutParameter(i + 1, sqlType);
                }
            }
        }
    }

    private void returnValue2Callback(CallableStatement statement) throws Exception {
        for (int i = 0; i < params.size(); i++) {
            ParameterHolder holder = params.get(i);
            if (holder.getType() == ParameterType.OUT && holder.callback != null) {
                holder.callback.output(statement.getObject(i + 1));
            }
        }
    }

    private void registerOutputParameter(CallableStatement statement, Class clazz) throws Exception {
        Integer sqlType = typeMapping.get(clazz);
        if (sqlType != null) {
            params.add(0, new ParameterHolder(ParameterType.OUT, null, null));
            statement.registerOutParameter(1, sqlType);
            setParameters(statement);
        }
    }

    private CallableStatement createStatement(Connection connection, Class clazz) throws Exception {
        String returnValue = clazz == null ? "" : "? := ";
        CallableStatement statement = connection.prepareCall("{ call " + returnValue + sqlCode + " }");
        if (clazz == null) {
            setParameters(statement);
        } else {
            registerOutputParameter(statement, clazz);
        }

        return statement;
    }

    private Object returnValue(CallableStatement statement, Class clazz) throws Exception {
        if (clazz == null) {
            returnValue2Callback(statement);
            return null;
        } else {
            return statement.getObject(1);
        }
    }

    private Connection getConnection() throws SQLException {
        return DriverManager.getConnection(
                C3DBConfig.getUrl(),
                C3DBConfig.getUsername(),
                C3DBConfig.getPassword()
        );
    }

    public <T> T execute(Class<T> clazz) throws Exception {
        Class.forName(C3DBConfig.getDriver());

        T value = null;

        Connection connection = null;
        CallableStatement statement = null;
        try {
            connection = getConnection();
            statement = createStatement(connection, clazz);
            statement.execute();

            value = (T) returnValue(statement, clazz);
        } finally {
            if (statement != null) {
                statement.close();
            }

            if (connection != null) {
                connection.close();
            }
        }

        return value;
    }

    public void execute() throws Exception {
        execute(null);
    }

    private static class ParameterHolder {

        private final ParameterType type;
        private final Object value;
        private final OutputCallback callback;

        public ParameterHolder(ParameterType type, Object value, OutputCallback callback) {
            this.type = type;
            this.value = value;
            this.callback = callback;
        }

        public ParameterType getType() {
            return type;
        }

        public Object getValue() {
            return value;
        }

        public OutputCallback getOutputCallback() {
            return callback;
        }

        public Integer getSqlType() throws Exception {
            if (callback == null) {
                return null;
            }

            Class clazz = ClassUtils.findMethod(
                    callback.getClass(),
                    "output"
            ).getParameterTypes()[0];

            return typeMapping.get(clazz);
        }
    }

    private static enum ParameterType {

        IN, OUT
    }
}


text:
generic background image — for text/image replacement and/or presentational (non-content) images — and icon styling

## About

## How to use it

## File size

- ≅ kb (gzipped)
- ≅ kb (unzipped)


text:
let textbox = document.getElementById("myText");
textbox.addEventListener("textInput", (event) => {
  console.log(event.data);
});


text:
@interface LGSemiModalNavViewController ()

@end

@implementation LGSemiModalNavViewController

#pragma mark - Life

- (void)loadView{
    [super loadView];

    self.extendedLayoutIncludesOpaqueBars = NO;
    self.view.clipsToBounds = YES;
    self.transitioningDelegate = self;
    self.modalPresentationStyle = UIModalPresentationCustom;
    [self defaults];
}

-(void)defaults{
    _tapDismissEnabled = YES;
    _animationSpeed = 0.35f;
    _backgroundShadeColor = [UIColor blackColor];
    _scaleTransform = CGAffineTransformMakeScale(.94, .94);
    _springDamping = 0.88;
    _springVelocity = 14;
    _backgroundShadeAlpha = 0.4;
}

#pragma mark - Actions

- (void)dismissWasTapped{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UIViewControllerTransitioningDelegate Methods

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented
                                                                  presentingController:(UIViewController *)presenting
                                                                      sourceController:(UIViewController *)source {
    return [self transitionPresenting:YES];
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed {
    return [self transitionPresenting:NO];
}

-(LGSemiModalTransition*)transitionPresenting:(BOOL)presenting{
    LGSemiModalTransition *animator = [LGSemiModalTransition new];
    animator.presenting = presenting;
    animator.tapDismissEnabled = _tapDismissEnabled;
    animator.animationSpeed = _animationSpeed;
    animator.backgroundShadeColor = _backgroundShadeColor;
    animator.scaleTransform = _scaleTransform;
    animator.springDamping = _springDamping;
    animator.springVelocity = _springVelocity;
    animator.backgroundShadeAlpha = _backgroundShadeAlpha;
    return animator;
}

@end


text:
<!DOCTYPE html>

    <title>Local variable error</title>
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>

Main include start

Main include end

        Templates:

Include template value: Test

Sub include template value: Test

Back


text:
{-# LANGUAGE TemplateHaskell, OverloadedStrings #-}
module Handler.Account where

import Lounge
import Common

import Control.Applicative ((<$>), (<*>))

getLoginR :: Handler RepHtml
getLoginR = do
	defaultLayout $ do
		setTitle $ string $ title ++ " - Login"
		addHamlet $(hamletFile "login")

postLoginR :: Handler ()
postLoginR = do
	(name, password) <- runFormPost' $ (,) <$> stringInput "user" <*> stringInput "pwd"
	tryLogin name password
	redirect RedirectTemporary EntriesR

getLogoutR :: Handler ()
getLogoutR = do
	deleteSession "user"
	redirect RedirectTemporary EntriesR


text:
package operator

import (
	"fmt"
	"github.com/gogo/protobuf/proto"
	"github.com/mesos/mesos-go"
	"github.com/mesos/mesos-go/agent"
	"github.com/mesos/mesos-go/encoding"
	"github.com/mesos/mesos-go/httpcli"
	"github.com/mesos/mesos-go/master"
)

// ErrInvalidCallType is caused by a miss-match of
// Agent or Master call types possibly indicating
// an API change between Mesos versions.
type ErrInvalidCallType struct {
	Name  string
	Value int32
}

func (e ErrInvalidCallType) Error() string {
	return fmt.Sprintf("ErrInvalidCallType %s %d", e.Name, e.Value)
}

type (
	client struct {
		*httpcli.Client
	}
	Caller interface {
		// Call issues an HTTP call to a Mesos Master or Agent operator API depending
		// on the type of message supplied. If the type is neither master.Call
		// or agent.Call we will panic.
		Call(proto.Message) (mesos.Response, error)
		// CallAgent issues a call to the Mesos Agent operator API
		CallAgent(call *agent.Call) (*agent.Response, error)
		// CallMaster issues a call to the Mesos Master operator API
		CallMaster(call *master.Call) (*master.Response, error)
	}
)

func (cli *client) Call(msg proto.Message) (mesos.Response, error) {
	switch call := msg.(type) {
	case *agent.Call:
		return cli.Do(call)
	case *master.Call:
		return cli.Do(call)
	}
	panic("Unknown caller message type")
}

func (cli *client) CallAgent(call *agent.Call) (*agent.Response, error) {
	callType, ok := agent.Call_Type_name[int32(*call.Type)]
	if !ok {
		return nil, ErrInvalidCallType{Value: int32(*call.Type)}
	}
	resp, err := cli.Call(call)
	if err != nil {
		return nil, err
	}
	defer resp.Close()
	message := &agent.Response{}
	err = resp.Decoder().Invoke(message)
	if err != nil {
		return nil, err
	}
	return message, checkType(callType, int32(*message.Type), agent.Response_Type_name)
}

func (cli *client) CallMaster(call *master.Call) (*master.Response, error) {
	callType, ok := master.Call_Type_name[int32(*call.Type)]
	if !ok {
		return nil, ErrInvalidCallType{Value: int32(*call.Type)}
	}
	resp, err := cli.Call(call)
	if err != nil {
		return nil, err
	}
	defer resp.Close()
	message := &master.Response{}
	err = resp.Decoder().Invoke(message)
	if err != nil {
		return nil, err
	}
	return message, checkType(callType, int32(*message.Type), master.Response_Type_name)
}

func NewCaller(cli *httpcli.Client) Caller {
	cli.With(
		httpcli.Codec(&encoding.JSONCodec),
	)
	return &client{cli}
}

// checkType validates the callType matches the respType
func checkType(callType string, respType int32, types map[int32]string) error {
	name, ok := types[respType]
	if !ok {
		return ErrInvalidCallType{Value: respType}
	}
	if name != callType {
		return ErrInvalidCallType{Name: name, Value: respType}
	}
	return nil
}


text:
from autothreadharness.harness_case import HarnessCase
import unittest

class Router_5_3_2(HarnessCase):
    role = HarnessCase.ROLE_ROUTER
    case = '5 3 2'
    golden_devices_required = 3

    def on_dialog(self, dialog, title):
        pass

if __name__ == '__main__':
    unittest.main()


text:
package de.philworld.bukkit.compassex;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;

import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.inventory.ItemStack;

import de.philworld.bukkit.compassex.command.Command;
import de.philworld.bukkit.compassex.command.CommandContext;
import de.philworld.bukkit.compassex.persistence.Persistable;
import de.philworld.bukkit.compassex.util.BlockLocation;
import de.philworld.bukkit.compassex.util.PermissionException;

public class DeathpointComponent extends Component implements Listener, Persistable {

	private final Map<String, BlockLocation> deathPoints = new HashMap<String, BlockLocation>();

	public DeathpointComponent(CompassEx plugin) {
		super(plugin);

		plugin.getServer().getPluginManager().registerEvents(this, plugin);

		help("deathpoint", "Set to your latest death point", "compassex.deathpoint");

		load();
	}

	private void load() {
		File f = new File(plugin.getDataFolder(), "deathpoints.db.yml");
		if (!f.exists())
			return;
		YamlConfiguration config = YamlConfiguration.loadConfiguration(f);
		for (String player : config.getKeys(false)) {
			deathPoints.put(player, (BlockLocation) config.get(player));
		}
	}

	@Override
	public void save() {
		YamlConfiguration config = new YamlConfiguration();
		synchronized (deathPoints) {
			for (Entry<String, BlockLocation> point : deathPoints.entrySet()) {
				config.set(point.getKey(), point.getValue());
			}
		}
		try {
			config.save(new File(plugin.getDataFolder(), "deathpoints.db.yml"));
		} catch (IOException e) {
			plugin.getLogger().log(Level.SEVERE, "Unable to save death points!", e);
		}
	}

	@SuppressWarnings("unused")
	@Command(aliases = { "deathpoint", "dp", "death" }, permission = "compassex.deathpoint")
	public void deathpoint(CommandContext context, Player p) throws PermissionException {
		BlockLocation dp = deathPoints.get(p.getName());
		if (dp == null) {
			sendMessage(p, "Could not find your last death point.");
			return;
		}
		Location loc = dp.toLocation();
		if (loc == null || !loc.getWorld().equals(p.getWorld())) {
			sendMessage(p, "Your deathpoint is in another world!");
			return;
		}
		setTarget(p, dp.toLocation());
		sendMessage(p, "Set your compass to your last death point.");
	}

	@EventHandler
	public void onEntityDeath(EntityDeathEvent event) {
		Entity entity = event.getEntity();
		if (entity instanceof Player) {
			Player p = (Player) entity;
			synchronized (deathPoints) {
				deathPoints.put(p.getName(), new BlockLocation(entity.getLocation()));
			}
		}
	}

	@EventHandler
	public void onPlayerRespawn(PlayerRespawnEvent event) {
		if (event.getPlayer().hasPermission("compassex.giveondeath")) {
			synchronized (deathPoints) {
				if (!deathPoints.containsKey(event.getPlayer().getName()))
					return;
			}
			givePlayerDPCompass(event.getPlayer());
		}
	}

	/**
	 * Gives a player a compass pointed to his/her death point.
	 */
	private void givePlayerDPCompass(Player p) {
		p.getInventory().addItem(new ItemStack(Material.COMPASS));

		BlockLocation dp = deathPoints.get(p.getName());
		Location loc = dp.toLocation();
		if (loc == null || !loc.getWorld().equals(p.getWorld()))
			return; // other world

		setTarget(p, loc);
	}

}


text:
Web Timer is a Chrome extension designed to help you keep track of how
you're using your time online.

Check it out in the [Chrome Web Store](http://webtimerapp.com)!


text:
package net.daw.dao.implementation;

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import net.daw.bean.implementation.ViaBean;
import net.daw.bean.implementation.UsuarioBean;
import net.daw.bean.implementation.ViaBean;
import net.daw.dao.publicinterface.TableDaoInterface;
import net.daw.dao.publicinterface.ViewDaoInterface;
import net.daw.data.implementation.MysqlData;
import net.daw.helper.statics.FilterBeanHelper;
import net.daw.helper.statics.Log4j;
import net.daw.helper.statics.SqlBuilder;

/**
 *
 * @author a044888329b
 */
public class ViaDao implements ViewDaoInterface<ViaBean>, TableDaoInterface<ViaBean>{

    private String strTable = "via";
    private String strSQL = "select * from via where 1=1 ";
    private MysqlData oMysql = null;
    private Connection oConnection = null;
    private UsuarioBean oPuserSecurity = null;

    public ViaDao(Connection oPooledConnection, UsuarioBean oPusuarioBean_security, String strWhere) throws Exception {
        try {
            oConnection = oPooledConnection;
            oMysql = new MysqlData(oConnection);
            oPuserSecurity = oPusuarioBean_security;
            if (strWhere != null) {
                strSQL += strWhere;
            }
        } catch (Exception ex) {
            Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
            throw new Exception();
        }
    }

    @Override
    public Long getCount(ArrayList<FilterBeanHelper> hmFilter) throws Exception {
        strSQL += SqlBuilder.buildSqlWhere(hmFilter);
        Long pages = 0L;
        try {
            pages = oMysql.getCount(strSQL);
        } catch (Exception ex) {
            Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
            throw new Exception();
        }
        return pages;
    }

    @Override
    public ArrayList<ViaBean> getPage(int intRegsPerPag, int intPage, ArrayList<FilterBeanHelper> alFilter, HashMap<String, String> hmOrder, Integer expand) throws Exception {
        strSQL += SqlBuilder.buildSqlWhere(alFilter);
        strSQL += SqlBuilder.buildSqlOrder(hmOrder);
        strSQL += SqlBuilder.buildSqlLimit(oMysql.getCount(strSQL), intRegsPerPag, intPage);
        ArrayList<ViaBean> arrVia = new ArrayList<>();
        ResultSet oResultSet = null;
        try {
            oResultSet = oMysql.getAllSQL(strSQL);
            while (oResultSet.next()) {
                ViaBean oViaBean = new ViaBean();
                arrVia.add(oViaBean.fill(oResultSet, oConnection, oPuserSecurity, expand));
            }
            if (oResultSet != null) {
                oResultSet.close();
            }
        } catch (Exception ex) {
            Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
            throw new Exception();
        } finally {
            if (oResultSet != null) {
                oResultSet.close();
            }
        }
        return arrVia;
    }

    @Override
    public ArrayList<ViaBean> getAll(ArrayList<FilterBeanHelper> alFilter, HashMap<String, String> hmOrder, Integer expand) throws Exception {
        strSQL += SqlBuilder.buildSqlWhere(alFilter);
        strSQL += SqlBuilder.buildSqlOrder(hmOrder);
        ArrayList<ViaBean> arrVia = new ArrayList<>();
        ResultSet oResultSet = null;
        try {
            oResultSet = oMysql.getAllSQL(strSQL);
            while (oResultSet.next()) {
                ViaBean oViaBean = new ViaBean();
                arrVia.add(oViaBean.fill(oResultSet, oConnection, oPuserSecurity, expand));
            }
        } catch (Exception ex) {
            Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
            throw new Exception();
        } finally {
            if (oResultSet != null) {
                oResultSet.close();
            }
        }
        return arrVia;
    }

    @Override
    public ViaBean get(ViaBean oViaBean, Integer expand) throws Exception {
        if (oViaBean.getId() > 0) {
            ResultSet oResultSet = null;
            try {
                oResultSet = oMysql.getAllSQL(strSQL + " And id= " + oViaBean.getId() + " ");
                Boolean empty = true;
                while (oResultSet.next()) {
                    oViaBean = oViaBean.fill(oResultSet, oConnection, oPuserSecurity, expand);
                    empty = false;
                }
                if (empty) {
                    oViaBean.setId(0);
                }
            } catch (Exception ex) {
                Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
                throw new Exception();
            } finally {
                if (oResultSet != null) {
                    oResultSet.close();
                }
            }
        } else {
            oViaBean.setId(0);
        }
        return oViaBean;
    }

    @Override
    public Integer set(ViaBean oViaBean) throws Exception {
        Integer iResult = null;
        try {
            if (oViaBean.getId() == 0) {
                strSQL = "INSERT INTO " + strTable + " ";
                strSQL += "(" + oViaBean.getColumns() + ")";
                strSQL += "VALUES(" + oViaBean.getValues() + ")";
                iResult = oMysql.executeInsertSQL(strSQL);
            } else {
                strSQL = "UPDATE " + strTable + " ";
                strSQL += " SET " + oViaBean.toPairs();
                strSQL += " WHERE id=" + oViaBean.getId();
                iResult = oMysql.executeUpdateSQL(strSQL);
            }
        } catch (Exception ex) {
            Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
            throw new Exception();
        }
        return iResult;
    }

    @Override
    public Integer remove(Integer id) throws Exception {
        int result = 0;
        try {
            result = oMysql.removeOne(id, strTable);
        } catch (Exception ex) {
            Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
            throw new Exception();
        }
        return result;
    }

}


text:
package storm.rx;

import rx.Observable;
import storm.core.StormDeleteDispatcher;
import storm.core.StormObject;
import storm.query.Selection;

/**
 * Created by Dimitry Ivanov on 21.12.2015.
 */
public class StormDeleteRxStream<T extends StormObject> implements StormRxStreamSingleValue<Integer> {

    private final StormRx mStorm;
    private final Class<T> mTable;
    private final Selection mSelection;
    private final StormDeleteDispatcher mDispatcher;

    StormDeleteRxStream(StormDeleteRxType<T> type) {
        mStorm = type.storm();
        mTable = type.table();
        mSelection = type.selection();
        mDispatcher = type.dispatcher();
    }

    @Override
    public Observable<Integer> create() {

        final StormRxObservable.ValueProvider<Integer> provider = new StormRxObservable.ValueProvider<Integer>() {
            @Override
            public Integer provide() {
                return mDispatcher.execute(mStorm, mTable, mSelection);
            }
        };

        return StormRxObservable.createOneShot(mStorm, provider);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2011 Google Inc.
All Rights Reserved. -->
<resources>
    <dimen name="message_item_avatar_on_right_text_indent">50dip</dimen>
    <dimen name="message_item_text_padding_left_right">12dip</dimen>
    <dimen name="message_item_text_padding_top">5dip</dimen>

    <dimen name="avatar_width_height">64dip</dimen>

    <dimen name="input_text_height">48dip</dimen>
    <dimen name="input_text_height_adjusted">8dip</dimen>

    <dimen name="mms_inline_attachment_size">178dip</dimen>

    <dimen name="widget_margin_top">0dip</dimen>
    <dimen name="widget_margin_left">0dip</dimen>
    <dimen name="widget_margin_right">0dip</dimen>
    <dimen name="widget_margin_bottom">0dip</dimen>

    <!-- Bammer item spacing -->
    <dimen name="banner_s_space">4dip</dimen>
    <dimen name="banner_m_space">8dip</dimen>
</resources>


text:
CREATE TABLE `contact` (
  `contact_id` int(11) NOT NULL AUTO_INCREMENT,
  `contact_name` varchar(255) NOT NULL,
  `contact_email` varchar(255) DEFAULT NULL,
  `contact_subject` varchar(255) DEFAULT NULL,
  `contact_message` text,
  `viewed` int(11) DEFAULT '0',
  `date_created` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`contact_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1


text:
import assert from "assert";
import * as t from "babel-types";
import { hoist } from "./hoist";
import { Emitter } from "./emit";
import * as util from "./util";

let getMarkInfo = require("private").makeAccessor();

exports.visitor = {
  Function: {
    exit: function(path, state) {
      let node = path.node;

      if (node.generator) {
        if (node.async) {
          // Async generator
          if (state.opts.asyncGenerators === false) return;
        } else {
          // Plain generator
          if (state.opts.generators === false) return;
        }
      } else if (node.async) {
        // Async function
        if (state.opts.async === false) return;
      } else {
        // Not a generator or async function.
        return;
      }

      let contextId = path.scope.generateUidIdentifier("context");
      let argsId = path.scope.generateUidIdentifier("args");

      path.ensureBlock();
      let bodyBlockPath = path.get("body");

      if (node.async) {
        bodyBlockPath.traverse(awaitVisitor);
      }

      bodyBlockPath.traverse(functionSentVisitor, {
        context: contextId
      });

      let outerBody = [];
      let innerBody = [];

      bodyBlockPath.get("body").forEach(function(childPath) {
        let node = childPath.node;
        if (node && node._blockHoist != null) {
          outerBody.push(node);
        } else {
          innerBody.push(node);
        }
      });

      if (outerBody.length > 0) {
        // Only replace the inner body if we actually hoisted any statements
        // to the outer body.
        bodyBlockPath.node.body = innerBody;
      }

      let outerFnExpr = getOuterFnExpr(path);
      // Note that getOuterFnExpr has the side-effect of ensuring that the
      // function has a name (so node.id will always be an Identifier), even
      // if a temporary name has to be synthesized.
      t.assertIdentifier(node.id);
      let innerFnId = t.identifier(node.id.name + "$");

      // Turn all declarations into vars, and replace the original
      // declarations with equivalent assignment expressions.
      let vars = hoist(path);

      let didRenameArguments = renameArguments(path, argsId);
      if (didRenameArguments) {
        vars = vars || t.variableDeclaration("var", []);
        vars.declarations.push(t.variableDeclarator(
          argsId, t.identifier("arguments")
        ));
      }

      let emitter = new Emitter(contextId);
      emitter.explode(path.get("body"));

      if (vars && vars.declarations.length > 0) {
        outerBody.push(vars);
      }

      let wrapArgs = [
        emitter.getContextFunction(innerFnId),
        // Async functions that are not generators don't care about the
        // outer function because they don't need it to be marked and don't
        // inherit from its .prototype.
        node.generator ? outerFnExpr : t.nullLiteral(),
        t.thisExpression()
      ];

      let tryLocsList = emitter.getTryLocsList();
      if (tryLocsList) {
        wrapArgs.push(tryLocsList);
      }

      let wrapCall = t.callExpression(
        util.runtimeProperty(node.async ? "async" : "wrap"),
        wrapArgs
      );

      outerBody.push(t.returnStatement(wrapCall));
      node.body = t.blockStatement(outerBody);

      let wasGeneratorFunction = node.generator;
      if (wasGeneratorFunction) {
        node.generator = false;
      }

      if (node.async) {
        node.async = false;
      }

      if (wasGeneratorFunction && t.isExpression(node)) {
        path.replaceWith(t.callExpression(util.runtimeProperty("mark"), [node]));
      }
    }
  }
};

// Given a NodePath for a Function, return an Expression node that can be
// used to refer reliably to the function object from inside the function.
// This expression is essentially a replacement for arguments.callee, with
// the key advantage that it works in strict mode.
function getOuterFnExpr(funPath) {
  let node = funPath.node;
  t.assertFunction(node);

  if (node.generator && // Non-generator functions don't need to be marked.
      t.isFunctionDeclaration(node)) {
    let pp = funPath.findParent(function (path) {
      return path.isProgram() || path.isBlockStatement();
    });

    if (!pp) {
      return node.id;
    }

    let markDecl = getRuntimeMarkDecl(pp);
    let markedArray = markDecl.declarations[0].id;
    let funDeclIdArray = markDecl.declarations[0].init.callee.object;
    t.assertArrayExpression(funDeclIdArray);

    let index = funDeclIdArray.elements.length;
    funDeclIdArray.elements.push(node.id);

    return t.memberExpression(
      markedArray,
      t.numericLiteral(index),
      true
    );
  }

  return node.id || (
    node.id = funPath.scope.parent.generateUidIdentifier("callee")
  );
}

function getRuntimeMarkDecl(blockPath) {
  let block = blockPath.node;
  assert.ok(Array.isArray(block.body));

  let info = getMarkInfo(block);
  if (info.decl) {
    return info.decl;
  }

  info.decl = t.variableDeclaration("var", [
    t.variableDeclarator(
      blockPath.scope.generateUidIdentifier("marked"),
      t.callExpression(
        t.memberExpression(
          t.arrayExpression([]),
          t.identifier("map"),
          false
        ),
        [util.runtimeProperty("mark")]
      )
    )
  ]);

  blockPath.unshiftContainer("body", info.decl);

  return info.decl;
}

function renameArguments(funcPath, argsId) {
  let state = {
    didRenameArguments: false,
    argsId: argsId
  };

  funcPath.traverse(argumentsVisitor, state);

  // If the traversal replaced any arguments references, then we need to
  // alias the outer function's arguments binding (be it the implicit
  // arguments object or some other parameter or variable) to the variable
  // named by argsId.
  return state.didRenameArguments;
}

let argumentsVisitor = {
  "FunctionExpression|FunctionDeclaration": function(path) {
    path.skip();
  },

  Identifier: function(path, state) {
    if (path.node.name === "arguments" && util.isReference(path)) {
      path.replaceWith(state.argsId);
      state.didRenameArguments = true;
    }
  }
};

let functionSentVisitor = {
  MetaProperty(path) {
    let { node } = path;

    if (node.meta.name === "function" && node.property.name === "sent") {
      path.replaceWith(t.memberExpression(this.context, t.identifier("_sent")));
    }
  }
};

let awaitVisitor = {
  Function: function(path) {
    path.skip(); // Don't descend into nested function scopes.
  },

  AwaitExpression: function(path) {
    // Convert await and await* expressions to yield expressions.
    let argument = path.node.argument;

    // Transforming `await x` to `yield regeneratorRuntime.awrap(x)`
    // causes the argument to be wrapped in such a way that the runtime
    // can distinguish between awaited and merely yielded values.
    path.replaceWith(t.yieldExpression(
      t.callExpression(
        util.runtimeProperty("awrap"),
        [argument]
      ),
      false
    ));
  }
};


text:
package com.beatsportable.beats;

import java.util.AbstractQueue;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Random;

/** An array-based queue. **/
public class ToolsArrayQueue<T> extends AbstractQueue<T> {

	/*TODO: This queue doesn't set dequeued spaces to null (in poll and clear).
	  This is a memory leak. I tried fixing it, it looked like doing that
	  killed the framerate (probably because clear() would be O(n) instead of O(1))
	  but that may have been an illusion. */

	protected T[] elements;
	protected int start = 0; //Index of first element
	protected int end = 0; //Index of element after last element
	/* Elements are stored in the range:   [start, end) mod elements.length
	   If start == end, the queue is empty. (Therefore the array can never be completely full.)
	   Elements are added to the end and removed from the start. */

	public ToolsArrayQueue() {
		this(32);
	}
	@SuppressWarnings("unchecked")
	public ToolsArrayQueue(int capacity) {
		elements = (T[]) new Object[capacity];
	}

	// ====== Queue functions ======

	public T peek() {
		if (end == start) return null;
		return elements[start];
	}

	public T poll() {
		if (end == start) return null;
		T out = elements[start];
		start = inc(start);
		return out;
	}

	public boolean offer(T o) {
		if (o == null) return false;

		int incend = inc(end);
		if (incend == start) {
			setCapacity(elements.length * 2);
			incend = inc(end);
		}

		elements[end] = o;
		end = incend;
		return true;
	}

	@Override
	public int size() {
		return (end >= start) ? (end - start) : (elements.length + end - start);
	}

	@Override
	public boolean isEmpty() { return end == start; }

	@Override
	public Iterator<T> iterator() {
		return new Iterator<T>() {
			int pos = start;
			int _end = end;
			public boolean hasNext() {
				return pos != _end;
			}

			public T next() {
				if (pos != _end) {
					T o = elements[pos];
					pos = inc(pos);
					return o;
				} else {
					throw new NoSuchElementException();
				}
			}

			public void remove() {
				throw new UnsupportedOperationException("ZE METHOD, ZIT DOES NOSSING EITHER!");
			}
		};
	}

	@Override
	public Object[] toArray() {
		Object[] o = new Object[size()];
		arraycopy(o, 0);
		return o;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <U> U[] toArray(U[] a) {
		int size = size();
		a = (size <= a.length) ? a : (U[]) new Object[size];
		arraycopy(a, 0);
		if (size < a.length)
			a[size] = null;
		return a;
	}

	@Override
	public void clear() {
		start = 0;
		end = 0;
	}

	// ======== Helpers ========

	private int inc(int idx) {
		idx++;
		return (idx >= elements.length) ? (idx - elements.length) : idx;
	}

	/*
	private int dec(int idx) {
		idx--;
		return (idx < 0) ? (idx + elements.length) : idx;
	}
	*/

	@SuppressWarnings("unchecked")
	private void setCapacity(int cap) {
		T[] newelements = (T[]) new Object[cap];
		arraycopy(newelements, 0);
		int s = size();
		elements = newelements;
		start = 0;
		end = s;
	}

	/* For cap elements, need an array of length at least cap+1 */
	private void ensureCapacity(int cap) {
		if (elements.length < cap+1) {
			setCapacity(cap*2);
		}
	}

	// ====== Copying =====

	//Ensure that the array indexing starts at 0.
	public void cleanup() {
		if (start != 0) setCapacity(elements.length);
	}

	/** Copies the contents of the given queue into consecutive elements
	 *   [  destpos, destpos + this.size()  )
	 * of the destination array.
	 *
	 * Throws the same exceptions as System.arraycopy.
	 *
	 * @param dest destination array
	 * @param destPos starting position in the destination array
	 * @return size = number of elements copied
	 */
	public int arraycopy(Object dest, int destPos) {
		return arraycopy(elements, elements.length, start, dest, destPos, size());
	}

	//TODO can this be addAll?
	public boolean addQueue(ToolsArrayQueue<T> that) {
		int thatsize = that.size();
		ensureCapacity(size() + thatsize);

		arraycopy(that.elements, that.elements.length, that.start,
				  elements, elements.length, end, thatsize);

		end += thatsize;
		if (end >= elements.length) end -= elements.length;
		return true;
	}

	/*
	private static final void fill(Object[] a, int fromIndex, int toIndex, Object val) {
		if (fromIndex <= toIndex) {
			Arrays.fill(a, fromIndex, toIndex, val);
		} else {
			//int size = toIndex - fromIndex + a.length;
			Arrays.fill(a, fromIndex, a.length, val);
			Arrays.fill(a, 0, toIndex, val);
		}
	}
	*/

	/** If src is a wraparound array of capacity srcCap
	 *     with elements at [srcStart, srcEnd) mod srcCap
	 *     and 0 <= srcStart < srcCap
	 *  and dest is a regular array
	 *  copy copyLen elements from src into elements [destPos, destPos + copyLen) of dest
	 *
	 *  Warning: this does not verify that copyLen < src.size()
	 *
	 * @param src source array
	 * @param srcCap capacity (i.e. backing array length) of src
	 * @param srcStart src backing array start index
	 * @param dest destination array
	 * @param destPos destination array start index
	 * @param copyLen number of elements to copy
	 * @return number of elements copied = copyLen
	 */
	private static final int arraycopy(Object src, int srcCap, int srcStart,
			                           Object dest, int destPos, int copyLen) {
		if (srcStart + copyLen <= srcCap) {
			System.arraycopy(src, srcStart, dest, destPos, copyLen);
		} else {
			int array1len = srcCap - srcStart;
			//do second half first, so this is hopefully an atomic operation
			System.arraycopy(src, 0, dest, destPos + array1len, copyLen - array1len);
			System.arraycopy(src, srcStart, dest, destPos, array1len);
		}
		return copyLen;
	}

	/** If src is a wraparound array of capacity srcCap with elements at [srcStart, srcEnd) mod srcCap
	 *  and dest is a wraparound array of capacity destCap with elements at [destStart, destEnd) mod srcCap
	 *  copy copyLen elements from src into elements [destPos, destPos + copyLen) of dest
	 *
	 *  Warning: this does not verify that copyLen < src.size() or copyLen < dest.size()
	 *
	 *  Returns # elements copied = copyLen */
	private static final int arraycopy(Object src, int srcCap, int srcStart,
			                           Object dest, int destCap, int destStart,
			                           int copyLen) {
		if (destStart + copyLen <= destCap) {
			arraycopy(src, srcCap, srcStart, dest, destStart, copyLen);
		} else {
			int array1len = destCap - destStart;
			int start2 = srcStart + array1len;
			if (start2 > srcCap) start2 -= srcCap;
			//do second half first, so this is hopefully an atomic operation
			arraycopy(src, srcCap, start2, dest, 0, copyLen - array1len);
			arraycopy(src, srcCap, srcStart, dest, destStart, array1len);
		}
		return copyLen;
	}

	// ======== Tester ==========
	private static final String assertequal(String msg, Object a, Object b) {
		if ((a == null && b == null) || (a != null && a.equals(b)))
			return "";
		else
			return String.format(msg, a, b);
	}
	public static final void test() {
		Random r = new Random();
		String msg = "";
		while (true) {
			ToolsArrayQueue<Integer> taq= new ToolsArrayQueue<Integer>();
			LinkedList<Integer> ll = new LinkedList<Integer>();
			for (int i=0; i<2000000; i++) {
				msg = "";
				try {
					msg += assertequal("Size difference: LL = %d, TAQ = %d; ", ll.size(), taq.size());
					msg += assertequal("Emptiness difference: LL = %d, TAQ = %d; ", ll.isEmpty(), taq.isEmpty());

					Object llv, taqv;
					switch(r.nextInt(4)) {
						case 0: case 3:
							int rnd = r.nextInt();
							llv = ll.offer(rnd);
							taqv = taq.offer(rnd);
							msg += assertequal("Offer: LL = %s, TAQ = %s; ", llv, taqv);
							break;
						case 1:
							llv = ll.peek();
							taqv = taq.peek();
							msg += assertequal("Peek: LL = %s, TAQ = %s; ", llv, taqv);
							break;
						case 2:
							llv = ll.poll();
							taqv = taq.poll();
							msg += assertequal("Poll: LL = %s, TAQ = %s; ", llv, taqv);
							break;
					}

				} catch (Exception e) {
					msg += "EXCEPTION [[" + e.toString() + "]]; ";
					e.printStackTrace();
				}
				if (!msg.equals("") || (i%100000 == 0))
					System.out.println(String.format("%d: %s", i, msg));
			}
			int size = taq.size();
			System.out.println("size: " + size);
			Integer[] fromArr = (Integer[]) taq.toArray(new Integer[size]);
			Integer[] fromIt = new Integer[size];
			int idx = 0; for (Integer ii: taq) { fromIt[idx++] = ii; }
			System.out.print(assertequal("fromIt size: expected %d got %d\n", size, idx));
			for (int i = 0; i<size; i++) {
				msg = "";
				msg += assertequal("arr/it: arr = %s, it = %s; ", fromArr[i], fromIt[i]);
				msg += assertequal("arr/Q: arr = %s, Q = %s; ", fromArr[i], taq.poll());
				if (!msg.equals(""))
					System.out.println(String.format("%d: %s", i, msg));
			}
			System.out.print(assertequal("size: expected %d got %d\n", 0, taq.size()));
			System.out.println("equality check done");
		}
	}

	//public static void main(String[] args) { test(); }

}


text:
module.exports = function (settings, callback) {
	var options = {
		url: settings.uri,
		type: settings.method,
		headers: settings.headers,
		data: settings.json,
		//we parse ourselves
		dataType: 'text'
	};

	$.ajax(options)
	.done(function (data, textStatus, jqXHR) {
		callback(null, { statusCode: jqXHR.status }, data);
	})
	.fail(function (jqXHR, textStatus, error) {
		callback(null, { statusCode: jqXHR.status }, error);
	});
};


text:
Rails.application.routes.draw do
  if UserSettings.redis
    get     UserSettings.route_drawer.match_get_settings
    post    UserSettings.route_drawer.match_set_settings
    put     UserSettings.route_drawer.match_set_once_settings
    delete  UserSettings.route_drawer.match_remove_settings
  end
end