<commit_before>use rustc_hir::def_id::LOCAL_CRATE;
use rustc_middle::ty::query::Providers;
use rustc_session::Session;
use rustc_span::symbol::sym;
use rustc_span::symbol::Symbol;

// When adding features to the below lists
// check whether they're named already elsewhere in rust
// e.g. in stdarch and whether the given name matches LLVM's
// if it doesn't, to_llvm_feature in llvm_util in rustc_codegen_llvm needs to be adapted

const ARM_ALLOWED_FEATURES: &[(&str, Option<Symbol>)] = &[
    ("aclass", Some(sym::arm_target_feature)),
    ("mclass", Some(sym::arm_target_feature)),
    ("rclass", Some(sym::arm_target_feature)),
    ("dsp", Some(sym::arm_target_feature)),
    ("neon", Some(sym::arm_target_feature)),
    ("crc", Some(sym::arm_target_feature)),
    ("crypto", Some(sym::arm_target_feature)),
    ("v5te", Some(sym::arm_target_feature)),
    ("v6", Some(sym::arm_target_feature)),
    ("v6k", Some(sym::arm_target_feature)),
    ("v6t2", Some(sym::arm_target_feature)),
    ("v7", Some(sym::arm_target_feature)),
    ("v8", Some(sym::arm_target_feature)),
    ("vfp2", Some(sym::arm_target_feature)),
    ("vfp3", Some(sym::arm_target_feature)),
    ("vfp4", Some(sym::arm_target_feature)),
    ("fp-armv8", Some(sym::arm_target_feature)),
    // This is needed for inline assembly, but shouldn't be stabilized as-is
    // since it should be enabled per-function using #[instruction_set], not
    // #[target_feature].
    ("thumb-mode", Some(sym::arm_target_feature)),
];

// Commented features are not available in LLVM 10.0, or have since been renamed
const AARCH64_ALLOWED_FEATURES: &[(&str, Option<Symbol>)] = &[
    // FEAT_AdvSimd
    ("neon", Some(sym::aarch64_target_feature)),
    // FEAT_FP
    ("fp", Some(sym::aarch64_target_feature)),
    // FEAT_FP16
    ("fp16", Some(sym::aarch64_target_feature)),
    // FEAT_SVE
    ("sve", Some(sym::aarch64_target_feature)),
    // FEAT_CRC
    ("crc", Some(sym::aarch64_target_feature)),
    // Cryptographic extension
    ("crypto", Some(sym::aarch64_target_feature)),
    // FEAT_RAS
    ("ras", Some(sym::aarch64_target_feature)),
    // FEAT_LSE
    ("lse", Some(sym::aarch64_target_feature)),
    // FEAT_RDM
    ("rdm", Some(sym::aarch64_target_feature)),
    // FEAT_RCPC
    ("rcpc", Some(sym::aarch64_target_feature)),
    // FEAT_RCPC2
    ("rcpc2", Some(sym::aarch64_target_feature)),
    // FEAT_DotProd
    ("dotprod", Some(sym::aarch64_target_feature)),
    // FEAT_TME
    ("tme", Some(sym::aarch64_target_feature)),
    // FEAT_FHM
    ("fhm", Some(sym::aarch64_target_feature)),
    // FEAT_DIT
    ("dit", Some(sym::aarch64_target_feature)),
    // FEAT_FLAGM
    // ("flagm", Some(sym::aarch64_target_feature)),
    // FEAT_SSBS
    ("ssbs", Some(sym::aarch64_target_feature)),
    // FEAT_SB
    ("sb", Some(sym::aarch64_target_feature)),
    // FEAT_PAUTH
    // ("pauth", Some(sym::aarch64_target_feature)),
    // FEAT_DPB
    ("dpb", Some(sym::aarch64_target_feature)),
    // FEAT_DPB2
    ("dpb2", Some(sym::aarch64_target_feature)),
    // FEAT_SVE2
    ("sve2", Some(sym::aarch64_target_feature)),
    // FEAT_SVE2_AES
    ("sve2-aes", Some(sym::aarch64_target_feature)),
    // FEAT_SVE2_SM4
    ("sve2-sm4", Some(sym::aarch64_target_feature)),
    // FEAT_SVE2_SHA3
    ("sve2-sha3", Some(sym::aarch64_target_feature)),
    // FEAT_SVE2_BitPerm
    ("sve2-bitperm", Some(sym::aarch64_target_feature)),
    // FEAT_FRINTTS
    ("frintts", Some(sym::aarch64_target_feature)),
    // FEAT_I8MM
    // ("i8mm", Some(sym::aarch64_target_feature)),
    // FEAT_F32MM
    // ("f32mm", Some(sym::aarch64_target_feature)),
    // FEAT_F64MM
    // ("f64mm", Some(sym::aarch64_target_feature)),
    // FEAT_BF16
    // ("bf16", Some(sym::aarch64_target_feature)),
    // FEAT_RAND
    ("rand", Some(sym::aarch64_target_feature)),
    // FEAT_BTI
    ("bti", Some(sym::aarch64_target_feature)),
    // FEAT_MTE
    ("mte", Some(sym::aarch64_target_feature)),
    // FEAT_JSCVT
    ("jsconv", Some(sym::aarch64_target_feature)),
    // FEAT_FCMA
    ("fcma", Some(sym::aarch64_target_feature)),
    // FEAT_SHA1 & FEAT_SHA256
    ("sha2", Some(sym::aarch64_target_feature)),
    // FEAT_SHA512 & FEAT_SHA3
    ("sha3", Some(sym::aarch64_target_feature)),
    // FEAT_SM3 & FEAT_SM4
    ("sm4", Some(sym::aarch64_target_feature)),
    ("v8.1a", Some(sym::aarch64_target_feature)),
    ("v8.2a", Some(sym::aarch64_target_feature)),
    ("v8.3a", Some(sym::aarch64_target_feature)),
    ("v8.4a", Some(sym::aarch64_target_feature)),
    ("v8.5a", Some(sym::aarch64_target_feature)),
    // ("v8.6a", Some(sym::aarch64_target_feature)),
    // ("v8.7a", Some(sym::aarch64_target_feature)),
];

const X86_ALLOWED_FEATURES: &[(&str, Option<Symbol>)] = &[
    ("adx", Some(sym::adx_target_feature)),
    ("aes", None),
    ("avx", None),
    ("avx2", None),
    ("avx512bf16", Some(sym::avx512_target_feature)),
    ("avx512bitalg", Some(sym::avx512_target_feature)),
    ("avx512bw", Some(sym::avx512_target_feature)),
    ("avx512cd", Some(sym::avx512_target_feature)),
    ("avx512dq", Some(sym::avx512_target_feature)),
    ("avx512er", Some(sym::avx512_target_feature)),
    ("avx512f", Some(sym::avx512_target_feature)),
    ("avx512gfni", Some(sym::avx512_target_feature)),
    ("avx512ifma", Some(sym::avx512_target_feature)),
    ("avx512pf", Some(sym::avx512_target_feature)),
    ("avx512vaes", Some(sym::avx512_target_feature)),
    ("avx512vbmi", Some(sym::avx512_target_feature)),
    ("avx512vbmi2", Some(sym::avx512_target_feature)),
    ("avx512vl", Some(sym::avx512_target_feature)),
    ("avx512vnni", Some(sym::avx512_target_feature)),
    ("avx512vp2intersect", Some(sym::avx512_target_feature)),
    ("avx512vpclmulqdq", Some(sym::avx512_target_feature)),
    ("avx512vpopcntdq", Some(sym::avx512_target_feature)),
    ("bmi1", None),
    ("bmi2", None),
    ("cmpxchg16b", Some(sym::cmpxchg16b_target_feature)),
    ("ermsb", Some(sym::ermsb_target_feature)),
    ("f16c", Some(sym::f16c_target_feature)),
    ("fma", None),
    ("fxsr", None),
    ("lzcnt", None),
    ("movbe", Some(sym::movbe_target_feature)),
    ("pclmulqdq", None),
    ("popcnt", None),
    ("rdrand", None),
    ("rdseed", None),
    ("rtm", Some(sym::rtm_target_feature)),
    ("sha", None),
    ("sse", None),
    ("sse2", None),
    ("sse3", None),
    ("sse4.1", None),
    ("sse4.2", None),
    ("sse4a", Some(sym::sse4a_target_feature)),
    ("ssse3", None),
    ("tbm", Some(sym::tbm_target_feature)),
    ("xsave", None),
    ("xsavec", None),
    ("xsaveopt", None),
    ("xsaves", None),
];

const HEXAGON_ALLOWED_FEATURES: &[(&str, Option<Symbol>)] = &[
    ("hvx", Some(sym::hexagon_target_feature)),
    ("hvx-length128b", Some(sym::hexagon_target_feature)),
];

const POWERPC_ALLOWED_FEATURES: &[(&str, Option<Symbol>)] = &[
    ("altivec", Some(sym::powerpc_target_feature)),
    ("power8-altivec", Some(sym::powerpc_target_feature)),
    ("power9-altivec", Some(sym::powerpc_target_feature)),
    ("power8-vector", Some(sym::powerpc_target_feature)),
    ("power9-vector", Some(sym::powerpc_target_feature)),
    ("vsx", Some(sym::powerpc_target_feature)),
];

const MIPS_ALLOWED_FEATURES: &[(&str, Option<Symbol>)] =
    &[("fp64", Some(sym::mips_target_feature)), ("msa", Some(sym::mips_target_feature))];

const RISCV_ALLOWED_FEATURES: &[(&str, Option<Symbol>)] = &[
    ("m", Some(sym::riscv_target_feature)),
    ("a", Some(sym::riscv_target_feature)),
    ("c", Some(sym::riscv_target_feature)),
    ("f", Some(sym::riscv_target_feature)),
    ("d", Some(sym::riscv_target_feature)),
    ("e", Some(sym::riscv_target_feature)),
];

const WASM_ALLOWED_FEATURES: &[(&str, Option<Symbol>)] = &[
    ("simd128", Some(sym::wasm_target_feature)),
    ("atomics", Some(sym::wasm_target_feature)),
    ("nontrapping-fptoint", Some(sym::wasm_target_feature)),
];

/// When rustdoc is running, provide a list of all known features so that all their respective
/// primitives may be documented.
///
/// IMPORTANT: If you're adding another feature list above, make sure to add it to this iterator!
pub fn all_known_features() -> impl Iterator<Item = (&'static str, Option<Symbol>)> {
    std::iter::empty()
        .chain(ARM_ALLOWED_FEATURES.iter())
        .chain(AARCH64_ALLOWED_FEATURES.iter())
        .chain(X86_ALLOWED_FEATURES.iter())
        .chain(HEXAGON_ALLOWED_FEATURES.iter())
        .chain(POWERPC_ALLOWED_FEATURES.iter())
        .chain(MIPS_ALLOWED_FEATURES.iter())
        .chain(RISCV_ALLOWED_FEATURES.iter())
        .chain(WASM_ALLOWED_FEATURES.iter())
        .cloned()
}

pub fn supported_target_features(sess: &Session) -> &'static [(&'static str, Option<Symbol>)] {
    match &*sess.target.arch {
        "arm" => ARM_ALLOWED_FEATURES,
        "aarch64" => AARCH64_ALLOWED_FEATURES,
        "x86" | "x86_64" => X86_ALLOWED_FEATURES,
        "hexagon" => HEXAGON_ALLOWED_FEATURES,
        "mips" | "mips64" => MIPS_ALLOWED_FEATURES,
        "powerpc" | "powerpc64" => POWERPC_ALLOWED_FEATURES,
        "riscv32" | "riscv64" => RISCV_ALLOWED_FEATURES,
        "wasm32" | "wasm64" => WASM_ALLOWED_FEATURES,
        _ => &[],
    }
}

pub(crate) fn provide(providers: &mut Providers) {
    providers.supported_target_features = |tcx, cnum| {
        assert_eq!(cnum, LOCAL_CRATE);
        if tcx.sess.opts.actually_rustdoc {
            // rustdoc needs to be able to document functions that use all the features, so
            // whitelist them all
            all_known_features().map(|(a, b)| (a.to_string(), b)).collect()
        } else {
            supported_target_features(tcx.sess).iter().map(|&(a, b)| (a.to_string(), b)).collect()
        }
    };
}
<commit_msg>Ensure all crypto components (AES, PMULL, SHA1/2) are available on arm/aarch64<commit_after>use rustc_hir::def_id::LOCAL_CRATE;
use rustc_middle::ty::query::Providers;
use rustc_session::Session;
use rustc_span::symbol::sym;
use rustc_span::symbol::Symbol;

// When adding features to the below lists
// check whether they're named already elsewhere in rust
// e.g. in stdarch and whether the given name matches LLVM's
// if it doesn't, to_llvm_feature in llvm_util in rustc_codegen_llvm needs to be adapted

const ARM_ALLOWED_FEATURES: &[(&str, Option<Symbol>)] = &[
    ("aclass", Some(sym::arm_target_feature)),
    ("mclass", Some(sym::arm_target_feature)),
    ("rclass", Some(sym::arm_target_feature)),
    ("dsp", Some(sym::arm_target_feature)),
    ("neon", Some(sym::arm_target_feature)),
    ("crc", Some(sym::arm_target_feature)),
    ("crypto", Some(sym::arm_target_feature)),
    ("aes", Some(sym::arm_target_feature)),
    ("sha2", Some(sym::arm_target_feature)),
    ("v5te", Some(sym::arm_target_feature)),
    ("v6", Some(sym::arm_target_feature)),
    ("v6k", Some(sym::arm_target_feature)),
    ("v6t2", Some(sym::arm_target_feature)),
    ("v7", Some(sym::arm_target_feature)),
    ("v8", Some(sym::arm_target_feature)),
    ("vfp2", Some(sym::arm_target_feature)),
    ("vfp3", Some(sym::arm_target_feature)),
    ("vfp4", Some(sym::arm_target_feature)),
    ("fp-armv8", Some(sym::arm_target_feature)),
    // This is needed for inline assembly, but shouldn't be stabilized as-is
    // since it should be enabled per-function using #[instruction_set], not
    // #[target_feature].
    ("thumb-mode", Some(sym::arm_target_feature)),
];

// Commented features are not available in LLVM 10.0, or have since been renamed
const AARCH64_ALLOWED_FEATURES: &[(&str, Option<Symbol>)] = &[
    // FEAT_AdvSimd
    ("neon", Some(sym::aarch64_target_feature)),
    // FEAT_FP
    ("fp", Some(sym::aarch64_target_feature)),
    // FEAT_FP16
    ("fp16", Some(sym::aarch64_target_feature)),
    // FEAT_SVE
    ("sve", Some(sym::aarch64_target_feature)),
    // FEAT_CRC
    ("crc", Some(sym::aarch64_target_feature)),
    // Cryptographic extension
    ("crypto", Some(sym::aarch64_target_feature)),
    // FEAT_RAS
    ("ras", Some(sym::aarch64_target_feature)),
    // FEAT_LSE
    ("lse", Some(sym::aarch64_target_feature)),
    // FEAT_RDM
    ("rdm", Some(sym::aarch64_target_feature)),
    // FEAT_RCPC
    ("rcpc", Some(sym::aarch64_target_feature)),
    // FEAT_RCPC2
    ("rcpc2", Some(sym::aarch64_target_feature)),
    // FEAT_DotProd
    ("dotprod", Some(sym::aarch64_target_feature)),
    // FEAT_TME
    ("tme", Some(sym::aarch64_target_feature)),
    // FEAT_FHM
    ("fhm", Some(sym::aarch64_target_feature)),
    // FEAT_DIT
    ("dit", Some(sym::aarch64_target_feature)),
    // FEAT_FLAGM
    // ("flagm", Some(sym::aarch64_target_feature)),
    // FEAT_SSBS
    ("ssbs", Some(sym::aarch64_target_feature)),
    // FEAT_SB
    ("sb", Some(sym::aarch64_target_feature)),
    // FEAT_PAUTH
    // ("pauth", Some(sym::aarch64_target_feature)),
    // FEAT_DPB
    ("dpb", Some(sym::aarch64_target_feature)),
    // FEAT_DPB2
    ("dpb2", Some(sym::aarch64_target_feature)),
    // FEAT_SVE2
    ("sve2", Some(sym::aarch64_target_feature)),
    // FEAT_SVE2_AES
    ("sve2-aes", Some(sym::aarch64_target_feature)),
    // FEAT_SVE2_SM4
    ("sve2-sm4", Some(sym::aarch64_target_feature)),
    // FEAT_SVE2_SHA3
    ("sve2-sha3", Some(sym::aarch64_target_feature)),
    // FEAT_SVE2_BitPerm
    ("sve2-bitperm", Some(sym::aarch64_target_feature)),
    // FEAT_FRINTTS
    ("frintts", Some(sym::aarch64_target_feature)),
    // FEAT_I8MM
    // ("i8mm", Some(sym::aarch64_target_feature)),
    // FEAT_F32MM
    // ("f32mm", Some(sym::aarch64_target_feature)),
    // FEAT_F64MM
    // ("f64mm", Some(sym::aarch64_target_feature)),
    // FEAT_BF16
    // ("bf16", Some(sym::aarch64_target_feature)),
    // FEAT_RAND
    ("rand", Some(sym::aarch64_target_feature)),
    // FEAT_BTI
    ("bti", Some(sym::aarch64_target_feature)),
    // FEAT_MTE
    ("mte", Some(sym::aarch64_target_feature)),
    // FEAT_JSCVT
    ("jsconv", Some(sym::aarch64_target_feature)),
    // FEAT_FCMA
    ("fcma", Some(sym::aarch64_target_feature)),
    // FEAT_AES
    ("aes", Some(sym::aarch64_target_feature)),
    // FEAT_SHA1 & FEAT_SHA256
    ("sha2", Some(sym::aarch64_target_feature)),
    // FEAT_SHA512 & FEAT_SHA3
    ("sha3", Some(sym::aarch64_target_feature)),
    // FEAT_SM3 & FEAT_SM4
    ("sm4", Some(sym::aarch64_target_feature)),
    ("v8.1a", Some(sym::aarch64_target_feature)),
    ("v8.2a", Some(sym::aarch64_target_feature)),
    ("v8.3a", Some(sym::aarch64_target_feature)),
    ("v8.4a", Some(sym::aarch64_target_feature)),
    ("v8.5a", Some(sym::aarch64_target_feature)),
    // ("v8.6a", Some(sym::aarch64_target_feature)),
    // ("v8.7a", Some(sym::aarch64_target_feature)),
];

const X86_ALLOWED_FEATURES: &[(&str, Option<Symbol>)] = &[
    ("adx", Some(sym::adx_target_feature)),
    ("aes", None),
    ("avx", None),
    ("avx2", None),
    ("avx512bf16", Some(sym::avx512_target_feature)),
    ("avx512bitalg", Some(sym::avx512_target_feature)),
    ("avx512bw", Some(sym::avx512_target_feature)),
    ("avx512cd", Some(sym::avx512_target_feature)),
    ("avx512dq", Some(sym::avx512_target_feature)),
    ("avx512er", Some(sym::avx512_target_feature)),
    ("avx512f", Some(sym::avx512_target_feature)),
    ("avx512gfni", Some(sym::avx512_target_feature)),
    ("avx512ifma", Some(sym::avx512_target_feature)),
    ("avx512pf", Some(sym::avx512_target_feature)),
    ("avx512vaes", Some(sym::avx512_target_feature)),
    ("avx512vbmi", Some(sym::avx512_target_feature)),
    ("avx512vbmi2", Some(sym::avx512_target_feature)),
    ("avx512vl", Some(sym::avx512_target_feature)),
    ("avx512vnni", Some(sym::avx512_target_feature)),
    ("avx512vp2intersect", Some(sym::avx512_target_feature)),
    ("avx512vpclmulqdq", Some(sym::avx512_target_feature)),
    ("avx512vpopcntdq", Some(sym::avx512_target_feature)),
    ("bmi1", None),
    ("bmi2", None),
    ("cmpxchg16b", Some(sym::cmpxchg16b_target_feature)),
    ("ermsb", Some(sym::ermsb_target_feature)),
    ("f16c", Some(sym::f16c_target_feature)),
    ("fma", None),
    ("fxsr", None),
    ("lzcnt", None),
    ("movbe", Some(sym::movbe_target_feature)),
    ("pclmulqdq", None),
    ("popcnt", None),
    ("rdrand", None),
    ("rdseed", None),
    ("rtm", Some(sym::rtm_target_feature)),
    ("sha", None),
    ("sse", None),
    ("sse2", None),
    ("sse3", None),
    ("sse4.1", None),
    ("sse4.2", None),
    ("sse4a", Some(sym::sse4a_target_feature)),
    ("ssse3", None),
    ("tbm", Some(sym::tbm_target_feature)),
    ("xsave", None),
    ("xsavec", None),
    ("xsaveopt", None),
    ("xsaves", None),
];

const HEXAGON_ALLOWED_FEATURES: &[(&str, Option<Symbol>)] = &[
    ("hvx", Some(sym::hexagon_target_feature)),
    ("hvx-length128b", Some(sym::hexagon_target_feature)),
];

const POWERPC_ALLOWED_FEATURES: &[(&str, Option<Symbol>)] = &[
    ("altivec", Some(sym::powerpc_target_feature)),
    ("power8-altivec", Some(sym::powerpc_target_feature)),
    ("power9-altivec", Some(sym::powerpc_target_feature)),
    ("power8-vector", Some(sym::powerpc_target_feature)),
    ("power9-vector", Some(sym::powerpc_target_feature)),
    ("vsx", Some(sym::powerpc_target_feature)),
];

const MIPS_ALLOWED_FEATURES: &[(&str, Option<Symbol>)] =
    &[("fp64", Some(sym::mips_target_feature)), ("msa", Some(sym::mips_target_feature))];

const RISCV_ALLOWED_FEATURES: &[(&str, Option<Symbol>)] = &[
    ("m", Some(sym::riscv_target_feature)),
    ("a", Some(sym::riscv_target_feature)),
    ("c", Some(sym::riscv_target_feature)),
    ("f", Some(sym::riscv_target_feature)),
    ("d", Some(sym::riscv_target_feature)),
    ("e", Some(sym::riscv_target_feature)),
];

const WASM_ALLOWED_FEATURES: &[(&str, Option<Symbol>)] = &[
    ("simd128", Some(sym::wasm_target_feature)),
    ("atomics", Some(sym::wasm_target_feature)),
    ("nontrapping-fptoint", Some(sym::wasm_target_feature)),
];

/// When rustdoc is running, provide a list of all known features so that all their respective
/// primitives may be documented.
///
/// IMPORTANT: If you're adding another feature list above, make sure to add it to this iterator!
pub fn all_known_features() -> impl Iterator<Item = (&'static str, Option<Symbol>)> {
    std::iter::empty()
        .chain(ARM_ALLOWED_FEATURES.iter())
        .chain(AARCH64_ALLOWED_FEATURES.iter())
        .chain(X86_ALLOWED_FEATURES.iter())
        .chain(HEXAGON_ALLOWED_FEATURES.iter())
        .chain(POWERPC_ALLOWED_FEATURES.iter())
        .chain(MIPS_ALLOWED_FEATURES.iter())
        .chain(RISCV_ALLOWED_FEATURES.iter())
        .chain(WASM_ALLOWED_FEATURES.iter())
        .cloned()
}

pub fn supported_target_features(sess: &Session) -> &'static [(&'static str, Option<Symbol>)] {
    match &*sess.target.arch {
        "arm" => ARM_ALLOWED_FEATURES,
        "aarch64" => AARCH64_ALLOWED_FEATURES,
        "x86" | "x86_64" => X86_ALLOWED_FEATURES,
        "hexagon" => HEXAGON_ALLOWED_FEATURES,
        "mips" | "mips64" => MIPS_ALLOWED_FEATURES,
        "powerpc" | "powerpc64" => POWERPC_ALLOWED_FEATURES,
        "riscv32" | "riscv64" => RISCV_ALLOWED_FEATURES,
        "wasm32" | "wasm64" => WASM_ALLOWED_FEATURES,
        _ => &[],
    }
}

pub(crate) fn provide(providers: &mut Providers) {
    providers.supported_target_features = |tcx, cnum| {
        assert_eq!(cnum, LOCAL_CRATE);
        if tcx.sess.opts.actually_rustdoc {
            // rustdoc needs to be able to document functions that use all the features, so
            // whitelist them all
            all_known_features().map(|(a, b)| (a.to_string(), b)).collect()
        } else {
            supported_target_features(tcx.sess).iter().map(|&(a, b)| (a.to_string(), b)).collect()
        }
    };
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

<%namespace name="helpers" file="/helpers.mako.rs" />

<% data.new_style_struct("SVG", inherited=False, gecko_name="SVGReset") %>

${helpers.single_keyword(
    "dominant-baseline",
    """auto use-script no-change reset-size ideographic alphabetic hanging
    mathematical central middle text-after-edge text-before-edge""",
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG11/text.html#DominantBaselineProperty",
)}

${helpers.single_keyword(
    "vector-effect",
    "none non-scaling-stroke",
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVGTiny12/painting.html#VectorEffectProperty",
)}

// Section 13 - Gradients and Patterns

${helpers.predefined_type(
    "stop-color",
    "Color",
    "RGBA::new(0, 0, 0, 255).into()",
    products="gecko",
    animation_value_type="AnimatedRGBA",
    spec="https://www.w3.org/TR/SVGTiny12/painting.html#StopColorProperty",
)}

${helpers.predefined_type(
    "stop-opacity",
    "Opacity",
    "1.0",
    products="gecko",
    animation_value_type="ComputedValue",
    spec="https://svgwg.org/svg2-draft/pservers.html#StopOpacityProperty",
)}

// Section 15 - Filter Effects

${helpers.predefined_type(
    "flood-color",
    "Color",
    "RGBA::new(0, 0, 0, 255).into()",
    products="gecko",
    animation_value_type="AnimatedColor",
    spec="https://www.w3.org/TR/SVG/filters.html#FloodColorProperty",
)}

${helpers.predefined_type(
    "flood-opacity",
    "Opacity",
    "1.0",
    products="gecko",
    animation_value_type="ComputedValue",
    spec="https://drafts.fxtf.org/filter-effects/#FloodOpacityProperty",
)}

${helpers.predefined_type(
    "lighting-color",
    "Color",
    "RGBA::new(255, 255, 255, 255).into()",
    products="gecko",
    animation_value_type="AnimatedColor",
    spec="https://www.w3.org/TR/SVG/filters.html#LightingColorProperty",
)}

// CSS Masking Module Level 1
// https://drafts.fxtf.org/css-masking
${helpers.single_keyword(
    "mask-type",
    "luminance alpha",
    products="gecko",
    animation_value_type="discrete",
    spec="https://drafts.fxtf.org/css-masking/#propdef-mask-type",
)}

${helpers.predefined_type(
    "clip-path",
    "basic_shape::ClippingShape",
    "generics::basic_shape::ShapeSource::None",
    products="gecko",
    animation_value_type="basic_shape::ClippingShape",
    flags="CREATES_STACKING_CONTEXT",
    spec="https://drafts.fxtf.org/css-masking/#propdef-clip-path",
)}

${helpers.single_keyword(
    "mask-mode",
    "match-source alpha luminance",
    gecko_enum_prefix="StyleMaskMode",
    vector=True,
    products="gecko",
    animation_value_type="discrete",
    spec="https://drafts.fxtf.org/css-masking/#propdef-mask-mode",
)}

${helpers.predefined_type(
    "mask-repeat",
    "BackgroundRepeat",
    "computed::BackgroundRepeat::repeat()",
    initial_specified_value="specified::BackgroundRepeat::repeat()",
    products="gecko",
    extra_prefixes="webkit",
    animation_value_type="discrete",
    spec="https://drafts.fxtf.org/css-masking/#propdef-mask-repeat",
    vector=True,
)}

% for (axis, direction) in [("x", "Horizontal"), ("y", "Vertical")]:
    ${helpers.predefined_type(
        "mask-position-" + axis,
        "position::" + direction + "Position",
        "computed::LengthPercentage::zero()",
        products="gecko",
        extra_prefixes="webkit",
        initial_specified_value="specified::PositionComponent::Center",
        spec="https://drafts.fxtf.org/css-masking/#propdef-mask-position",
        animation_value_type="ComputedValue",
        vector_animation_type="repeatable_list",
        vector=True,
    )}
% endfor

${helpers.single_keyword(
    "mask-clip",
    "border-box content-box padding-box",
    extra_gecko_values="fill-box stroke-box view-box no-clip",
    vector=True,
    products="gecko",
    extra_prefixes="webkit",
    gecko_enum_prefix="StyleGeometryBox",
    gecko_inexhaustive=True,
    animation_value_type="discrete",
    spec="https://drafts.fxtf.org/css-masking/#propdef-mask-clip",
)}

${helpers.single_keyword(
    "mask-origin",
    "border-box content-box padding-box",
    extra_gecko_values="fill-box stroke-box view-box",
    vector=True,
    products="gecko",
    extra_prefixes="webkit",
    gecko_enum_prefix="StyleGeometryBox",
    gecko_inexhaustive=True,
    animation_value_type="discrete",
    spec="https://drafts.fxtf.org/css-masking/#propdef-mask-origin",
)}

${helpers.predefined_type(
    "mask-size",
    "background::BackgroundSize",
    "computed::BackgroundSize::auto()",
    initial_specified_value="specified::BackgroundSize::auto()",
    products="gecko",
    extra_prefixes="webkit",
    spec="https://drafts.fxtf.org/css-masking/#propdef-mask-size",
    animation_value_type="MaskSizeList",
    vector=True,
    vector_animation_type="repeatable_list",
)}

${helpers.single_keyword(
    "mask-composite",
    "add subtract intersect exclude",
    vector=True,
    products="gecko",
    extra_prefixes="webkit",
    animation_value_type="discrete",
    spec="https://drafts.fxtf.org/css-masking/#propdef-mask-composite",
)}

${helpers.predefined_type(
    "mask-image",
    "ImageLayer",
    initial_value="computed::ImageLayer::none()",
    initial_specified_value="specified::ImageLayer::none()",
    parse_method="parse_with_cors_anonymous",
    spec="https://drafts.fxtf.org/css-masking/#propdef-mask-image",
    vector=True,
    products="gecko",
    extra_prefixes="webkit",
    animation_value_type="discrete",
    flags="CREATES_STACKING_CONTEXT",
)}

${helpers.predefined_type(
    "x",
    "LengthPercentage",
    "computed::LengthPercentage::zero()",
    products="gecko",
    animation_value_type="ComputedValue",
    spec="https://svgwg.org/svg2-draft/geometry.html#X",
)}

${helpers.predefined_type(
    "y",
    "LengthPercentage",
    "computed::LengthPercentage::zero()",
    products="gecko",
    animation_value_type="ComputedValue",
    spec="https://svgwg.org/svg2-draft/geometry.html#Y",
)}

${helpers.predefined_type(
    "cx",
    "LengthPercentage",
    "computed::LengthPercentage::zero()",
    products="gecko",
    animation_value_type="ComputedValue",
    spec="https://svgwg.org/svg2-draft/geometry.html#CX",
)}

${helpers.predefined_type(
    "cy",
    "LengthPercentage",
    "computed::LengthPercentage::zero()",
    products="gecko",
    animation_value_type="ComputedValue",
    spec="https://svgwg.org/svg2-draft/geometry.html#CY",
)}

${helpers.predefined_type(
    "rx",
    "NonNegativeLengthPercentageOrAuto",
    "computed::NonNegativeLengthPercentageOrAuto::auto()",
    products="gecko",
    animation_value_type="LengthPercentageOrAuto",
    spec="https://svgwg.org/svg2-draft/geometry.html#RX",
)}

${helpers.predefined_type(
    "ry",
    "NonNegativeLengthPercentageOrAuto",
    "computed::NonNegativeLengthPercentageOrAuto::auto()",
    products="gecko",
    animation_value_type="LengthPercentageOrAuto",
    spec="https://svgwg.org/svg2-draft/geometry.html#RY",
)}

${helpers.predefined_type(
    "r",
    "NonNegativeLengthPercentage",
    "computed::NonNegativeLengthPercentage::zero()",
    products="gecko",
    animation_value_type="LengthPercentage",
    spec="https://svgwg.org/svg2-draft/geometry.html#R",
)}
<commit_msg>style: Remove dominant-baseline values that no longer exist.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

<%namespace name="helpers" file="/helpers.mako.rs" />

<% data.new_style_struct("SVG", inherited=False, gecko_name="SVGReset") %>

${helpers.single_keyword(
    "dominant-baseline",
    """auto ideographic alphabetic hanging mathematical central middle
       text-after-edge text-before-edge""",
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVG11/text.html#DominantBaselineProperty",
)}

${helpers.single_keyword(
    "vector-effect",
    "none non-scaling-stroke",
    products="gecko",
    animation_value_type="discrete",
    spec="https://www.w3.org/TR/SVGTiny12/painting.html#VectorEffectProperty",
)}

// Section 13 - Gradients and Patterns

${helpers.predefined_type(
    "stop-color",
    "Color",
    "RGBA::new(0, 0, 0, 255).into()",
    products="gecko",
    animation_value_type="AnimatedRGBA",
    spec="https://www.w3.org/TR/SVGTiny12/painting.html#StopColorProperty",
)}

${helpers.predefined_type(
    "stop-opacity",
    "Opacity",
    "1.0",
    products="gecko",
    animation_value_type="ComputedValue",
    spec="https://svgwg.org/svg2-draft/pservers.html#StopOpacityProperty",
)}

// Section 15 - Filter Effects

${helpers.predefined_type(
    "flood-color",
    "Color",
    "RGBA::new(0, 0, 0, 255).into()",
    products="gecko",
    animation_value_type="AnimatedColor",
    spec="https://www.w3.org/TR/SVG/filters.html#FloodColorProperty",
)}

${helpers.predefined_type(
    "flood-opacity",
    "Opacity",
    "1.0",
    products="gecko",
    animation_value_type="ComputedValue",
    spec="https://drafts.fxtf.org/filter-effects/#FloodOpacityProperty",
)}

${helpers.predefined_type(
    "lighting-color",
    "Color",
    "RGBA::new(255, 255, 255, 255).into()",
    products="gecko",
    animation_value_type="AnimatedColor",
    spec="https://www.w3.org/TR/SVG/filters.html#LightingColorProperty",
)}

// CSS Masking Module Level 1
// https://drafts.fxtf.org/css-masking
${helpers.single_keyword(
    "mask-type",
    "luminance alpha",
    products="gecko",
    animation_value_type="discrete",
    spec="https://drafts.fxtf.org/css-masking/#propdef-mask-type",
)}

${helpers.predefined_type(
    "clip-path",
    "basic_shape::ClippingShape",
    "generics::basic_shape::ShapeSource::None",
    products="gecko",
    animation_value_type="basic_shape::ClippingShape",
    flags="CREATES_STACKING_CONTEXT",
    spec="https://drafts.fxtf.org/css-masking/#propdef-clip-path",
)}

${helpers.single_keyword(
    "mask-mode",
    "match-source alpha luminance",
    gecko_enum_prefix="StyleMaskMode",
    vector=True,
    products="gecko",
    animation_value_type="discrete",
    spec="https://drafts.fxtf.org/css-masking/#propdef-mask-mode",
)}

${helpers.predefined_type(
    "mask-repeat",
    "BackgroundRepeat",
    "computed::BackgroundRepeat::repeat()",
    initial_specified_value="specified::BackgroundRepeat::repeat()",
    products="gecko",
    extra_prefixes="webkit",
    animation_value_type="discrete",
    spec="https://drafts.fxtf.org/css-masking/#propdef-mask-repeat",
    vector=True,
)}

% for (axis, direction) in [("x", "Horizontal"), ("y", "Vertical")]:
    ${helpers.predefined_type(
        "mask-position-" + axis,
        "position::" + direction + "Position",
        "computed::LengthPercentage::zero()",
        products="gecko",
        extra_prefixes="webkit",
        initial_specified_value="specified::PositionComponent::Center",
        spec="https://drafts.fxtf.org/css-masking/#propdef-mask-position",
        animation_value_type="ComputedValue",
        vector_animation_type="repeatable_list",
        vector=True,
    )}
% endfor

${helpers.single_keyword(
    "mask-clip",
    "border-box content-box padding-box",
    extra_gecko_values="fill-box stroke-box view-box no-clip",
    vector=True,
    products="gecko",
    extra_prefixes="webkit",
    gecko_enum_prefix="StyleGeometryBox",
    gecko_inexhaustive=True,
    animation_value_type="discrete",
    spec="https://drafts.fxtf.org/css-masking/#propdef-mask-clip",
)}

${helpers.single_keyword(
    "mask-origin",
    "border-box content-box padding-box",
    extra_gecko_values="fill-box stroke-box view-box",
    vector=True,
    products="gecko",
    extra_prefixes="webkit",
    gecko_enum_prefix="StyleGeometryBox",
    gecko_inexhaustive=True,
    animation_value_type="discrete",
    spec="https://drafts.fxtf.org/css-masking/#propdef-mask-origin",
)}

${helpers.predefined_type(
    "mask-size",
    "background::BackgroundSize",
    "computed::BackgroundSize::auto()",
    initial_specified_value="specified::BackgroundSize::auto()",
    products="gecko",
    extra_prefixes="webkit",
    spec="https://drafts.fxtf.org/css-masking/#propdef-mask-size",
    animation_value_type="MaskSizeList",
    vector=True,
    vector_animation_type="repeatable_list",
)}

${helpers.single_keyword(
    "mask-composite",
    "add subtract intersect exclude",
    vector=True,
    products="gecko",
    extra_prefixes="webkit",
    animation_value_type="discrete",
    spec="https://drafts.fxtf.org/css-masking/#propdef-mask-composite",
)}

${helpers.predefined_type(
    "mask-image",
    "ImageLayer",
    initial_value="computed::ImageLayer::none()",
    initial_specified_value="specified::ImageLayer::none()",
    parse_method="parse_with_cors_anonymous",
    spec="https://drafts.fxtf.org/css-masking/#propdef-mask-image",
    vector=True,
    products="gecko",
    extra_prefixes="webkit",
    animation_value_type="discrete",
    flags="CREATES_STACKING_CONTEXT",
)}

${helpers.predefined_type(
    "x",
    "LengthPercentage",
    "computed::LengthPercentage::zero()",
    products="gecko",
    animation_value_type="ComputedValue",
    spec="https://svgwg.org/svg2-draft/geometry.html#X",
)}

${helpers.predefined_type(
    "y",
    "LengthPercentage",
    "computed::LengthPercentage::zero()",
    products="gecko",
    animation_value_type="ComputedValue",
    spec="https://svgwg.org/svg2-draft/geometry.html#Y",
)}

${helpers.predefined_type(
    "cx",
    "LengthPercentage",
    "computed::LengthPercentage::zero()",
    products="gecko",
    animation_value_type="ComputedValue",
    spec="https://svgwg.org/svg2-draft/geometry.html#CX",
)}

${helpers.predefined_type(
    "cy",
    "LengthPercentage",
    "computed::LengthPercentage::zero()",
    products="gecko",
    animation_value_type="ComputedValue",
    spec="https://svgwg.org/svg2-draft/geometry.html#CY",
)}

${helpers.predefined_type(
    "rx",
    "NonNegativeLengthPercentageOrAuto",
    "computed::NonNegativeLengthPercentageOrAuto::auto()",
    products="gecko",
    animation_value_type="LengthPercentageOrAuto",
    spec="https://svgwg.org/svg2-draft/geometry.html#RX",
)}

${helpers.predefined_type(
    "ry",
    "NonNegativeLengthPercentageOrAuto",
    "computed::NonNegativeLengthPercentageOrAuto::auto()",
    products="gecko",
    animation_value_type="LengthPercentageOrAuto",
    spec="https://svgwg.org/svg2-draft/geometry.html#RY",
)}

${helpers.predefined_type(
    "r",
    "NonNegativeLengthPercentage",
    "computed::NonNegativeLengthPercentage::zero()",
    products="gecko",
    animation_value_type="LengthPercentage",
    spec="https://svgwg.org/svg2-draft/geometry.html#R",
)}
<|endoftext|>


<commit_before>use sink::Sink;

use {Poll, StartSend};

/// Sink for the `Sink::sink_map_err` combinator.
#[derive(Debug)]
#[must_use = "sinks do nothing unless polled"]
pub struct SinkMapErr<S, F> {
    sink: S,
    f: Option<F>,
}

pub fn new<S, F>(s: S, f: F) -> SinkMapErr<S, F> {
    SinkMapErr { sink: s, f: Some(f) }
}

impl<S, E> SinkMapErr<S, E> {
    /// Get a shared reference to the inner sink.
    pub fn get_ref(&self) -> &S {
        &self.sink
    }

    /// Get a mutable reference to the inner sink.
    pub fn get_mut(&mut self) -> &mut S {
        &mut self.sink
    }

    /// Consumes this combinator, returning the underlying sink.
    ///
    /// Note that this may discard intermediate state of this combinator, so
    /// care should be taken to avoid losing resources when this is called.
    pub fn into_inner(self) -> S {
        self.sink
    }
}

impl<S, F, E> Sink for SinkMapErr<S, F>
    where S: Sink,
          F: FnOnce(S::SinkError) -> E,
{
    type SinkItem = S::SinkItem;
    type SinkError = E;

    fn start_send(&mut self, item: Self::SinkItem) -> StartSend<Self::SinkItem, Self::SinkError> {
        self.sink.start_send(item).map_err(|e| self.f.take().expect("cannot use MapErr after an error")(e))
    }

    fn poll_complete(&mut self) -> Poll<(), Self::SinkError> {
        self.sink.poll_complete().map_err(|e| self.f.take().expect("cannot use MapErr after an error")(e))
    }

    fn close(&mut self) -> Poll<(), Self::SinkError> {
        self.sink.close().map_err(|e| self.f.take().expect("cannot use MapErr after an error")(e))
    }
}
<commit_msg>Forward Stream through `SinkMapErr`<commit_after>use sink::Sink;

use {Poll, StartSend, Stream};

/// Sink for the `Sink::sink_map_err` combinator.
#[derive(Debug)]
#[must_use = "sinks do nothing unless polled"]
pub struct SinkMapErr<S, F> {
    sink: S,
    f: Option<F>,
}

pub fn new<S, F>(s: S, f: F) -> SinkMapErr<S, F> {
    SinkMapErr { sink: s, f: Some(f) }
}

impl<S, E> SinkMapErr<S, E> {
    /// Get a shared reference to the inner sink.
    pub fn get_ref(&self) -> &S {
        &self.sink
    }

    /// Get a mutable reference to the inner sink.
    pub fn get_mut(&mut self) -> &mut S {
        &mut self.sink
    }

    /// Consumes this combinator, returning the underlying sink.
    ///
    /// Note that this may discard intermediate state of this combinator, so
    /// care should be taken to avoid losing resources when this is called.
    pub fn into_inner(self) -> S {
        self.sink
    }
}

impl<S, F, E> Sink for SinkMapErr<S, F>
    where S: Sink,
          F: FnOnce(S::SinkError) -> E,
{
    type SinkItem = S::SinkItem;
    type SinkError = E;

    fn start_send(&mut self, item: Self::SinkItem) -> StartSend<Self::SinkItem, Self::SinkError> {
        self.sink.start_send(item).map_err(|e| self.f.take().expect("cannot use MapErr after an error")(e))
    }

    fn poll_complete(&mut self) -> Poll<(), Self::SinkError> {
        self.sink.poll_complete().map_err(|e| self.f.take().expect("cannot use MapErr after an error")(e))
    }

    fn close(&mut self) -> Poll<(), Self::SinkError> {
        self.sink.close().map_err(|e| self.f.take().expect("cannot use MapErr after an error")(e))
    }
}

impl<S: Stream, F> Stream for SinkMapErr<S, F> {
    type Item = S::Item;
    type Error = S::Error;

    fn poll(&mut self) -> Poll<Option<S::Item>, S::Error> {
        self.sink.poll()
    }
}
<|endoftext|>


<commit_before>use std::path::PathBuf;

use glob::glob;
use glob::Paths;
use glob::PatternError;

use storage::file::id::FileID;
use storage::file::id_type::FileIDType;
use storage::file::hash::FileHash;
use module::Module;

/*
 * A path represents either a GLOB ("/tmp/store/module-*-*.imag" for example) or a full path
 *
 * It can be used to generate a File or iterate over some files
 *
 */
struct Path<'a> {

    /*
     * The base part ("/tmp/")
     */
    base: PathBuf,

    /*
     * The store part ("/store/")
     */
    store: PathBuf,

    /*
     * The module
     */
    module: &'a Module<'a>,

    /*
     * The ID
     */
    idtype: Option<FileIDType>,
    idhash: Option<FileHash>,
    id:     Option<FileID>,

}

impl<'a> Path<'a> {

    fn new(base: PathBuf, store: PathBuf, m: &'a Module<'a>, id: FileID) -> Path<'a> {
        Path {
            base:   base,
            store:  store,
            module: m,
            idtype: Some(id.get_type()),
            idhash: Some(id.get_id()),
            id:     Some(id),
        }
    }

    fn new_with_idtype(base: PathBuf, store: PathBuf, m: &'a Module<'a>, id: FileIDType) -> Path<'a> {
        Path {
            base:   base,
            store:  store,
            module: m,
            idtype: Some(id),
            idhash: None,
            id:     None,
        }
    }

    fn new_with_idhash(base: PathBuf, store: PathBuf, m: &'a Module<'a>, id: FileHash) -> Path<'a> {
        Path {
            base:   base,
            store:  store,
            module: m,
            idtype: None,
            idhash: Some(id),
            id:     None,
        }
    }

}

/*
 * Transform Path into str, so we can call glob() on it
 */
impl<'a> Into<&'a str> for Path<'a> {

    fn into(self) -> &'a str {
        let mut s = self.base.clone();
        s.push(self.store.clone());
        s.push(self.module.name());
        if self.id.is_some() {
            let idstr : String = self.id.unwrap().into();
            s.push(idstr);
        } else {
            s.push("*");
        }
        s.set_extension("imag");
        s.to_str().unwrap_or("")
    }
}

impl<'a> Into<Result<Paths, PatternError>> for Path<'a> {

    fn into(self) -> Result<Paths, PatternError> {
        let s : &str = self.into();
        glob(s)
    }

}
<commit_msg>Fixup Into<str> for Path -> Impl as Into<String> for Path<commit_after>use std::path::PathBuf;

use glob::glob;
use glob::Paths;
use glob::PatternError;

use storage::file::id::FileID;
use storage::file::id_type::FileIDType;
use storage::file::hash::FileHash;
use module::Module;

/*
 * A path represents either a GLOB ("/tmp/store/module-*-*.imag" for example) or a full path
 *
 * It can be used to generate a File or iterate over some files
 *
 */
struct Path<'a> {

    /*
     * The base part ("/tmp/")
     */
    base: PathBuf,

    /*
     * The store part ("/store/")
     */
    store: PathBuf,

    /*
     * The module
     */
    module: &'a Module<'a>,

    /*
     * The ID
     */
    idtype: Option<FileIDType>,
    idhash: Option<FileHash>,
    id:     Option<FileID>,

}

impl<'a> Path<'a> {

    fn new(base: PathBuf, store: PathBuf, m: &'a Module<'a>, id: FileID) -> Path<'a> {
        Path {
            base:   base,
            store:  store,
            module: m,
            idtype: Some(id.get_type()),
            idhash: Some(id.get_id()),
            id:     Some(id),
        }
    }

    fn new_with_idtype(base: PathBuf, store: PathBuf, m: &'a Module<'a>, id: FileIDType) -> Path<'a> {
        Path {
            base:   base,
            store:  store,
            module: m,
            idtype: Some(id),
            idhash: None,
            id:     None,
        }
    }

    fn new_with_idhash(base: PathBuf, store: PathBuf, m: &'a Module<'a>, id: FileHash) -> Path<'a> {
        Path {
            base:   base,
            store:  store,
            module: m,
            idtype: None,
            idhash: Some(id),
            id:     None,
        }
    }

}

/*
 * Transform Path into str, so we can call glob() on it
 */
impl<'a> Into<String> for Path<'a> {

    fn into(self) -> String {
        let mut s = self.base.clone();
        s.push(self.store.clone());
        s.push(self.module.name());
        if self.id.is_some() {
            let idstr : String = self.id.unwrap().into();
            s.push(idstr);
        } else {
            s.push("*");
        }
        s.set_extension("imag");
        s.to_str().unwrap_or("").into()
    }
}

impl<'a> Into<Result<Paths, PatternError>> for Path<'a> {

    fn into(self) -> Result<Paths, PatternError> {
        let s : String = self.into();
        glob(&s[..])
    }

}
<|endoftext|>


<commit_before>#![allow(bad_style, missing_docs, unreachable_pub)]
#![cfg_attr(rustfmt, rustfmt_skip)]
//! Generated from grammar.ron
use tree::SyntaxInfo;

/// The kind of syntax node, e.g. `IDENT`, `USE_KW`, or `STRUCT_DEF`.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u32)]
pub enum SyntaxKind {
    USE_KW,
    FN_KW,
    STRUCT_KW,
    ENUM_KW,
    TRAIT_KW,
    IMPL_KW,
    TRUE_KW,
    FALSE_KW,
    AS_KW,
    EXTERN_KW,
    CRATE_KW,
    MOD_KW,
    PUB_KW,
    SELF_KW,
    SUPER_KW,
    IN_KW,
    WHERE_KW,
    ERROR,
    IDENT,
    UNDERSCORE,
    WHITESPACE,
    INT_NUMBER,
    FLOAT_NUMBER,
    SEMI,
    COMMA,
    DOT,
    DOTDOT,
    DOTDOTDOT,
    DOTDOTEQ,
    L_PAREN,
    R_PAREN,
    L_CURLY,
    R_CURLY,
    L_BRACK,
    R_BRACK,
    L_ANGLE,
    R_ANGLE,
    AT,
    POUND,
    TILDE,
    QUESTION,
    COLON,
    COLONCOLON,
    DOLLAR,
    EQ,
    EQEQ,
    FAT_ARROW,
    NEQ,
    EXCL,
    LIFETIME,
    CHAR,
    BYTE,
    STRING,
    RAW_STRING,
    BYTE_STRING,
    RAW_BYTE_STRING,
    PLUS,
    MINUS,
    STAR,
    SLASH,
    CARET,
    PERCENT,
    AMPERSAND,
    PIPE,
    THIN_ARROW,
    COMMENT,
    DOC_COMMENT,
    SHEBANG,
    FILE,
    STRUCT_ITEM,
    NAMED_FIELD,
    POS_FIELD,
    FN_ITEM,
    EXTERN_CRATE_ITEM,
    ATTR,
    META_ITEM,
    MOD_ITEM,
    USE_ITEM,
    USE_TREE,
    PATH,
    PATH_SEGMENT,
    LITERAL,
    ALIAS,
    VISIBILITY,

    // Technical SyntaxKinds: they appear temporally during parsing,
    // but never end up in the final tree
    #[doc(hidden)]
    TOMBSTONE,
    #[doc(hidden)]
    EOF,
}
pub(crate) use self::SyntaxKind::*;

impl SyntaxKind {
    pub(crate) fn info(self) -> &'static SyntaxInfo {
        match self {
            USE_KW => &SyntaxInfo { name: "USE_KW" },
            FN_KW => &SyntaxInfo { name: "FN_KW" },
            STRUCT_KW => &SyntaxInfo { name: "STRUCT_KW" },
            ENUM_KW => &SyntaxInfo { name: "ENUM_KW" },
            TRAIT_KW => &SyntaxInfo { name: "TRAIT_KW" },
            IMPL_KW => &SyntaxInfo { name: "IMPL_KW" },
            TRUE_KW => &SyntaxInfo { name: "TRUE_KW" },
            FALSE_KW => &SyntaxInfo { name: "FALSE_KW" },
            AS_KW => &SyntaxInfo { name: "AS_KW" },
            EXTERN_KW => &SyntaxInfo { name: "EXTERN_KW" },
            CRATE_KW => &SyntaxInfo { name: "CRATE_KW" },
            MOD_KW => &SyntaxInfo { name: "MOD_KW" },
            PUB_KW => &SyntaxInfo { name: "PUB_KW" },
            SELF_KW => &SyntaxInfo { name: "SELF_KW" },
            SUPER_KW => &SyntaxInfo { name: "SUPER_KW" },
            IN_KW => &SyntaxInfo { name: "IN_KW" },
            WHERE_KW => &SyntaxInfo { name: "WHERE_KW" },
            ERROR => &SyntaxInfo { name: "ERROR" },
            IDENT => &SyntaxInfo { name: "IDENT" },
            UNDERSCORE => &SyntaxInfo { name: "UNDERSCORE" },
            WHITESPACE => &SyntaxInfo { name: "WHITESPACE" },
            INT_NUMBER => &SyntaxInfo { name: "INT_NUMBER" },
            FLOAT_NUMBER => &SyntaxInfo { name: "FLOAT_NUMBER" },
            SEMI => &SyntaxInfo { name: "SEMI" },
            COMMA => &SyntaxInfo { name: "COMMA" },
            DOT => &SyntaxInfo { name: "DOT" },
            DOTDOT => &SyntaxInfo { name: "DOTDOT" },
            DOTDOTDOT => &SyntaxInfo { name: "DOTDOTDOT" },
            DOTDOTEQ => &SyntaxInfo { name: "DOTDOTEQ" },
            L_PAREN => &SyntaxInfo { name: "L_PAREN" },
            R_PAREN => &SyntaxInfo { name: "R_PAREN" },
            L_CURLY => &SyntaxInfo { name: "L_CURLY" },
            R_CURLY => &SyntaxInfo { name: "R_CURLY" },
            L_BRACK => &SyntaxInfo { name: "L_BRACK" },
            R_BRACK => &SyntaxInfo { name: "R_BRACK" },
            L_ANGLE => &SyntaxInfo { name: "L_ANGLE" },
            R_ANGLE => &SyntaxInfo { name: "R_ANGLE" },
            AT => &SyntaxInfo { name: "AT" },
            POUND => &SyntaxInfo { name: "POUND" },
            TILDE => &SyntaxInfo { name: "TILDE" },
            QUESTION => &SyntaxInfo { name: "QUESTION" },
            COLON => &SyntaxInfo { name: "COLON" },
            COLONCOLON => &SyntaxInfo { name: "COLONCOLON" },
            DOLLAR => &SyntaxInfo { name: "DOLLAR" },
            EQ => &SyntaxInfo { name: "EQ" },
            EQEQ => &SyntaxInfo { name: "EQEQ" },
            FAT_ARROW => &SyntaxInfo { name: "FAT_ARROW" },
            NEQ => &SyntaxInfo { name: "NEQ" },
            EXCL => &SyntaxInfo { name: "EXCL" },
            LIFETIME => &SyntaxInfo { name: "LIFETIME" },
            CHAR => &SyntaxInfo { name: "CHAR" },
            BYTE => &SyntaxInfo { name: "BYTE" },
            STRING => &SyntaxInfo { name: "STRING" },
            RAW_STRING => &SyntaxInfo { name: "RAW_STRING" },
            BYTE_STRING => &SyntaxInfo { name: "BYTE_STRING" },
            RAW_BYTE_STRING => &SyntaxInfo { name: "RAW_BYTE_STRING" },
            PLUS => &SyntaxInfo { name: "PLUS" },
            MINUS => &SyntaxInfo { name: "MINUS" },
            STAR => &SyntaxInfo { name: "STAR" },
            SLASH => &SyntaxInfo { name: "SLASH" },
            CARET => &SyntaxInfo { name: "CARET" },
            PERCENT => &SyntaxInfo { name: "PERCENT" },
            AMPERSAND => &SyntaxInfo { name: "AMPERSAND" },
            PIPE => &SyntaxInfo { name: "PIPE" },
            THIN_ARROW => &SyntaxInfo { name: "THIN_ARROW" },
            COMMENT => &SyntaxInfo { name: "COMMENT" },
            DOC_COMMENT => &SyntaxInfo { name: "DOC_COMMENT" },
            SHEBANG => &SyntaxInfo { name: "SHEBANG" },
            FILE => &SyntaxInfo { name: "FILE" },
            STRUCT_ITEM => &SyntaxInfo { name: "STRUCT_ITEM" },
            NAMED_FIELD => &SyntaxInfo { name: "NAMED_FIELD" },
            POS_FIELD => &SyntaxInfo { name: "POS_FIELD" },
            FN_ITEM => &SyntaxInfo { name: "FN_ITEM" },
            EXTERN_CRATE_ITEM => &SyntaxInfo { name: "EXTERN_CRATE_ITEM" },
            ATTR => &SyntaxInfo { name: "ATTR" },
            META_ITEM => &SyntaxInfo { name: "META_ITEM" },
            MOD_ITEM => &SyntaxInfo { name: "MOD_ITEM" },
            USE_ITEM => &SyntaxInfo { name: "USE_ITEM" },
            USE_TREE => &SyntaxInfo { name: "USE_TREE" },
            PATH => &SyntaxInfo { name: "PATH" },
            PATH_SEGMENT => &SyntaxInfo { name: "PATH_SEGMENT" },
            LITERAL => &SyntaxInfo { name: "LITERAL" },
            ALIAS => &SyntaxInfo { name: "ALIAS" },
            VISIBILITY => &SyntaxInfo { name: "VISIBILITY" },

            TOMBSTONE => &SyntaxInfo { name: "TOMBSTONE" },
            EOF => &SyntaxInfo { name: "EOF" },
        }
    }
}

pub(crate) fn ident_to_keyword(ident: &str) -> Option<SyntaxKind> {
    match ident {
        "use" => Some(USE_KW),
        "fn" => Some(FN_KW),
        "struct" => Some(STRUCT_KW),
        "enum" => Some(ENUM_KW),
        "trait" => Some(TRAIT_KW),
        "impl" => Some(IMPL_KW),
        "true" => Some(TRUE_KW),
        "false" => Some(FALSE_KW),
        "as" => Some(AS_KW),
        "extern" => Some(EXTERN_KW),
        "crate" => Some(CRATE_KW),
        "mod" => Some(MOD_KW),
        "pub" => Some(PUB_KW),
        "self" => Some(SELF_KW),
        "super" => Some(SUPER_KW),
        "in" => Some(IN_KW),
        "where" => Some(WHERE_KW),
        _ => None,
    }
}
<commit_msg>Drop `repr(u32)` from SyntaxKind<commit_after>#![allow(bad_style, missing_docs, unreachable_pub)]
#![cfg_attr(rustfmt, rustfmt_skip)]
//! Generated from grammar.ron
use tree::SyntaxInfo;

/// The kind of syntax node, e.g. `IDENT`, `USE_KW`, or `STRUCT_DEF`.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum SyntaxKind {
    USE_KW,
    FN_KW,
    STRUCT_KW,
    ENUM_KW,
    TRAIT_KW,
    IMPL_KW,
    TRUE_KW,
    FALSE_KW,
    AS_KW,
    EXTERN_KW,
    CRATE_KW,
    MOD_KW,
    PUB_KW,
    SELF_KW,
    SUPER_KW,
    IN_KW,
    WHERE_KW,
    ERROR,
    IDENT,
    UNDERSCORE,
    WHITESPACE,
    INT_NUMBER,
    FLOAT_NUMBER,
    SEMI,
    COMMA,
    DOT,
    DOTDOT,
    DOTDOTDOT,
    DOTDOTEQ,
    L_PAREN,
    R_PAREN,
    L_CURLY,
    R_CURLY,
    L_BRACK,
    R_BRACK,
    L_ANGLE,
    R_ANGLE,
    AT,
    POUND,
    TILDE,
    QUESTION,
    COLON,
    COLONCOLON,
    DOLLAR,
    EQ,
    EQEQ,
    FAT_ARROW,
    NEQ,
    EXCL,
    LIFETIME,
    CHAR,
    BYTE,
    STRING,
    RAW_STRING,
    BYTE_STRING,
    RAW_BYTE_STRING,
    PLUS,
    MINUS,
    STAR,
    SLASH,
    CARET,
    PERCENT,
    AMPERSAND,
    PIPE,
    THIN_ARROW,
    COMMENT,
    DOC_COMMENT,
    SHEBANG,
    FILE,
    STRUCT_ITEM,
    NAMED_FIELD,
    POS_FIELD,
    FN_ITEM,
    EXTERN_CRATE_ITEM,
    ATTR,
    META_ITEM,
    MOD_ITEM,
    USE_ITEM,
    USE_TREE,
    PATH,
    PATH_SEGMENT,
    LITERAL,
    ALIAS,
    VISIBILITY,

    // Technical SyntaxKinds: they appear temporally during parsing,
    // but never end up in the final tree
    #[doc(hidden)]
    TOMBSTONE,
    #[doc(hidden)]
    EOF,
}
pub(crate) use self::SyntaxKind::*;

impl SyntaxKind {
    pub(crate) fn info(self) -> &'static SyntaxInfo {
        match self {
            USE_KW => &SyntaxInfo { name: "USE_KW" },
            FN_KW => &SyntaxInfo { name: "FN_KW" },
            STRUCT_KW => &SyntaxInfo { name: "STRUCT_KW" },
            ENUM_KW => &SyntaxInfo { name: "ENUM_KW" },
            TRAIT_KW => &SyntaxInfo { name: "TRAIT_KW" },
            IMPL_KW => &SyntaxInfo { name: "IMPL_KW" },
            TRUE_KW => &SyntaxInfo { name: "TRUE_KW" },
            FALSE_KW => &SyntaxInfo { name: "FALSE_KW" },
            AS_KW => &SyntaxInfo { name: "AS_KW" },
            EXTERN_KW => &SyntaxInfo { name: "EXTERN_KW" },
            CRATE_KW => &SyntaxInfo { name: "CRATE_KW" },
            MOD_KW => &SyntaxInfo { name: "MOD_KW" },
            PUB_KW => &SyntaxInfo { name: "PUB_KW" },
            SELF_KW => &SyntaxInfo { name: "SELF_KW" },
            SUPER_KW => &SyntaxInfo { name: "SUPER_KW" },
            IN_KW => &SyntaxInfo { name: "IN_KW" },
            WHERE_KW => &SyntaxInfo { name: "WHERE_KW" },
            ERROR => &SyntaxInfo { name: "ERROR" },
            IDENT => &SyntaxInfo { name: "IDENT" },
            UNDERSCORE => &SyntaxInfo { name: "UNDERSCORE" },
            WHITESPACE => &SyntaxInfo { name: "WHITESPACE" },
            INT_NUMBER => &SyntaxInfo { name: "INT_NUMBER" },
            FLOAT_NUMBER => &SyntaxInfo { name: "FLOAT_NUMBER" },
            SEMI => &SyntaxInfo { name: "SEMI" },
            COMMA => &SyntaxInfo { name: "COMMA" },
            DOT => &SyntaxInfo { name: "DOT" },
            DOTDOT => &SyntaxInfo { name: "DOTDOT" },
            DOTDOTDOT => &SyntaxInfo { name: "DOTDOTDOT" },
            DOTDOTEQ => &SyntaxInfo { name: "DOTDOTEQ" },
            L_PAREN => &SyntaxInfo { name: "L_PAREN" },
            R_PAREN => &SyntaxInfo { name: "R_PAREN" },
            L_CURLY => &SyntaxInfo { name: "L_CURLY" },
            R_CURLY => &SyntaxInfo { name: "R_CURLY" },
            L_BRACK => &SyntaxInfo { name: "L_BRACK" },
            R_BRACK => &SyntaxInfo { name: "R_BRACK" },
            L_ANGLE => &SyntaxInfo { name: "L_ANGLE" },
            R_ANGLE => &SyntaxInfo { name: "R_ANGLE" },
            AT => &SyntaxInfo { name: "AT" },
            POUND => &SyntaxInfo { name: "POUND" },
            TILDE => &SyntaxInfo { name: "TILDE" },
            QUESTION => &SyntaxInfo { name: "QUESTION" },
            COLON => &SyntaxInfo { name: "COLON" },
            COLONCOLON => &SyntaxInfo { name: "COLONCOLON" },
            DOLLAR => &SyntaxInfo { name: "DOLLAR" },
            EQ => &SyntaxInfo { name: "EQ" },
            EQEQ => &SyntaxInfo { name: "EQEQ" },
            FAT_ARROW => &SyntaxInfo { name: "FAT_ARROW" },
            NEQ => &SyntaxInfo { name: "NEQ" },
            EXCL => &SyntaxInfo { name: "EXCL" },
            LIFETIME => &SyntaxInfo { name: "LIFETIME" },
            CHAR => &SyntaxInfo { name: "CHAR" },
            BYTE => &SyntaxInfo { name: "BYTE" },
            STRING => &SyntaxInfo { name: "STRING" },
            RAW_STRING => &SyntaxInfo { name: "RAW_STRING" },
            BYTE_STRING => &SyntaxInfo { name: "BYTE_STRING" },
            RAW_BYTE_STRING => &SyntaxInfo { name: "RAW_BYTE_STRING" },
            PLUS => &SyntaxInfo { name: "PLUS" },
            MINUS => &SyntaxInfo { name: "MINUS" },
            STAR => &SyntaxInfo { name: "STAR" },
            SLASH => &SyntaxInfo { name: "SLASH" },
            CARET => &SyntaxInfo { name: "CARET" },
            PERCENT => &SyntaxInfo { name: "PERCENT" },
            AMPERSAND => &SyntaxInfo { name: "AMPERSAND" },
            PIPE => &SyntaxInfo { name: "PIPE" },
            THIN_ARROW => &SyntaxInfo { name: "THIN_ARROW" },
            COMMENT => &SyntaxInfo { name: "COMMENT" },
            DOC_COMMENT => &SyntaxInfo { name: "DOC_COMMENT" },
            SHEBANG => &SyntaxInfo { name: "SHEBANG" },
            FILE => &SyntaxInfo { name: "FILE" },
            STRUCT_ITEM => &SyntaxInfo { name: "STRUCT_ITEM" },
            NAMED_FIELD => &SyntaxInfo { name: "NAMED_FIELD" },
            POS_FIELD => &SyntaxInfo { name: "POS_FIELD" },
            FN_ITEM => &SyntaxInfo { name: "FN_ITEM" },
            EXTERN_CRATE_ITEM => &SyntaxInfo { name: "EXTERN_CRATE_ITEM" },
            ATTR => &SyntaxInfo { name: "ATTR" },
            META_ITEM => &SyntaxInfo { name: "META_ITEM" },
            MOD_ITEM => &SyntaxInfo { name: "MOD_ITEM" },
            USE_ITEM => &SyntaxInfo { name: "USE_ITEM" },
            USE_TREE => &SyntaxInfo { name: "USE_TREE" },
            PATH => &SyntaxInfo { name: "PATH" },
            PATH_SEGMENT => &SyntaxInfo { name: "PATH_SEGMENT" },
            LITERAL => &SyntaxInfo { name: "LITERAL" },
            ALIAS => &SyntaxInfo { name: "ALIAS" },
            VISIBILITY => &SyntaxInfo { name: "VISIBILITY" },

            TOMBSTONE => &SyntaxInfo { name: "TOMBSTONE" },
            EOF => &SyntaxInfo { name: "EOF" },
        }
    }
}

pub(crate) fn ident_to_keyword(ident: &str) -> Option<SyntaxKind> {
    match ident {
        "use" => Some(USE_KW),
        "fn" => Some(FN_KW),
        "struct" => Some(STRUCT_KW),
        "enum" => Some(ENUM_KW),
        "trait" => Some(TRAIT_KW),
        "impl" => Some(IMPL_KW),
        "true" => Some(TRUE_KW),
        "false" => Some(FALSE_KW),
        "as" => Some(AS_KW),
        "extern" => Some(EXTERN_KW),
        "crate" => Some(CRATE_KW),
        "mod" => Some(MOD_KW),
        "pub" => Some(PUB_KW),
        "self" => Some(SELF_KW),
        "super" => Some(SUPER_KW),
        "in" => Some(IN_KW),
        "where" => Some(WHERE_KW),
        _ => None,
    }
}
<|endoftext|>


<commit_before>use super::command::{Command, Query};
use super::command::Command::TableCreate;
use std::collections::HashMap;
use types::table_flag_type::TableFlagType;
use types::data_type::DataType;
use types::tokenizer_type::TokenizerType;
use types::normalizer_type::NormalizerType;
use types::token_filters_type::TokenFiltersType;
use util;
use command_query::CommandQuery;
use queryable::Queryable;

pub type LoadValues = String;

#[derive(Clone, PartialEq, Eq, Debug)]
pub struct TableCreateCommand {
    command: Command,
    name: String,
    arguments: HashMap<String, String>,
}

impl Default for TableCreateCommand {
    fn default() -> TableCreateCommand {
        TableCreateCommand {
            command: TableCreate,
            name: "".to_string(),
            arguments: HashMap::new(),
        }
    }
}

impl TableCreateCommand {
    pub fn new(name: String) -> TableCreateCommand {
        let default: TableCreateCommand = Default::default();
        TableCreateCommand {
            command: default.command,
            name: name,
            arguments: default.arguments,
        }
    }

    pub fn flags(mut self, flags: Vec<TableFlagType>) -> TableCreateCommand {
        let string = util::split_flags_vec(flags);
        self.arguments.insert("flags".to_string(), string.clone());
        self
    }

    pub fn key_type(mut self, key_type: DataType) -> TableCreateCommand {
        let string = format!("{}", key_type);
        self.arguments.insert("key_type".to_string(), string.clone());
        self
    }

    pub fn default_tokenizer(mut self, tokenizer: TokenizerType) -> TableCreateCommand {
        let string = format!("{}", tokenizer);
        self.arguments.insert("default_tokenizer".to_string(), string.clone());
        self
    }

    pub fn normalizer(mut self, normalizer: NormalizerType) -> TableCreateCommand {
        let string = format!("{}", normalizer);
        self.arguments.insert("normalizer".to_string(), string.clone());
        self
    }

    pub fn token_filter(mut self, token_filter: TokenFiltersType) -> TableCreateCommand {
        let string = format!("{}", token_filter);
        self.arguments.insert("token_filter".to_string(), string.clone());
        self
    }

    pub fn build(self) -> (Command, Query) {
        let mut query: Query = vec![("name".to_string(), self.name)];
        for (key, value) in self.arguments.iter() {
            query.push((key.to_owned(), value.to_owned()));
        }
        (TableCreate, query)
    }
}

impl Queryable for TableCreateCommand {
    fn to_query(self) -> String {
        let (command, query) = self.build();
        let mut command = CommandQuery::new(command, query);
        command.encode()
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use command::Command::TableCreate;
    use std::collections::HashMap;
    use types::table_flag_type::TableFlagType;
    use types::data_type::DataType;
    use types::tokenizer_type::TokenizerType;
    use types::normalizer_type::NormalizerType;
    use types::token_filters_type::TokenFiltersType;
    use command::Query;
    use queryable::Queryable;

    #[test]
    fn test_new() {
        let vanilla_table_create = TableCreateCommand::new("Test".to_string());
        let expected = TableCreateCommand {
            command: TableCreate,
            name: "Test".to_string(),
            arguments: HashMap::new(),
        };
        assert_eq!(expected, vanilla_table_create);
    }

    #[test]
    fn test_flags() {
        let table_create = TableCreateCommand::new("Test".to_string())
            .flags(vec![(TableFlagType::PatKey), (TableFlagType::KeyWithSIS)]);
        let mut arg: HashMap<String, String> = HashMap::new();
        arg.insert("flags".to_string(),
                   "TABLE_PAT_KEY|TABLE_KEY_WITH_SIS".to_string());
        let expected = TableCreateCommand {
            command: TableCreate,
            name: "Test".to_string(),
            arguments: arg,
        };
        assert_eq!(expected, table_create);
    }

    #[test]
    fn test_key_type() {
        let table_create = TableCreateCommand::new("Test".to_string())
            .key_type(DataType::TokyoGeoPoint);
        let mut arg: HashMap<String, String> = HashMap::new();
        arg.insert("key_type".to_string(), "TokyoGeoPoint".to_string());
        let expected = TableCreateCommand {
            command: TableCreate,
            name: "Test".to_string(),
            arguments: arg,
        };
        assert_eq!(expected, table_create);
    }

    #[test]
    fn test_default_tokenizer() {
        let table_create = TableCreateCommand::new("Test".to_string())
            .default_tokenizer(TokenizerType::BigramSplitSymbolAlpha);
        let mut arg: HashMap<String, String> = HashMap::new();
        arg.insert("default_tokenizer".to_string(),
                   "TokenBigramSplitSymbolAlpha".to_string());
        let expected = TableCreateCommand {
            command: TableCreate,
            name: "Test".to_string(),
            arguments: arg,
        };
        assert_eq!(expected, table_create);
    }

    #[test]
    fn test_normalizer() {
        let table_create = TableCreateCommand::new("Test".to_string())
            .normalizer(NormalizerType::Auto);
        let mut arg: HashMap<String, String> = HashMap::new();
        arg.insert("normalizer".to_string(),
                   "NormalizerAuto".to_string());
        let expected = TableCreateCommand {
            command: TableCreate,
            name: "Test".to_string(),
            arguments: arg,
        };
        assert_eq!(expected, table_create);
    }

    #[test]
    fn test_token_filter() {
        let table_create = TableCreateCommand::new("Test".to_string())
            .token_filter(TokenFiltersType::StopWord);
        let mut arg: HashMap<String, String> = HashMap::new();
        arg.insert("token_filter".to_string(),
                   "TokenFilterStopWord".to_string());
        let expected = TableCreateCommand {
            command: TableCreate,
            name: "Test".to_string(),
            arguments: arg,
        };
        assert_eq!(expected, table_create);
    }

    #[test]
    fn test_build() {
        let actual = TableCreateCommand::new("Test".to_string())
            .flags(vec![(TableFlagType::PatKey), (TableFlagType::KeyWithSIS)]).build();
        let expected_query: Query =
            vec![("name".to_string(), "Test".to_string()),
                 ("flags".to_string(),
                  "TABLE_PAT_KEY|TABLE_KEY_WITH_SIS".to_string())];
        let expected = (TableCreate, expected_query);
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_queryable() {
        let query = TableCreateCommand::new("Test".to_string())
            .flags(vec![(TableFlagType::PatKey), (TableFlagType::KeyWithSIS)])
            .to_query();
        let url_encoded = "/d/table_create?name=Test&flags=TABLE_PAT_KEY%7CTABLE_KEY_WITH_SIS";
        assert_eq!(url_encoded.to_string(), query);
    }
}
<commit_msg>table_create: Remove unused type alias<commit_after>use super::command::{Command, Query};
use super::command::Command::TableCreate;
use std::collections::HashMap;
use types::table_flag_type::TableFlagType;
use types::data_type::DataType;
use types::tokenizer_type::TokenizerType;
use types::normalizer_type::NormalizerType;
use types::token_filters_type::TokenFiltersType;
use util;
use command_query::CommandQuery;
use queryable::Queryable;

#[derive(Clone, PartialEq, Eq, Debug)]
pub struct TableCreateCommand {
    command: Command,
    name: String,
    arguments: HashMap<String, String>,
}

impl Default for TableCreateCommand {
    fn default() -> TableCreateCommand {
        TableCreateCommand {
            command: TableCreate,
            name: "".to_string(),
            arguments: HashMap::new(),
        }
    }
}

impl TableCreateCommand {
    pub fn new(name: String) -> TableCreateCommand {
        let default: TableCreateCommand = Default::default();
        TableCreateCommand {
            command: default.command,
            name: name,
            arguments: default.arguments,
        }
    }

    pub fn flags(mut self, flags: Vec<TableFlagType>) -> TableCreateCommand {
        let string = util::split_flags_vec(flags);
        self.arguments.insert("flags".to_string(), string.clone());
        self
    }

    pub fn key_type(mut self, key_type: DataType) -> TableCreateCommand {
        let string = format!("{}", key_type);
        self.arguments.insert("key_type".to_string(), string.clone());
        self
    }

    pub fn default_tokenizer(mut self, tokenizer: TokenizerType) -> TableCreateCommand {
        let string = format!("{}", tokenizer);
        self.arguments.insert("default_tokenizer".to_string(), string.clone());
        self
    }

    pub fn normalizer(mut self, normalizer: NormalizerType) -> TableCreateCommand {
        let string = format!("{}", normalizer);
        self.arguments.insert("normalizer".to_string(), string.clone());
        self
    }

    pub fn token_filter(mut self, token_filter: TokenFiltersType) -> TableCreateCommand {
        let string = format!("{}", token_filter);
        self.arguments.insert("token_filter".to_string(), string.clone());
        self
    }

    pub fn build(self) -> (Command, Query) {
        let mut query: Query = vec![("name".to_string(), self.name)];
        for (key, value) in self.arguments.iter() {
            query.push((key.to_owned(), value.to_owned()));
        }
        (TableCreate, query)
    }
}

impl Queryable for TableCreateCommand {
    fn to_query(self) -> String {
        let (command, query) = self.build();
        let mut command = CommandQuery::new(command, query);
        command.encode()
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use command::Command::TableCreate;
    use std::collections::HashMap;
    use types::table_flag_type::TableFlagType;
    use types::data_type::DataType;
    use types::tokenizer_type::TokenizerType;
    use types::normalizer_type::NormalizerType;
    use types::token_filters_type::TokenFiltersType;
    use command::Query;
    use queryable::Queryable;

    #[test]
    fn test_new() {
        let vanilla_table_create = TableCreateCommand::new("Test".to_string());
        let expected = TableCreateCommand {
            command: TableCreate,
            name: "Test".to_string(),
            arguments: HashMap::new(),
        };
        assert_eq!(expected, vanilla_table_create);
    }

    #[test]
    fn test_flags() {
        let table_create = TableCreateCommand::new("Test".to_string())
            .flags(vec![(TableFlagType::PatKey), (TableFlagType::KeyWithSIS)]);
        let mut arg: HashMap<String, String> = HashMap::new();
        arg.insert("flags".to_string(),
                   "TABLE_PAT_KEY|TABLE_KEY_WITH_SIS".to_string());
        let expected = TableCreateCommand {
            command: TableCreate,
            name: "Test".to_string(),
            arguments: arg,
        };
        assert_eq!(expected, table_create);
    }

    #[test]
    fn test_key_type() {
        let table_create = TableCreateCommand::new("Test".to_string())
            .key_type(DataType::TokyoGeoPoint);
        let mut arg: HashMap<String, String> = HashMap::new();
        arg.insert("key_type".to_string(), "TokyoGeoPoint".to_string());
        let expected = TableCreateCommand {
            command: TableCreate,
            name: "Test".to_string(),
            arguments: arg,
        };
        assert_eq!(expected, table_create);
    }

    #[test]
    fn test_default_tokenizer() {
        let table_create = TableCreateCommand::new("Test".to_string())
            .default_tokenizer(TokenizerType::BigramSplitSymbolAlpha);
        let mut arg: HashMap<String, String> = HashMap::new();
        arg.insert("default_tokenizer".to_string(),
                   "TokenBigramSplitSymbolAlpha".to_string());
        let expected = TableCreateCommand {
            command: TableCreate,
            name: "Test".to_string(),
            arguments: arg,
        };
        assert_eq!(expected, table_create);
    }

    #[test]
    fn test_normalizer() {
        let table_create = TableCreateCommand::new("Test".to_string())
            .normalizer(NormalizerType::Auto);
        let mut arg: HashMap<String, String> = HashMap::new();
        arg.insert("normalizer".to_string(),
                   "NormalizerAuto".to_string());
        let expected = TableCreateCommand {
            command: TableCreate,
            name: "Test".to_string(),
            arguments: arg,
        };
        assert_eq!(expected, table_create);
    }

    #[test]
    fn test_token_filter() {
        let table_create = TableCreateCommand::new("Test".to_string())
            .token_filter(TokenFiltersType::StopWord);
        let mut arg: HashMap<String, String> = HashMap::new();
        arg.insert("token_filter".to_string(),
                   "TokenFilterStopWord".to_string());
        let expected = TableCreateCommand {
            command: TableCreate,
            name: "Test".to_string(),
            arguments: arg,
        };
        assert_eq!(expected, table_create);
    }

    #[test]
    fn test_build() {
        let actual = TableCreateCommand::new("Test".to_string())
            .flags(vec![(TableFlagType::PatKey), (TableFlagType::KeyWithSIS)]).build();
        let expected_query: Query =
            vec![("name".to_string(), "Test".to_string()),
                 ("flags".to_string(),
                  "TABLE_PAT_KEY|TABLE_KEY_WITH_SIS".to_string())];
        let expected = (TableCreate, expected_query);
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_queryable() {
        let query = TableCreateCommand::new("Test".to_string())
            .flags(vec![(TableFlagType::PatKey), (TableFlagType::KeyWithSIS)])
            .to_query();
        let url_encoded = "/d/table_create?name=Test&flags=TABLE_PAT_KEY%7CTABLE_KEY_WITH_SIS";
        assert_eq!(url_encoded.to_string(), query);
    }
}
<|endoftext|>


<commit_before>// Copyright 2015-2016 Intecture Developers. See the COPYRIGHT file at the
// top-level directory of this distribution and at
// https://intecture.io/COPYRIGHT.
//
// Licensed under the Mozilla Public License 2.0 <LICENSE or
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distributed except according to those terms.

//! The primitive for opening and rendering templates.
//!
//! # Examples
//!
//! ```no_run
//! # use inapi::{MapBuilder, Template};
//! let template = Template::new("/path/to/template").unwrap();
//! let data = MapBuilder::new().insert_str("key", "value").build();
//! let rendered_file = template.render_data(&data).unwrap();
//! ```
#![cfg_attr(feature = "remote-run", doc = "")]
#![cfg_attr(feature = "remote-run", doc = "To upload the rendered file to your host, you can pass it")]
#![cfg_attr(feature = "remote-run", doc = "straight into the File primitive:")]
#![cfg_attr(feature = "remote-run", doc = "")]
#![cfg_attr(feature = "remote-run", doc = "```no_run")]
#![cfg_attr(feature = "remote-run", doc = "# use inapi::{File, Host, MapBuilder, Template};")]
#![cfg_attr(feature = "remote-run", doc = "# let template = Template::new(\"/path/to/template\").unwrap();")]
#![cfg_attr(feature = "remote-run", doc = "# let data = MapBuilder::new().insert_str(\"key\", \"value\").build();")]
#![cfg_attr(feature = "remote-run", doc = "# let rendered_file = template.render_data(&data).unwrap();")]
#![cfg_attr(feature = "remote-run", doc = "let mut host = Host::connect(\"nodes/mynode.json\").unwrap();")]
#![cfg_attr(feature = "remote-run", doc = "")]
#![cfg_attr(feature = "remote-run", doc = "let file = File::new(&mut host, \"/path/to/remote/file\").unwrap();")]
#![cfg_attr(feature = "remote-run", doc = "file.upload_file(&mut host, rendered_file, None).unwrap();")]
#![cfg_attr(feature = "remote-run", doc = "```")]

pub mod ffi;

use error::Result;
use error::Error;
use mustache;
use rustc_serialize::Encodable;
use std::convert::Into;
use std::fs;
use std::io::{Seek, SeekFrom};
use std::path::{Path, PathBuf};
use tempfile::tempfile;

/// Container for rendering and uploading templates.
pub struct Template {
    inner: mustache::Template,
}

impl Template {
    /// Create a new File struct.
    pub fn new<P: AsRef<Path>>(path: P) -> Result<Template> {
        let mut buf = PathBuf::from("payloads");
        buf.push(path);

        if !buf.exists() {
            return Err(Error::Generic("Template path does not exist".into()));
        }

        Ok(Template {
            inner: try!(mustache::compile_path(&buf)),
        })
    }

    /// Render template to file using generic Encodable data.
    pub fn render<T: Encodable>(&self, data: &T) -> Result<fs::File> {
        let mut fh = try!(tempfile());
        try!(self.inner.render(&mut fh, data));

        // Reset cursor to beginning of file for reading
        try!(fh.seek(SeekFrom::Start(0)));
        Ok(fh)
    }

    /// Render template to file using a Data instance.
    pub fn render_data(&self, data: &mustache::Data) -> Result<fs::File> {
        let mut fh = try!(tempfile());
        self.inner.render_data(&mut fh, data);

        // Reset cursor to beginning of file for reading
        try!(fh.seek(SeekFrom::Start(0)));
        Ok(fh)
    }
}

#[cfg(test)]
mod tests {
    use mustache::MapBuilder;
    use std::fs;
    use std::io::{Read, Write};
    use super::*;
    use tempdir::TempDir;

    #[test]
    fn test_new() {
        let tempdir = TempDir::new("template_test_render").unwrap();
        let template_path = format!("{}/template.mustache", tempdir.path().to_str().unwrap());

        assert!(Template::new(&template_path).is_err());

        fs::File::create(&template_path).unwrap();
        Template::new(&template_path).unwrap();
        assert!(Template::new(&template_path).is_ok());
    }

    #[test]
    fn test_render() {
        let tempdir = TempDir::new("template_test_render").unwrap();
        let template_path = format!("{}/template.mustache", tempdir.path().to_str().unwrap());

        let template_str = "Hello, {{name}}!".to_string();
        let data = TestData {
            name: "Jasper Beardly"
        };

        let mut fh = fs::File::create(&template_path).unwrap();
        fh.write_all(template_str.as_bytes()).unwrap();

        let template = Template::new(&template_path).unwrap();
        let mut fh = template.render(&data).unwrap();
        let mut content = String::new();
        fh.read_to_string(&mut content).unwrap();
        assert_eq!(content, "Hello, Jasper Beardly!");
    }

    #[test]
    fn test_render_data_to_file() {
        let tempdir = TempDir::new("template_test_render").unwrap();
        let template_path = format!("{}/template.mustache", tempdir.path().to_str().unwrap());

        let template_str = "Hello, {{name}}!".to_string();
        let data = MapBuilder::new().insert_str("name", "Jasper Beardly").build();

        let mut fh = fs::File::create(&template_path).unwrap();
        fh.write_all(template_str.as_bytes()).unwrap();

        let template = Template::new(&template_path).unwrap();
        let mut fh = template.render_data(&data).unwrap();
        let mut content = String::new();
        fh.read_to_string(&mut content).unwrap();
        assert_eq!(content, "Hello, Jasper Beardly!");
    }

    #[derive(RustcEncodable)]
    struct TestData {
        name: &'static str,
    }
}
<commit_msg>Don't assume that a template is always stored within a payload<commit_after>// Copyright 2015-2016 Intecture Developers. See the COPYRIGHT file at the
// top-level directory of this distribution and at
// https://intecture.io/COPYRIGHT.
//
// Licensed under the Mozilla Public License 2.0 <LICENSE or
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distributed except according to those terms.

//! The primitive for opening and rendering templates.
//!
//! # Examples
//!
//! ```no_run
//! # use inapi::{MapBuilder, Template};
//! let template = Template::new("/path/to/template").unwrap();
//! let data = MapBuilder::new().insert_str("key", "value").build();
//! let rendered_file = template.render_data(&data).unwrap();
//! ```
#![cfg_attr(feature = "remote-run", doc = "")]
#![cfg_attr(feature = "remote-run", doc = "To upload the rendered file to your host, you can pass it")]
#![cfg_attr(feature = "remote-run", doc = "straight into the File primitive:")]
#![cfg_attr(feature = "remote-run", doc = "")]
#![cfg_attr(feature = "remote-run", doc = "```no_run")]
#![cfg_attr(feature = "remote-run", doc = "# use inapi::{File, Host, MapBuilder, Template};")]
#![cfg_attr(feature = "remote-run", doc = "# let template = Template::new(\"/path/to/template\").unwrap();")]
#![cfg_attr(feature = "remote-run", doc = "# let data = MapBuilder::new().insert_str(\"key\", \"value\").build();")]
#![cfg_attr(feature = "remote-run", doc = "# let rendered_file = template.render_data(&data).unwrap();")]
#![cfg_attr(feature = "remote-run", doc = "let mut host = Host::connect(\"nodes/mynode.json\").unwrap();")]
#![cfg_attr(feature = "remote-run", doc = "")]
#![cfg_attr(feature = "remote-run", doc = "let file = File::new(&mut host, \"/path/to/remote/file\").unwrap();")]
#![cfg_attr(feature = "remote-run", doc = "file.upload_file(&mut host, rendered_file, None).unwrap();")]
#![cfg_attr(feature = "remote-run", doc = "```")]

pub mod ffi;

use error::Result;
use error::Error;
use mustache;
use rustc_serialize::Encodable;
use std::convert::Into;
use std::fs;
use std::io::{Seek, SeekFrom};
use std::path::Path;
use tempfile::tempfile;

/// Container for rendering and uploading templates.
pub struct Template {
    inner: mustache::Template,
}

impl Template {
    /// Create a new File struct.
    pub fn new<P: AsRef<Path>>(path: P) -> Result<Template> {
        if !path.as_ref().exists() {
            return Err(Error::Generic("Template path does not exist".into()));
        }

        Ok(Template {
            inner: try!(mustache::compile_path(path.as_ref())),
        })
    }

    /// Render template to file using generic Encodable data.
    pub fn render<T: Encodable>(&self, data: &T) -> Result<fs::File> {
        let mut fh = try!(tempfile());
        try!(self.inner.render(&mut fh, data));

        // Reset cursor to beginning of file for reading
        try!(fh.seek(SeekFrom::Start(0)));
        Ok(fh)
    }

    /// Render template to file using a Data instance.
    pub fn render_data(&self, data: &mustache::Data) -> Result<fs::File> {
        let mut fh = try!(tempfile());
        self.inner.render_data(&mut fh, data);

        // Reset cursor to beginning of file for reading
        try!(fh.seek(SeekFrom::Start(0)));
        Ok(fh)
    }
}

#[cfg(test)]
mod tests {
    use mustache::MapBuilder;
    use std::fs;
    use std::io::{Read, Write};
    use super::*;
    use tempdir::TempDir;

    #[test]
    fn test_new() {
        let tempdir = TempDir::new("template_test_render").unwrap();
        let template_path = format!("{}/template.mustache", tempdir.path().to_str().unwrap());

        assert!(Template::new(&template_path).is_err());

        fs::File::create(&template_path).unwrap();
        Template::new(&template_path).unwrap();
        assert!(Template::new(&template_path).is_ok());
    }

    #[test]
    fn test_render() {
        let tempdir = TempDir::new("template_test_render").unwrap();
        let template_path = format!("{}/template.mustache", tempdir.path().to_str().unwrap());

        let template_str = "Hello, {{name}}!".to_string();
        let data = TestData {
            name: "Jasper Beardly"
        };

        let mut fh = fs::File::create(&template_path).unwrap();
        fh.write_all(template_str.as_bytes()).unwrap();

        let template = Template::new(&template_path).unwrap();
        let mut fh = template.render(&data).unwrap();
        let mut content = String::new();
        fh.read_to_string(&mut content).unwrap();
        assert_eq!(content, "Hello, Jasper Beardly!");
    }

    #[test]
    fn test_render_data_to_file() {
        let tempdir = TempDir::new("template_test_render").unwrap();
        let template_path = format!("{}/template.mustache", tempdir.path().to_str().unwrap());

        let template_str = "Hello, {{name}}!".to_string();
        let data = MapBuilder::new().insert_str("name", "Jasper Beardly").build();

        let mut fh = fs::File::create(&template_path).unwrap();
        fh.write_all(template_str.as_bytes()).unwrap();

        let template = Template::new(&template_path).unwrap();
        let mut fh = template.render_data(&data).unwrap();
        let mut content = String::new();
        fh.read_to_string(&mut content).unwrap();
        assert_eq!(content, "Hello, Jasper Beardly!");
    }

    #[derive(RustcEncodable)]
    struct TestData {
        name: &'static str,
    }
}
<|endoftext|>