<commit_before>// Copyright (c) Facebook, Inc. and its affiliates
// SPDX-License-Identifier: MIT OR Apache-2.0

use crate::analyzer;
use serde_reflection::{ContainerFormat, Format, Named, Registry, VariantFormat};
use std::collections::{BTreeMap, HashSet};
use std::io::{Result, Write};
use std::path::PathBuf;

pub fn output(
    out: &mut dyn Write,
    registry: &Registry,
    namespace: Option<&str>,
) -> std::result::Result<(), Box<dyn std::error::Error>> {
    let namespace_prefix = match namespace {
        None => "::".to_string(),
        Some(name) => format!("{}::", name),
    };
    let mut emitter = CppEmitter {
        out,
        indentation: 0,
        namespace,
        namespace_prefix,
        known_names: HashSet::new(),
        known_sizes: HashSet::new(),
    };

    emitter.output_preamble()?;
    emitter.output_open_namespace()?;

    let dependencies = analyzer::get_dependency_map(registry)?;
    let entries = analyzer::best_effort_topological_sort(&dependencies);

    for name in entries {
        for dependency in &dependencies[name] {
            if !emitter.known_names.contains(dependency) {
                emitter.output_container_forward_definition(*dependency)?;
                emitter.known_names.insert(*dependency);
            }
        }
        let format = &registry[name];
        emitter.output_container(name, format)?;
        emitter.known_sizes.insert(name);
        emitter.known_names.insert(name);
    }

    emitter.output_close_namespace()?;
    writeln!(emitter.out)?;
    for (name, format) in registry {
        emitter.output_container_traits(&name, format)?;
    }
    Ok(())
}

struct CppEmitter<'a, T> {
    out: T,
    indentation: usize,
    namespace: Option<&'a str>,
    namespace_prefix: String,
    known_names: HashSet<&'a str>,
    known_sizes: HashSet<&'a str>,
}

impl<'a, T> CppEmitter<'a, T>
where
    T: std::io::Write,
{
    fn output_preamble(&mut self) -> Result<()> {
        writeln!(
            self.out,
            r#"
#pragma once

#include "serde.hpp"
"#
        )
    }

    fn output_open_namespace(&mut self) -> Result<()> {
        assert_eq!(self.indentation, 0);
        if let Some(name) = self.namespace {
            writeln!(self.out, "\nnamespace {} {{\n", name,)?;
        }
        Ok(())
    }

    fn output_close_namespace(&mut self) -> Result<()> {
        assert_eq!(self.indentation, 0);
        if let Some(name) = self.namespace {
            writeln!(self.out, "\n}} // end of namespace {}", name,)?;
        }
        Ok(())
    }

    /// If known_sizes is present, we must try to return a type with a known size as well.
    /// A non-empty `namespace_prefix` is required when the type is quoted from a nested struct.
    fn quote_type(
        format: &Format,
        known_sizes: Option<&HashSet<&str>>,
        namespace_prefix: &str,
    ) -> String {
        use Format::*;
        match format {
            TypeName(x) => {
                if let Some(set) = known_sizes {
                    if !set.contains(x.as_str()) {
                        // Cannot use unique_ptr because we need a copy constructor (e.g. for vectors).
                        return format!("std::shared_ptr<{}{}>", namespace_prefix, x);
                    }
                }
                format!("{}{}", namespace_prefix, x)
            }
            Unit => "std::monostate".into(),
            Bool => "bool".into(),
            I8 => "int8_t".into(),
            I16 => "int16_t".into(),
            I32 => "int32_t".into(),
            I64 => "int64_t".into(),
            I128 => "serde::int128_t".into(),
            U8 => "uint8_t".into(),
            U16 => "uint16_t".into(),
            U32 => "uint32_t".into(),
            U64 => "uint64_t".into(),
            U128 => "serde::uint128_t".into(),
            F32 => "float".into(),
            F64 => "double".into(),
            Char => "char32_t".into(),
            Str => "std::string".into(),
            Bytes => "std::vector<uint8_t>".into(),

            Option(format) => format!(
                "std::optional<{}>",
                Self::quote_type(format, known_sizes, namespace_prefix)
            ),
            Seq(format) => format!(
                "std::vector<{}>",
                Self::quote_type(format, None, namespace_prefix)
            ),
            Map { key, value } => format!(
                "std::map<{}, {}>",
                Self::quote_type(key, None, namespace_prefix),
                Self::quote_type(value, None, namespace_prefix)
            ),
            Tuple(formats) => format!(
                "std::tuple<{}>",
                Self::quote_types(formats, known_sizes, namespace_prefix)
            ),
            TupleArray { content, size } => format!(
                "std::array<{}, {}>",
                Self::quote_type(content, known_sizes, namespace_prefix),
                *size
            ),

            Variable(_) => panic!("unexpected value"),
        }
    }

    fn quote_types(
        formats: &[Format],
        known_sizes: Option<&HashSet<&str>>,
        namespace_prefix: &str,
    ) -> String {
        formats
            .iter()
            .map(|x| Self::quote_type(x, known_sizes, namespace_prefix))
            .collect::<Vec<_>>()
            .join(", ")
    }

    fn output_fields(&mut self, fields: &[Named<Format>]) -> Result<()> {
        self.indentation += 1;
        let tab = "    ".repeat(self.indentation);
        for field in fields {
            writeln!(
                self.out,
                "{}{} {};",
                tab,
                Self::quote_type(
                    &field.value,
                    Some(&self.known_sizes),
                    &self.namespace_prefix
                ),
                field.name
            )?;
        }
        self.indentation -= 1;
        Ok(())
    }

    fn output_variant(&mut self, name: &str, variant: &VariantFormat) -> Result<()> {
        assert_eq!(self.indentation, 1);
        use VariantFormat::*;
        let operator = format!("friend bool operator==(const {}&, const {}&);", name, name);
        match variant {
            Unit => writeln!(
                self.out,
                "    struct {} {{\n        {}\n    }};",
                name, operator
            ),
            NewType(format) => writeln!(
                self.out,
                "    struct {} {{\n        {} value;\n        {}\n    }};",
                name,
                Self::quote_type(format, Some(&self.known_sizes), &self.namespace_prefix),
                operator,
            ),
            Tuple(formats) => writeln!(
                self.out,
                "    struct {} {{\n        std::tuple<{}> value;\n        {}\n    }};",
                name,
                Self::quote_types(formats, Some(&self.known_sizes), &self.namespace_prefix),
                operator
            ),
            Struct(fields) => {
                writeln!(self.out, "    struct {} {{", name)?;
                self.output_fields(fields)?;
                writeln!(self.out, "        {}\n    }};", operator)
            }
            Variable(_) => panic!("incorrect value"),
        }
    }

    fn output_variants(&mut self, variants: &BTreeMap<u32, Named<VariantFormat>>) -> Result<()> {
        assert_eq!(self.indentation, 0);
        self.indentation += 1;
        for (expected_index, (index, variant)) in variants.iter().enumerate() {
            assert_eq!(*index, expected_index as u32);
            self.output_variant(&variant.name, &variant.value)?;
        }
        self.indentation -= 1;
        Ok(())
    }

    fn output_container_forward_definition(&mut self, name: &str) -> Result<()> {
        writeln!(self.out, "struct {};\n", name)
    }

    fn output_container(&mut self, name: &str, format: &ContainerFormat) -> Result<()> {
        assert_eq!(self.indentation, 0);
        use ContainerFormat::*;
        let operator = format!("friend bool operator==(const {}&, const {}&);", name, name);
        match format {
            UnitStruct => writeln!(self.out, "struct {} {{\n    {}\n}};\n", name, operator),
            NewTypeStruct(format) => writeln!(
                self.out,
                "struct {} {{\n    {} value;\n    {}\n}};\n",
                name,
                Self::quote_type(format, Some(&self.known_sizes), ""),
                operator,
            ),
            TupleStruct(formats) => writeln!(
                self.out,
                "struct {} {{\n    std::tuple<{}> value;\n    {}\n}};\n",
                name,
                Self::quote_types(formats, Some(&self.known_sizes), ""),
                operator,
            ),
            Struct(fields) => {
                writeln!(self.out, "struct {} {{", name)?;
                self.output_fields(fields)?;
                writeln!(self.out, "    {}\n}};\n", operator)
            }
            Enum(variants) => {
                writeln!(self.out, "struct {} {{", name)?;
                self.output_variants(variants)?;
                writeln!(
                    self.out,
                    "    std::variant<{}> value;\n    {}\n}};\n",
                    variants
                        .iter()
                        .map(|(_, v)| v.name.clone())
                        .collect::<Vec<_>>()
                        .join(", "),
                    operator,
                )
            }
        }
    }

    fn output_struct_equality_test(&mut self, name: &str, fields: &[&str]) -> Result<()> {
        assert_eq!(self.indentation, 0);
        writeln!(
            self.out,
            "inline bool operator==(const {} &lhs, const {} &rhs) {{",
            name, name,
        )?;
        for field in fields {
            writeln!(
                self.out,
                "    if (!(lhs.{} == rhs.{})) {{ return false; }}",
                field, field,
            )?;
        }
        writeln!(self.out, "    return true;\n}}")
    }

    fn output_struct_serializable(&mut self, name: &str, fields: &[&str]) -> Result<()> {
        assert_eq!(self.indentation, 0);
        writeln!(
            self.out,
            r#"
template <>
template <typename Serializer>
void serde::Serializable<{}>::serialize(const {} &obj, Serializer &serializer) {{"#,
            name, name,
        )?;
        for field in fields {
            writeln!(
                self.out,
                "    serde::Serializable<decltype(obj.{})>::serialize(obj.{}, serializer);",
                field, field,
            )?;
        }
        writeln!(self.out, "}}")
    }

    fn output_struct_deserializable(&mut self, name: &str, fields: &[&str]) -> Result<()> {
        assert_eq!(self.indentation, 0);
        writeln!(
            self.out,
            r#"
template <>
template <typename Deserializer>
{} serde::Deserializable<{}>::deserialize(Deserializer &deserializer) {{
    {} obj;"#,
            name, name, name,
        )?;
        for field in fields {
            writeln!(
                self.out,
                "    obj.{} = serde::Deserializable<decltype(obj.{})>::deserialize(deserializer);",
                field, field,
            )?;
        }
        writeln!(self.out, "    return obj;\n}}")
    }

    fn output_struct_traits(&mut self, name: &str, fields: &[&str]) -> Result<()> {
        assert_eq!(self.indentation, 0);
        self.output_open_namespace()?;
        self.output_struct_equality_test(name, fields)?;
        self.output_close_namespace()?;
        let namespaced_name = format!("{}{}", self.namespace_prefix, name);
        self.output_struct_serializable(&namespaced_name, fields)?;
        self.output_struct_deserializable(&namespaced_name, fields)
    }

    fn get_variant_fields(format: &VariantFormat) -> Vec<&str> {
        use VariantFormat::*;
        match format {
            Unit => Vec::new(),
            NewType(_format) => vec!["value"],
            Tuple(_formats) => vec!["value"],
            Struct(fields) => fields
                .iter()
                .map(|field| field.name.as_str())
                .collect::<Vec<_>>(),
            Variable(_) => panic!("incorrect value"),
        }
    }

    fn output_container_traits(&mut self, name: &str, format: &ContainerFormat) -> Result<()> {
        assert_eq!(self.indentation, 0);
        use ContainerFormat::*;
        match format {
            UnitStruct => self.output_struct_traits(name, &[]),
            NewTypeStruct(_format) => self.output_struct_traits(name, &["value"]),
            TupleStruct(_formats) => self.output_struct_traits(name, &["value"]),
            Struct(fields) => self.output_struct_traits(
                name,
                &fields
                    .iter()
                    .map(|field| field.name.as_str())
                    .collect::<Vec<_>>(),
            ),
            Enum(variants) => {
                self.output_struct_traits(name, &["value"])?;
                for variant in variants.values() {
                    self.output_struct_traits(
                        &format!("{}::{}", name, variant.name),
                        &Self::get_variant_fields(&variant.value),
                    )?;
                }
                Ok(())
            }
        }
    }
}

pub struct Installer {
    install_dir: PathBuf,
}

impl Installer {
    pub fn new(install_dir: PathBuf) -> Self {
        Installer { install_dir }
    }

    fn create_header_file(&self, name: &str) -> Result<std::fs::File> {
        let dir_path = &self.install_dir;
        std::fs::create_dir_all(dir_path)?;
        std::fs::File::create(dir_path.join(name.to_string() + ".hpp"))
    }
}

impl crate::SourceInstaller for Installer {
    type Error = Box<dyn std::error::Error>;

    fn install_module(
        &self,
        name: &str,
        registry: &Registry,
    ) -> std::result::Result<(), Self::Error> {
        let mut file = self.create_header_file(name)?;
        output(&mut file, &registry, Some(name))
    }

    fn install_serde_runtime(&self) -> std::result::Result<(), Self::Error> {
        let mut file = self.create_header_file("serde")?;
        write!(file, "{}", include_str!("../runtime/cpp/serde.hpp"))?;
        Ok(())
    }

    fn install_bincode_runtime(&self) -> std::result::Result<(), Self::Error> {
        let mut file = self.create_header_file("bincode")?;
        write!(file, "{}", include_str!("../runtime/cpp/bincode.hpp"))?;
        Ok(())
    }

    fn install_lcs_runtime(&self) -> std::result::Result<(), Self::Error> {
        let mut file = self.create_header_file("lcs")?;
        write!(file, "{}", include_str!("../runtime/cpp/lcs.hpp"))?;
        Ok(())
    }
}
<commit_msg>[serde generate] C++: use IndentWriter<commit_after>// Copyright (c) Facebook, Inc. and its affiliates
// SPDX-License-Identifier: MIT OR Apache-2.0

use crate::{
    analyzer,
    indent::{IndentConfig, IndentedWriter},
};
use serde_reflection::{ContainerFormat, Format, Named, Registry, VariantFormat};
use std::collections::{BTreeMap, HashSet};
use std::io::{Result, Write};
use std::path::PathBuf;

pub fn output(
    out: &mut dyn Write,
    registry: &Registry,
    namespace: Option<&str>,
) -> std::result::Result<(), Box<dyn std::error::Error>> {
    let namespace_prefix = match namespace {
        None => "::".to_string(),
        Some(name) => format!("{}::", name),
    };
    let mut emitter = CppEmitter {
        out: IndentedWriter::new(out, IndentConfig::Space(4)),
        namespace,
        namespace_prefix,
        known_names: HashSet::new(),
        known_sizes: HashSet::new(),
    };

    emitter.output_preamble()?;
    emitter.output_open_namespace()?;

    let dependencies = analyzer::get_dependency_map(registry)?;
    let entries = analyzer::best_effort_topological_sort(&dependencies);

    for name in entries {
        for dependency in &dependencies[name] {
            if !emitter.known_names.contains(dependency) {
                emitter.output_container_forward_definition(*dependency)?;
                emitter.known_names.insert(*dependency);
            }
        }
        let format = &registry[name];
        emitter.output_container(name, format)?;
        emitter.known_sizes.insert(name);
        emitter.known_names.insert(name);
    }

    emitter.output_close_namespace()?;
    writeln!(emitter.out)?;
    for (name, format) in registry {
        emitter.output_container_traits(&name, format)?;
    }
    Ok(())
}

struct CppEmitter<'a, T> {
    out: IndentedWriter<T>,
    namespace: Option<&'a str>,
    namespace_prefix: String,
    known_names: HashSet<&'a str>,
    known_sizes: HashSet<&'a str>,
}

impl<'a, T> CppEmitter<'a, T>
where
    T: std::io::Write,
{
    fn output_preamble(&mut self) -> Result<()> {
        writeln!(
            self.out,
            r#"#pragma once

#include "serde.hpp""#
        )
    }

    fn output_open_namespace(&mut self) -> Result<()> {
        if let Some(name) = self.namespace {
            writeln!(self.out, "\nnamespace {} {{\n", name)?;
            self.out.inc_level();
        }
        Ok(())
    }

    fn output_close_namespace(&mut self) -> Result<()> {
        if let Some(name) = self.namespace {
            self.out.dec_level();
            writeln!(self.out, "}} // end of namespace {}", name)?;
        }
        Ok(())
    }

    /// If known_sizes is present, we must try to return a type with a known size as well.
    /// A non-empty `namespace_prefix` is required when the type is quoted from a nested struct.
    fn quote_type(
        format: &Format,
        known_sizes: Option<&HashSet<&str>>,
        namespace_prefix: &str,
    ) -> String {
        use Format::*;
        match format {
            TypeName(x) => {
                if let Some(set) = known_sizes {
                    if !set.contains(x.as_str()) {
                        // Cannot use unique_ptr because we need a copy constructor (e.g. for vectors).
                        return format!("std::shared_ptr<{}{}>", namespace_prefix, x);
                    }
                }
                format!("{}{}", namespace_prefix, x)
            }
            Unit => "std::monostate".into(),
            Bool => "bool".into(),
            I8 => "int8_t".into(),
            I16 => "int16_t".into(),
            I32 => "int32_t".into(),
            I64 => "int64_t".into(),
            I128 => "serde::int128_t".into(),
            U8 => "uint8_t".into(),
            U16 => "uint16_t".into(),
            U32 => "uint32_t".into(),
            U64 => "uint64_t".into(),
            U128 => "serde::uint128_t".into(),
            F32 => "float".into(),
            F64 => "double".into(),
            Char => "char32_t".into(),
            Str => "std::string".into(),
            Bytes => "std::vector<uint8_t>".into(),

            Option(format) => format!(
                "std::optional<{}>",
                Self::quote_type(format, known_sizes, namespace_prefix)
            ),
            Seq(format) => format!(
                "std::vector<{}>",
                Self::quote_type(format, None, namespace_prefix)
            ),
            Map { key, value } => format!(
                "std::map<{}, {}>",
                Self::quote_type(key, None, namespace_prefix),
                Self::quote_type(value, None, namespace_prefix)
            ),
            Tuple(formats) => format!(
                "std::tuple<{}>",
                Self::quote_types(formats, known_sizes, namespace_prefix)
            ),
            TupleArray { content, size } => format!(
                "std::array<{}, {}>",
                Self::quote_type(content, known_sizes, namespace_prefix),
                *size
            ),

            Variable(_) => panic!("unexpected value"),
        }
    }

    fn quote_types(
        formats: &[Format],
        known_sizes: Option<&HashSet<&str>>,
        namespace_prefix: &str,
    ) -> String {
        formats
            .iter()
            .map(|x| Self::quote_type(x, known_sizes, namespace_prefix))
            .collect::<Vec<_>>()
            .join(", ")
    }

    fn output_fields(&mut self, fields: &[Named<Format>]) -> Result<()> {
        for field in fields {
            writeln!(
                self.out,
                "{} {};",
                Self::quote_type(
                    &field.value,
                    Some(&self.known_sizes),
                    &self.namespace_prefix
                ),
                field.name
            )?;
        }
        Ok(())
    }

    fn output_variant(&mut self, name: &str, variant: &VariantFormat) -> Result<()> {
        use VariantFormat::*;
        let operator = format!("friend bool operator==(const {}&, const {}&);", name, name);
        match variant {
            Unit => writeln!(self.out, "struct {} {{\n    {}\n}};", name, operator),
            NewType(format) => writeln!(
                self.out,
                "struct {} {{\n    {} value;\n    {}\n}};",
                name,
                Self::quote_type(format, Some(&self.known_sizes), &self.namespace_prefix),
                operator,
            ),
            Tuple(formats) => writeln!(
                self.out,
                "struct {} {{\n    std::tuple<{}> value;\n    {}\n}};",
                name,
                Self::quote_types(formats, Some(&self.known_sizes), &self.namespace_prefix),
                operator
            ),
            Struct(fields) => {
                writeln!(self.out, "struct {} {{", name)?;
                self.out.inc_level();
                self.output_fields(fields)?;
                writeln!(self.out, "{}", operator)?;
                self.out.dec_level();
                writeln!(self.out, "}};")
            }
            Variable(_) => panic!("incorrect value"),
        }
    }

    fn output_variants(&mut self, variants: &BTreeMap<u32, Named<VariantFormat>>) -> Result<()> {
        for (expected_index, (index, variant)) in variants.iter().enumerate() {
            assert_eq!(*index, expected_index as u32);
            self.output_variant(&variant.name, &variant.value)?;
        }
        Ok(())
    }

    fn output_container_forward_definition(&mut self, name: &str) -> Result<()> {
        writeln!(self.out, "struct {};\n", name)
    }

    fn output_container(&mut self, name: &str, format: &ContainerFormat) -> Result<()> {
        use ContainerFormat::*;
        let operator = format!("friend bool operator==(const {0}&, const {0}&);", name);
        match format {
            UnitStruct => writeln!(self.out, "struct {} {{\n    {}\n}};\n", name, operator),
            NewTypeStruct(format) => writeln!(
                self.out,
                "struct {} {{\n    {} value;\n    {}\n}};\n",
                name,
                Self::quote_type(format, Some(&self.known_sizes), ""),
                operator,
            ),
            TupleStruct(formats) => writeln!(
                self.out,
                "struct {} {{\n    std::tuple<{}> value;\n    {}\n}};\n",
                name,
                Self::quote_types(formats, Some(&self.known_sizes), ""),
                operator,
            ),
            Struct(fields) => {
                writeln!(self.out, "struct {} {{", name)?;
                self.out.inc_level();
                self.output_fields(fields)?;
                writeln!(self.out, "{}", operator)?;
                self.out.dec_level();
                writeln!(self.out, "}};\n")
            }
            Enum(variants) => {
                writeln!(self.out, "struct {} {{", name)?;
                self.out.inc_level();
                self.output_variants(variants)?;
                writeln!(
                    self.out,
                    "std::variant<{}> value;",
                    variants
                        .iter()
                        .map(|(_, v)| v.name.clone())
                        .collect::<Vec<_>>()
                        .join(", "),
                )?;
                writeln!(self.out, "{}", operator)?;
                self.out.dec_level();
                writeln!(self.out, "}};\n")
            }
        }
    }

    fn output_struct_equality_test(&mut self, name: &str, fields: &[&str]) -> Result<()> {
        writeln!(
            self.out,
            "inline bool operator==(const {0} &lhs, const {0} &rhs) {{",
            name,
        )?;
        self.out.inc_level();
        for field in fields {
            writeln!(
                self.out,
                "if (!(lhs.{0} == rhs.{0})) {{ return false; }}",
                field,
            )?;
        }
        writeln!(self.out, "return true;")?;
        self.out.dec_level();
        writeln!(self.out, "}}\n")
    }

    fn output_struct_serializable(&mut self, name: &str, fields: &[&str]) -> Result<()> {
        writeln!(
            self.out,
            r#"
template <>
template <typename Serializer>
void serde::Serializable<{0}>::serialize(const {0} &obj, Serializer &serializer) {{"#,
            name,
        )?;
        self.out.inc_level();
        for field in fields {
            writeln!(
                self.out,
                "serde::Serializable<decltype(obj.{0})>::serialize(obj.{0}, serializer);",
                field,
            )?;
        }
        self.out.dec_level();
        writeln!(self.out, "}}")
    }

    fn output_struct_deserializable(&mut self, name: &str, fields: &[&str]) -> Result<()> {
        writeln!(
            self.out,
            r#"
template <>
template <typename Deserializer>
{0} serde::Deserializable<{0}>::deserialize(Deserializer &deserializer) {{"#,
            name,
        )?;
        self.out.inc_level();
        writeln!(self.out, "{} obj;", name)?;
        for field in fields {
            writeln!(
                self.out,
                "obj.{0} = serde::Deserializable<decltype(obj.{0})>::deserialize(deserializer);",
                field,
            )?;
        }
        writeln!(self.out, "return obj;")?;
        self.out.dec_level();
        writeln!(self.out, "}}")
    }

    fn output_struct_traits(&mut self, name: &str, fields: &[&str]) -> Result<()> {
        self.output_open_namespace()?;
        self.output_struct_equality_test(name, fields)?;
        self.output_close_namespace()?;
        let namespaced_name = format!("{}{}", self.namespace_prefix, name);
        self.output_struct_serializable(&namespaced_name, fields)?;
        self.output_struct_deserializable(&namespaced_name, fields)
    }

    fn get_variant_fields(format: &VariantFormat) -> Vec<&str> {
        use VariantFormat::*;
        match format {
            Unit => Vec::new(),
            NewType(_format) => vec!["value"],
            Tuple(_formats) => vec!["value"],
            Struct(fields) => fields
                .iter()
                .map(|field| field.name.as_str())
                .collect::<Vec<_>>(),
            Variable(_) => panic!("incorrect value"),
        }
    }

    fn output_container_traits(&mut self, name: &str, format: &ContainerFormat) -> Result<()> {
        use ContainerFormat::*;
        match format {
            UnitStruct => self.output_struct_traits(name, &[]),
            NewTypeStruct(_format) => self.output_struct_traits(name, &["value"]),
            TupleStruct(_formats) => self.output_struct_traits(name, &["value"]),
            Struct(fields) => self.output_struct_traits(
                name,
                &fields
                    .iter()
                    .map(|field| field.name.as_str())
                    .collect::<Vec<_>>(),
            ),
            Enum(variants) => {
                self.output_struct_traits(name, &["value"])?;
                for variant in variants.values() {
                    self.output_struct_traits(
                        &format!("{}::{}", name, variant.name),
                        &Self::get_variant_fields(&variant.value),
                    )?;
                }
                Ok(())
            }
        }
    }
}

pub struct Installer {
    install_dir: PathBuf,
}

impl Installer {
    pub fn new(install_dir: PathBuf) -> Self {
        Installer { install_dir }
    }

    fn create_header_file(&self, name: &str) -> Result<std::fs::File> {
        let dir_path = &self.install_dir;
        std::fs::create_dir_all(dir_path)?;
        std::fs::File::create(dir_path.join(name.to_string() + ".hpp"))
    }
}

impl crate::SourceInstaller for Installer {
    type Error = Box<dyn std::error::Error>;

    fn install_module(
        &self,
        name: &str,
        registry: &Registry,
    ) -> std::result::Result<(), Self::Error> {
        let mut file = self.create_header_file(name)?;
        output(&mut file, &registry, Some(name))
    }

    fn install_serde_runtime(&self) -> std::result::Result<(), Self::Error> {
        let mut file = self.create_header_file("serde")?;
        write!(file, "{}", include_str!("../runtime/cpp/serde.hpp"))?;
        Ok(())
    }

    fn install_bincode_runtime(&self) -> std::result::Result<(), Self::Error> {
        let mut file = self.create_header_file("bincode")?;
        write!(file, "{}", include_str!("../runtime/cpp/bincode.hpp"))?;
        Ok(())
    }

    fn install_lcs_runtime(&self) -> std::result::Result<(), Self::Error> {
        let mut file = self.create_header_file("lcs")?;
        write!(file, "{}", include_str!("../runtime/cpp/lcs.hpp"))?;
        Ok(())
    }
}
<|endoftext|>


<commit_before>//! This pass checks HIR bodies that may be evaluated at compile-time (e.g., `const`, `static`,
//! `const fn`) for structured control flow (e.g. `if`, `while`), which is forbidden in a const
//! context.
//!
//! By the time the MIR const-checker runs, these high-level constructs have been lowered to
//! control-flow primitives (e.g., `Goto`, `SwitchInt`), making it tough to properly attribute
//! errors. We still look for those primitives in the MIR const-checker to ensure nothing slips
//! through, but errors for structured control flow in a `const` should be emitted here.

use rustc_attr as attr;
use rustc_errors::struct_span_err;
use rustc_hir as hir;
use rustc_hir::def_id::LocalDefId;
use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
use rustc_middle::hir::map::Map;
use rustc_middle::ty::query::Providers;
use rustc_middle::ty::TyCtxt;
use rustc_session::config::nightly_options;
use rustc_session::parse::feature_err;
use rustc_span::{sym, Span, Symbol};

/// An expression that is not *always* legal in a const context.
#[derive(Clone, Copy)]
enum NonConstExpr {
    Loop(hir::LoopSource),
    Match(hir::MatchSource),
}

impl NonConstExpr {
    fn name(self) -> String {
        match self {
            Self::Loop(src) => format!("`{}`", src.name()),
            Self::Match(src) => format!("`{}`", src.name()),
        }
    }

    fn required_feature_gates(self) -> Option<&'static [Symbol]> {
        use hir::LoopSource::*;
        use hir::MatchSource::*;

        let gates: &[_] = match self {
            // A `for` loop's desugaring contains a call to `IntoIterator::into_iter`,
            // so they are not yet allowed.
            // Likewise, `?` desugars to a call to `Try::into_result`.
            Self::Loop(ForLoop) | Self::Match(ForLoopDesugar | TryDesugar | AwaitDesugar) => {
                return None;
            }

            // All other expressions are allowed.
            Self::Loop(Loop | While | WhileLet)
            | Self::Match(
                WhileDesugar | WhileLetDesugar | Normal | IfDesugar { .. } | IfLetDesugar { .. },
            ) => &[],
        };

        Some(gates)
    }
}

fn check_mod_const_bodies(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
    let mut vis = CheckConstVisitor::new(tcx);
    tcx.hir().visit_item_likes_in_module(module_def_id, &mut vis.as_deep_visitor());
}

pub(crate) fn provide(providers: &mut Providers<'_>) {
    *providers = Providers { check_mod_const_bodies, ..*providers };
}

#[derive(Copy, Clone)]
struct CheckConstVisitor<'tcx> {
    tcx: TyCtxt<'tcx>,
    const_kind: Option<hir::ConstContext>,
    def_id: Option<DefId>,
}

impl<'tcx> CheckConstVisitor<'tcx> {
    fn new(tcx: TyCtxt<'tcx>) -> Self {
        CheckConstVisitor { tcx, const_kind: None, def_id: None }
    }

    /// Emits an error when an unsupported expression is found in a const context.
    fn const_check_violated(&self, expr: NonConstExpr, span: Span) {
        let Self { tcx, def_id, const_kind } = *self;

        let features = tcx.features();
        let required_gates = expr.required_feature_gates();

        let is_feature_allowed = |feature_gate| {
            // All features require that the corresponding gate be enabled,
            // even if the function has `#[allow_internal_unstable(the_gate)]`.
            if !tcx.features().enabled(feature_gate) {
                return false;
            }

            // If `def_id` is `None`, we don't need to consider stability attributes.
            let def_id = match def_id {
                Some(x) => x,
                None => return true,
            };

            // If this crate is not using stability attributes, or this function is not claiming to be a
            // stable `const fn`, that is all that is required.
            if !tcx.features().staged_api || tcx.has_attr(def_id, sym::rustc_const_unstable) {
                return true;
            }

            // However, we cannot allow stable `const fn`s to use unstable features without an explicit
            // opt-in via `allow_internal_unstable`.
            attr::allow_internal_unstable(&tcx.get_attrs(def_id), &tcx.sess.diagnostic())
                .map_or(false, |mut features| features.any(|name| name == feature_gate))
        };

        match required_gates {
            // Don't emit an error if the user has enabled the requisite feature gates.
            Some(gates) if gates.iter().copied().all(is_feature_allowed) => return,

            // `-Zunleash-the-miri-inside-of-you` only works for expressions that don't have a
            // corresponding feature gate. This encourages nightly users to use feature gates when
            // possible.
            None if tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you => {
                tcx.sess.span_warn(span, "skipping const checks");
                return;
            }

            _ => {}
        }

        let const_kind =
            const_kind.expect("`const_check_violated` may only be called inside a const context");

        let msg = format!("{} is not allowed in a `{}`", expr.name(), const_kind.keyword_name());

        let required_gates = required_gates.unwrap_or(&[]);
        let missing_gates: Vec<_> =
            required_gates.iter().copied().filter(|&g| !features.enabled(g)).collect();

        match missing_gates.as_slice() {
            &[] => struct_span_err!(tcx.sess, span, E0744, "{}", msg).emit(),

            &[missing_primary, ref missing_secondary @ ..] => {
                let mut err = feature_err(&tcx.sess.parse_sess, missing_primary, span, &msg);

                // If multiple feature gates would be required to enable this expression, include
                // them as help messages. Don't emit a separate error for each missing feature gate.
                //
                // FIXME(ecstaticmorse): Maybe this could be incorporated into `feature_err`? This
                // is a pretty narrow case, however.
                if nightly_options::is_nightly_build() {
                    for gate in missing_secondary {
                        let note = format!(
                            "add `#![feature({})]` to the crate attributes to enable",
                            gate,
                        );
                        err.help(&note);
                    }
                }

                err.emit();
            }
        }
    }

    /// Saves the parent `const_kind` before calling `f` and restores it afterwards.
    fn recurse_into(
        &mut self,
        kind: Option<hir::ConstContext>,
        def_id: Option<DefId>,
        f: impl FnOnce(&mut Self),
    ) {
        let parent_def_id = self.def_id;
        let parent_kind = self.const_kind;
        self.def_id = def_id;
        self.const_kind = kind;
        f(self);
        self.def_id = parent_def_id;
        self.const_kind = parent_kind;
    }
}

impl<'tcx> Visitor<'tcx> for CheckConstVisitor<'tcx> {
    type Map = Map<'tcx>;

    fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
        NestedVisitorMap::OnlyBodies(self.tcx.hir())
    }

    fn visit_anon_const(&mut self, anon: &'tcx hir::AnonConst) {
        let kind = Some(hir::ConstContext::Const);
        self.recurse_into(kind, None, |this| intravisit::walk_anon_const(this, anon));
    }

    fn visit_body(&mut self, body: &'tcx hir::Body<'tcx>) {
        let owner = self.tcx.hir().body_owner_def_id(body.id());
        let kind = self.tcx.hir().body_const_context(owner);
        self.recurse_into(kind, Some(owner.to_def_id()), |this| intravisit::walk_body(this, body));
    }

    fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
        match &e.kind {
            // Skip the following checks if we are not currently in a const context.
            _ if self.const_kind.is_none() => {}

            hir::ExprKind::Loop(_, _, source) => {
                self.const_check_violated(NonConstExpr::Loop(*source), e.span);
            }

            hir::ExprKind::Match(_, _, source) => {
                let non_const_expr = match source {
                    // These are handled by `ExprKind::Loop` above.
                    hir::MatchSource::WhileDesugar
                    | hir::MatchSource::WhileLetDesugar
                    | hir::MatchSource::ForLoopDesugar => None,

                    _ => Some(NonConstExpr::Match(*source)),
                };

                if let Some(expr) = non_const_expr {
                    self.const_check_violated(expr, e.span);
                }
            }

            _ => {}
        }

        intravisit::walk_expr(self, e);
    }
}
<commit_msg>Use `LocalDefId` in HIR const-checker<commit_after>//! This pass checks HIR bodies that may be evaluated at compile-time (e.g., `const`, `static`,
//! `const fn`) for structured control flow (e.g. `if`, `while`), which is forbidden in a const
//! context.
//!
//! By the time the MIR const-checker runs, these high-level constructs have been lowered to
//! control-flow primitives (e.g., `Goto`, `SwitchInt`), making it tough to properly attribute
//! errors. We still look for those primitives in the MIR const-checker to ensure nothing slips
//! through, but errors for structured control flow in a `const` should be emitted here.

use rustc_attr as attr;
use rustc_errors::struct_span_err;
use rustc_hir as hir;
use rustc_hir::def_id::LocalDefId;
use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
use rustc_middle::hir::map::Map;
use rustc_middle::ty::query::Providers;
use rustc_middle::ty::TyCtxt;
use rustc_session::config::nightly_options;
use rustc_session::parse::feature_err;
use rustc_span::{sym, Span, Symbol};

/// An expression that is not *always* legal in a const context.
#[derive(Clone, Copy)]
enum NonConstExpr {
    Loop(hir::LoopSource),
    Match(hir::MatchSource),
}

impl NonConstExpr {
    fn name(self) -> String {
        match self {
            Self::Loop(src) => format!("`{}`", src.name()),
            Self::Match(src) => format!("`{}`", src.name()),
        }
    }

    fn required_feature_gates(self) -> Option<&'static [Symbol]> {
        use hir::LoopSource::*;
        use hir::MatchSource::*;

        let gates: &[_] = match self {
            // A `for` loop's desugaring contains a call to `IntoIterator::into_iter`,
            // so they are not yet allowed.
            // Likewise, `?` desugars to a call to `Try::into_result`.
            Self::Loop(ForLoop) | Self::Match(ForLoopDesugar | TryDesugar | AwaitDesugar) => {
                return None;
            }

            // All other expressions are allowed.
            Self::Loop(Loop | While | WhileLet)
            | Self::Match(
                WhileDesugar | WhileLetDesugar | Normal | IfDesugar { .. } | IfLetDesugar { .. },
            ) => &[],
        };

        Some(gates)
    }
}

fn check_mod_const_bodies(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
    let mut vis = CheckConstVisitor::new(tcx);
    tcx.hir().visit_item_likes_in_module(module_def_id, &mut vis.as_deep_visitor());
}

pub(crate) fn provide(providers: &mut Providers<'_>) {
    *providers = Providers { check_mod_const_bodies, ..*providers };
}

#[derive(Copy, Clone)]
struct CheckConstVisitor<'tcx> {
    tcx: TyCtxt<'tcx>,
    const_kind: Option<hir::ConstContext>,
    def_id: Option<LocalDefId>,
}

impl<'tcx> CheckConstVisitor<'tcx> {
    fn new(tcx: TyCtxt<'tcx>) -> Self {
        CheckConstVisitor { tcx, const_kind: None, def_id: None }
    }

    /// Emits an error when an unsupported expression is found in a const context.
    fn const_check_violated(&self, expr: NonConstExpr, span: Span) {
        let Self { tcx, def_id, const_kind } = *self;

        let features = tcx.features();
        let required_gates = expr.required_feature_gates();

        let is_feature_allowed = |feature_gate| {
            // All features require that the corresponding gate be enabled,
            // even if the function has `#[allow_internal_unstable(the_gate)]`.
            if !tcx.features().enabled(feature_gate) {
                return false;
            }

            // If `def_id` is `None`, we don't need to consider stability attributes.
            let def_id = match def_id {
                Some(x) => x.to_def_id(),
                None => return true,
            };

            // If this crate is not using stability attributes, or this function is not claiming to be a
            // stable `const fn`, that is all that is required.
            if !tcx.features().staged_api || tcx.has_attr(def_id, sym::rustc_const_unstable) {
                return true;
            }

            // However, we cannot allow stable `const fn`s to use unstable features without an explicit
            // opt-in via `allow_internal_unstable`.
            attr::allow_internal_unstable(&tcx.get_attrs(def_id), &tcx.sess.diagnostic())
                .map_or(false, |mut features| features.any(|name| name == feature_gate))
        };

        match required_gates {
            // Don't emit an error if the user has enabled the requisite feature gates.
            Some(gates) if gates.iter().copied().all(is_feature_allowed) => return,

            // `-Zunleash-the-miri-inside-of-you` only works for expressions that don't have a
            // corresponding feature gate. This encourages nightly users to use feature gates when
            // possible.
            None if tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you => {
                tcx.sess.span_warn(span, "skipping const checks");
                return;
            }

            _ => {}
        }

        let const_kind =
            const_kind.expect("`const_check_violated` may only be called inside a const context");

        let msg = format!("{} is not allowed in a `{}`", expr.name(), const_kind.keyword_name());

        let required_gates = required_gates.unwrap_or(&[]);
        let missing_gates: Vec<_> =
            required_gates.iter().copied().filter(|&g| !features.enabled(g)).collect();

        match missing_gates.as_slice() {
            &[] => struct_span_err!(tcx.sess, span, E0744, "{}", msg).emit(),

            &[missing_primary, ref missing_secondary @ ..] => {
                let mut err = feature_err(&tcx.sess.parse_sess, missing_primary, span, &msg);

                // If multiple feature gates would be required to enable this expression, include
                // them as help messages. Don't emit a separate error for each missing feature gate.
                //
                // FIXME(ecstaticmorse): Maybe this could be incorporated into `feature_err`? This
                // is a pretty narrow case, however.
                if nightly_options::is_nightly_build() {
                    for gate in missing_secondary {
                        let note = format!(
                            "add `#![feature({})]` to the crate attributes to enable",
                            gate,
                        );
                        err.help(&note);
                    }
                }

                err.emit();
            }
        }
    }

    /// Saves the parent `const_kind` before calling `f` and restores it afterwards.
    fn recurse_into(
        &mut self,
        kind: Option<hir::ConstContext>,
        def_id: Option<LocalDefId>,
        f: impl FnOnce(&mut Self),
    ) {
        let parent_def_id = self.def_id;
        let parent_kind = self.const_kind;
        self.def_id = def_id;
        self.const_kind = kind;
        f(self);
        self.def_id = parent_def_id;
        self.const_kind = parent_kind;
    }
}

impl<'tcx> Visitor<'tcx> for CheckConstVisitor<'tcx> {
    type Map = Map<'tcx>;

    fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
        NestedVisitorMap::OnlyBodies(self.tcx.hir())
    }

    fn visit_anon_const(&mut self, anon: &'tcx hir::AnonConst) {
        let kind = Some(hir::ConstContext::Const);
        self.recurse_into(kind, None, |this| intravisit::walk_anon_const(this, anon));
    }

    fn visit_body(&mut self, body: &'tcx hir::Body<'tcx>) {
        let owner = self.tcx.hir().body_owner_def_id(body.id());
        let kind = self.tcx.hir().body_const_context(owner);
        self.recurse_into(kind, Some(owner), |this| intravisit::walk_body(this, body));
    }

    fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
        match &e.kind {
            // Skip the following checks if we are not currently in a const context.
            _ if self.const_kind.is_none() => {}

            hir::ExprKind::Loop(_, _, source) => {
                self.const_check_violated(NonConstExpr::Loop(*source), e.span);
            }

            hir::ExprKind::Match(_, _, source) => {
                let non_const_expr = match source {
                    // These are handled by `ExprKind::Loop` above.
                    hir::MatchSource::WhileDesugar
                    | hir::MatchSource::WhileLetDesugar
                    | hir::MatchSource::ForLoopDesugar => None,

                    _ => Some(NonConstExpr::Match(*source)),
                };

                if let Some(expr) = non_const_expr {
                    self.const_check_violated(expr, e.span);
                }
            }

            _ => {}
        }

        intravisit::walk_expr(self, e);
    }
}
<|endoftext|>


<commit_before>syntax::register_diagnostics! {
/*
E0014: r##"
Constants can only be initialized by a constant value or, in a future
version of Rust, a call to a const function. This error indicates the use
of a path (like a::b, or x) denoting something other than one of these
allowed items. Erroneous code xample:

```compile_fail
const FOO: i32 = { let x = 0; x }; // 'x' isn't a constant nor a function!
```

To avoid it, you have to replace the non-constant value:

```
const FOO: i32 = { const X : i32 = 0; X };
// or even:
const FOO2: i32 = { 0 }; // but brackets are useless here
```
"##,
*/

E0130: r##"
You declared a pattern as an argument in a foreign function declaration.
Erroneous code example:

```compile_fail
extern {
    fn foo((a, b): (u32, u32)); // error: patterns aren't allowed in foreign
                                //        function declarations
}
```

Please replace the pattern argument with a regular one. Example:

```
struct SomeStruct {
    a: u32,
    b: u32,
}

extern {
    fn foo(s: SomeStruct); // ok!
}
```

Or:

```
extern {
    fn foo(a: (u32, u32)); // ok!
}
```
"##,

E0197: r##"
Inherent implementations (one that do not implement a trait but provide
methods associated with a type) are always safe because they are not
implementing an unsafe trait. Removing the `unsafe` keyword from the inherent
implementation will resolve this error.

```compile_fail,E0197
struct Foo;

// this will cause this error
unsafe impl Foo { }
// converting it to this will fix it
impl Foo { }
```
"##,

E0198: r##"
A negative implementation is one that excludes a type from implementing a
particular trait. Not being able to use a trait is always a safe operation,
so negative implementations are always safe and never need to be marked as
unsafe.

```compile_fail
#![feature(optin_builtin_traits)]

struct Foo;

// unsafe is unnecessary
unsafe impl !Clone for Foo { }
```

This will compile:

```ignore (ignore auto_trait future compatibility warning)
#![feature(optin_builtin_traits)]

struct Foo;

auto trait Enterprise {}

impl !Enterprise for Foo { }
```

Please note that negative impls are only allowed for auto traits.
"##,

E0267: r##"
This error indicates the use of a loop keyword (`break` or `continue`) inside a
closure but outside of any loop. Erroneous code example:

```compile_fail,E0267
let w = || { break; }; // error: `break` inside of a closure
```

`break` and `continue` keywords can be used as normal inside closures as long as
they are also contained within a loop. To halt the execution of a closure you
should instead use a return statement. Example:

```
let w = || {
    for _ in 0..10 {
        break;
    }
};

w();
```
"##,

E0268: r##"
This error indicates the use of a loop keyword (`break` or `continue`) outside
of a loop. Without a loop to break out of or continue in, no sensible action can
be taken. Erroneous code example:

```compile_fail,E0268
fn some_func() {
    break; // error: `break` outside of a loop
}
```

Please verify that you are using `break` and `continue` only in loops. Example:

```
fn some_func() {
    for _ in 0..10 {
        break; // ok!
    }
}
```
"##,

E0379: r##"
Trait methods cannot be declared `const` by design. For more information, see
[RFC 911].

[RFC 911]: https://github.com/rust-lang/rfcs/pull/911
"##,

E0380: r##"
Auto traits cannot have methods or associated items.
For more information see the [opt-in builtin traits RFC][RFC 19].

[RFC 19]: https://github.com/rust-lang/rfcs/blob/master/text/0019-opt-in-builtin-traits.md
"##,

E0449: r##"
A visibility qualifier was used when it was unnecessary. Erroneous code
examples:

```compile_fail,E0449
struct Bar;

trait Foo {
    fn foo();
}

pub impl Bar {} // error: unnecessary visibility qualifier

pub impl Foo for Bar { // error: unnecessary visibility qualifier
    pub fn foo() {} // error: unnecessary visibility qualifier
}
```

To fix this error, please remove the visibility qualifier when it is not
required. Example:

```
struct Bar;

trait Foo {
    fn foo();
}

// Directly implemented methods share the visibility of the type itself,
// so `pub` is unnecessary here
impl Bar {}

// Trait methods share the visibility of the trait, so `pub` is
// unnecessary in either case
impl Foo for Bar {
    fn foo() {}
}
```
"##,

E0590: r##"
`break` or `continue` must include a label when used in the condition of a
`while` loop.

Example of erroneous code:

```compile_fail
while break {}
```

To fix this, add a label specifying which loop is being broken out of:
```
'foo: while break 'foo {}
```
"##,

E0571: r##"
A `break` statement with an argument appeared in a non-`loop` loop.

Example of erroneous code:

```compile_fail,E0571
# let mut i = 1;
# fn satisfied(n: usize) -> bool { n % 23 == 0 }
let result = while true {
    if satisfied(i) {
        break 2*i; // error: `break` with value from a `while` loop
    }
    i += 1;
};
```

The `break` statement can take an argument (which will be the value of the loop
expression if the `break` statement is executed) in `loop` loops, but not
`for`, `while`, or `while let` loops.

Make sure `break value;` statements only occur in `loop` loops:

```
# let mut i = 1;
# fn satisfied(n: usize) -> bool { n % 23 == 0 }
let result = loop { // ok!
    if satisfied(i) {
        break 2*i;
    }
    i += 1;
};
```
"##,

E0642: r##"
Trait methods currently cannot take patterns as arguments.

Example of erroneous code:

```compile_fail,E0642
trait Foo {
    fn foo((x, y): (i32, i32)); // error: patterns aren't allowed
                                //        in trait methods
}
```

You can instead use a single name for the argument:

```
trait Foo {
    fn foo(x_and_y: (i32, i32)); // ok!
}
```
"##,

E0695: r##"
A `break` statement without a label appeared inside a labeled block.

Example of erroneous code:

```compile_fail,E0695
# #![feature(label_break_value)]
loop {
    'a: {
        break;
    }
}
```

Make sure to always label the `break`:

```
# #![feature(label_break_value)]
'l: loop {
    'a: {
        break 'l;
    }
}
```

Or if you want to `break` the labeled block:

```
# #![feature(label_break_value)]
loop {
    'a: {
        break 'a;
    }
    break;
}
```
"##,

E0670: r##"
Rust 2015 does not permit the use of `async fn`.

Example of erroneous code:

```compile_fail,E0670
async fn foo() {}
```

Switch to the Rust 2018 edition to use `async fn`.
"##,

// This shouldn't really ever trigger since the repeated value error comes first
E0136: r##"
A binary can only have one entry point, and by default that entry point is the
function `main()`. If there are multiple such functions, please rename one.
"##,

E0137: r##"
More than one function was declared with the `#[main]` attribute.

Erroneous code example:

```compile_fail,E0137
#![feature(main)]

#[main]
fn foo() {}

#[main]
fn f() {} // error: multiple functions with a `#[main]` attribute
```

This error indicates that the compiler found multiple functions with the
`#[main]` attribute. This is an error because there must be a unique entry
point into a Rust program. Example:

```
#![feature(main)]

#[main]
fn f() {} // ok!
```
"##,

E0138: r##"
More than one function was declared with the `#[start]` attribute.

Erroneous code example:

```compile_fail,E0138
#![feature(start)]

#[start]
fn foo(argc: isize, argv: *const *const u8) -> isize {}

#[start]
fn f(argc: isize, argv: *const *const u8) -> isize {}
// error: multiple 'start' functions
```

This error indicates that the compiler found multiple functions with the
`#[start]` attribute. This is an error because there must be a unique entry
point into a Rust program. Example:

```
#![feature(start)]

#[start]
fn foo(argc: isize, argv: *const *const u8) -> isize { 0 } // ok!
```
"##,

E0601: r##"
No `main` function was found in a binary crate. To fix this error, add a
`main` function. For example:

```
fn main() {
    // Your program will start here.
    println!("Hello world!");
}
```

If you don't know the basics of Rust, you can go look to the Rust Book to get
started: https://doc.rust-lang.org/book/
"##,

E0591: r##"
Per [RFC 401][rfc401], if you have a function declaration `foo`:

```
// For the purposes of this explanation, all of these
// different kinds of `fn` declarations are equivalent:
struct S;
fn foo(x: S) { /* ... */ }
# #[cfg(for_demonstration_only)]
extern "C" { fn foo(x: S); }
# #[cfg(for_demonstration_only)]
impl S { fn foo(self) { /* ... */ } }
```

the type of `foo` is **not** `fn(S)`, as one might expect.
Rather, it is a unique, zero-sized marker type written here as `typeof(foo)`.
However, `typeof(foo)` can be _coerced_ to a function pointer `fn(S)`,
so you rarely notice this:

```
# struct S;
# fn foo(_: S) {}
let x: fn(S) = foo; // OK, coerces
```

The reason that this matter is that the type `fn(S)` is not specific to
any particular function: it's a function _pointer_. So calling `x()` results
in a virtual call, whereas `foo()` is statically dispatched, because the type
of `foo` tells us precisely what function is being called.

As noted above, coercions mean that most code doesn't have to be
concerned with this distinction. However, you can tell the difference
when using **transmute** to convert a fn item into a fn pointer.

This is sometimes done as part of an FFI:

```compile_fail,E0591
extern "C" fn foo(userdata: Box<i32>) {
    /* ... */
}

# fn callback(_: extern "C" fn(*mut i32)) {}
# use std::mem::transmute;
# unsafe {
let f: extern "C" fn(*mut i32) = transmute(foo);
callback(f);
# }
```

Here, transmute is being used to convert the types of the fn arguments.
This pattern is incorrect because, because the type of `foo` is a function
**item** (`typeof(foo)`), which is zero-sized, and the target type (`fn()`)
is a function pointer, which is not zero-sized.
This pattern should be rewritten. There are a few possible ways to do this:

- change the original fn declaration to match the expected signature,
  and do the cast in the fn body (the preferred option)
- cast the fn item fo a fn pointer before calling transmute, as shown here:

    ```
    # extern "C" fn foo(_: Box<i32>) {}
    # use std::mem::transmute;
    # unsafe {
    let f: extern "C" fn(*mut i32) = transmute(foo as extern "C" fn(_));
    let f: extern "C" fn(*mut i32) = transmute(foo as usize); // works too
    # }
    ```

The same applies to transmutes to `*mut fn()`, which were observed in practice.
Note though that use of this type is generally incorrect.
The intention is typically to describe a function pointer, but just `fn()`
alone suffices for that. `*mut fn()` is a pointer to a fn pointer.
(Since these values are typically just passed to C code, however, this rarely
makes a difference in practice.)

[rfc401]: https://github.com/rust-lang/rfcs/blob/master/text/0401-coercions.md
"##,

E0512: r##"
Transmute with two differently sized types was attempted. Erroneous code
example:

```compile_fail,E0512
fn takes_u8(_: u8) {}

fn main() {
    unsafe { takes_u8(::std::mem::transmute(0u16)); }
    // error: cannot transmute between types of different sizes,
    //        or dependently-sized types
}
```

Please use types with same size or use the expected type directly. Example:

```
fn takes_u8(_: u8) {}

fn main() {
    unsafe { takes_u8(::std::mem::transmute(0i8)); } // ok!
    // or:
    unsafe { takes_u8(0u8); } // ok!
}
```
"##,

;
    E0226, // only a single explicit lifetime bound is permitted
    E0472, // asm! is unsupported on this target
    E0561, // patterns aren't allowed in function pointer types
    E0567, // auto traits can not have generic parameters
    E0568, // auto traits can not have super traits
    E0666, // nested `impl Trait` is illegal
    E0667, // `impl Trait` in projections
    E0696, // `continue` pointing to a labeled block
    E0706, // `async fn` in trait
}
<commit_msg>Rollup merge of #65095 - GuillaumeGomez:sort-librustc_passes-err-codes, r=varkor<commit_after>syntax::register_diagnostics! {
/*
E0014: r##"
Constants can only be initialized by a constant value or, in a future
version of Rust, a call to a const function. This error indicates the use
of a path (like a::b, or x) denoting something other than one of these
allowed items. Erroneous code xample:

```compile_fail
const FOO: i32 = { let x = 0; x }; // 'x' isn't a constant nor a function!
```

To avoid it, you have to replace the non-constant value:

```
const FOO: i32 = { const X : i32 = 0; X };
// or even:
const FOO2: i32 = { 0 }; // but brackets are useless here
```
"##,
*/

E0130: r##"
You declared a pattern as an argument in a foreign function declaration.
Erroneous code example:

```compile_fail
extern {
    fn foo((a, b): (u32, u32)); // error: patterns aren't allowed in foreign
                                //        function declarations
}
```

Please replace the pattern argument with a regular one. Example:

```
struct SomeStruct {
    a: u32,
    b: u32,
}

extern {
    fn foo(s: SomeStruct); // ok!
}
```

Or:

```
extern {
    fn foo(a: (u32, u32)); // ok!
}
```
"##,

// This shouldn't really ever trigger since the repeated value error comes first
E0136: r##"
A binary can only have one entry point, and by default that entry point is the
function `main()`. If there are multiple such functions, please rename one.
"##,

E0137: r##"
More than one function was declared with the `#[main]` attribute.

Erroneous code example:

```compile_fail,E0137
#![feature(main)]

#[main]
fn foo() {}

#[main]
fn f() {} // error: multiple functions with a `#[main]` attribute
```

This error indicates that the compiler found multiple functions with the
`#[main]` attribute. This is an error because there must be a unique entry
point into a Rust program. Example:

```
#![feature(main)]

#[main]
fn f() {} // ok!
```
"##,

E0138: r##"
More than one function was declared with the `#[start]` attribute.

Erroneous code example:

```compile_fail,E0138
#![feature(start)]

#[start]
fn foo(argc: isize, argv: *const *const u8) -> isize {}

#[start]
fn f(argc: isize, argv: *const *const u8) -> isize {}
// error: multiple 'start' functions
```

This error indicates that the compiler found multiple functions with the
`#[start]` attribute. This is an error because there must be a unique entry
point into a Rust program. Example:

```
#![feature(start)]

#[start]
fn foo(argc: isize, argv: *const *const u8) -> isize { 0 } // ok!
```
"##,

E0197: r##"
Inherent implementations (one that do not implement a trait but provide
methods associated with a type) are always safe because they are not
implementing an unsafe trait. Removing the `unsafe` keyword from the inherent
implementation will resolve this error.

```compile_fail,E0197
struct Foo;

// this will cause this error
unsafe impl Foo { }
// converting it to this will fix it
impl Foo { }
```
"##,

E0198: r##"
A negative implementation is one that excludes a type from implementing a
particular trait. Not being able to use a trait is always a safe operation,
so negative implementations are always safe and never need to be marked as
unsafe.

```compile_fail
#![feature(optin_builtin_traits)]

struct Foo;

// unsafe is unnecessary
unsafe impl !Clone for Foo { }
```

This will compile:

```ignore (ignore auto_trait future compatibility warning)
#![feature(optin_builtin_traits)]

struct Foo;

auto trait Enterprise {}

impl !Enterprise for Foo { }
```

Please note that negative impls are only allowed for auto traits.
"##,

E0267: r##"
This error indicates the use of a loop keyword (`break` or `continue`) inside a
closure but outside of any loop. Erroneous code example:

```compile_fail,E0267
let w = || { break; }; // error: `break` inside of a closure
```

`break` and `continue` keywords can be used as normal inside closures as long as
they are also contained within a loop. To halt the execution of a closure you
should instead use a return statement. Example:

```
let w = || {
    for _ in 0..10 {
        break;
    }
};

w();
```
"##,

E0268: r##"
This error indicates the use of a loop keyword (`break` or `continue`) outside
of a loop. Without a loop to break out of or continue in, no sensible action can
be taken. Erroneous code example:

```compile_fail,E0268
fn some_func() {
    break; // error: `break` outside of a loop
}
```

Please verify that you are using `break` and `continue` only in loops. Example:

```
fn some_func() {
    for _ in 0..10 {
        break; // ok!
    }
}
```
"##,

E0379: r##"
Trait methods cannot be declared `const` by design. For more information, see
[RFC 911].

[RFC 911]: https://github.com/rust-lang/rfcs/pull/911
"##,

E0380: r##"
Auto traits cannot have methods or associated items.
For more information see the [opt-in builtin traits RFC][RFC 19].

[RFC 19]: https://github.com/rust-lang/rfcs/blob/master/text/0019-opt-in-builtin-traits.md
"##,

E0449: r##"
A visibility qualifier was used when it was unnecessary. Erroneous code
examples:

```compile_fail,E0449
struct Bar;

trait Foo {
    fn foo();
}

pub impl Bar {} // error: unnecessary visibility qualifier

pub impl Foo for Bar { // error: unnecessary visibility qualifier
    pub fn foo() {} // error: unnecessary visibility qualifier
}
```

To fix this error, please remove the visibility qualifier when it is not
required. Example:

```
struct Bar;

trait Foo {
    fn foo();
}

// Directly implemented methods share the visibility of the type itself,
// so `pub` is unnecessary here
impl Bar {}

// Trait methods share the visibility of the trait, so `pub` is
// unnecessary in either case
impl Foo for Bar {
    fn foo() {}
}
```
"##,

E0512: r##"
Transmute with two differently sized types was attempted. Erroneous code
example:

```compile_fail,E0512
fn takes_u8(_: u8) {}

fn main() {
    unsafe { takes_u8(::std::mem::transmute(0u16)); }
    // error: cannot transmute between types of different sizes,
    //        or dependently-sized types
}
```

Please use types with same size or use the expected type directly. Example:

```
fn takes_u8(_: u8) {}

fn main() {
    unsafe { takes_u8(::std::mem::transmute(0i8)); } // ok!
    // or:
    unsafe { takes_u8(0u8); } // ok!
}
```
"##,

E0571: r##"
A `break` statement with an argument appeared in a non-`loop` loop.

Example of erroneous code:

```compile_fail,E0571
# let mut i = 1;
# fn satisfied(n: usize) -> bool { n % 23 == 0 }
let result = while true {
    if satisfied(i) {
        break 2*i; // error: `break` with value from a `while` loop
    }
    i += 1;
};
```

The `break` statement can take an argument (which will be the value of the loop
expression if the `break` statement is executed) in `loop` loops, but not
`for`, `while`, or `while let` loops.

Make sure `break value;` statements only occur in `loop` loops:

```
# let mut i = 1;
# fn satisfied(n: usize) -> bool { n % 23 == 0 }
let result = loop { // ok!
    if satisfied(i) {
        break 2*i;
    }
    i += 1;
};
```
"##,

E0590: r##"
`break` or `continue` must include a label when used in the condition of a
`while` loop.

Example of erroneous code:

```compile_fail
while break {}
```

To fix this, add a label specifying which loop is being broken out of:
```
'foo: while break 'foo {}
```
"##,

E0591: r##"
Per [RFC 401][rfc401], if you have a function declaration `foo`:

```
// For the purposes of this explanation, all of these
// different kinds of `fn` declarations are equivalent:
struct S;
fn foo(x: S) { /* ... */ }
# #[cfg(for_demonstration_only)]
extern "C" { fn foo(x: S); }
# #[cfg(for_demonstration_only)]
impl S { fn foo(self) { /* ... */ } }
```

the type of `foo` is **not** `fn(S)`, as one might expect.
Rather, it is a unique, zero-sized marker type written here as `typeof(foo)`.
However, `typeof(foo)` can be _coerced_ to a function pointer `fn(S)`,
so you rarely notice this:

```
# struct S;
# fn foo(_: S) {}
let x: fn(S) = foo; // OK, coerces
```

The reason that this matter is that the type `fn(S)` is not specific to
any particular function: it's a function _pointer_. So calling `x()` results
in a virtual call, whereas `foo()` is statically dispatched, because the type
of `foo` tells us precisely what function is being called.

As noted above, coercions mean that most code doesn't have to be
concerned with this distinction. However, you can tell the difference
when using **transmute** to convert a fn item into a fn pointer.

This is sometimes done as part of an FFI:

```compile_fail,E0591
extern "C" fn foo(userdata: Box<i32>) {
    /* ... */
}

# fn callback(_: extern "C" fn(*mut i32)) {}
# use std::mem::transmute;
# unsafe {
let f: extern "C" fn(*mut i32) = transmute(foo);
callback(f);
# }
```

Here, transmute is being used to convert the types of the fn arguments.
This pattern is incorrect because, because the type of `foo` is a function
**item** (`typeof(foo)`), which is zero-sized, and the target type (`fn()`)
is a function pointer, which is not zero-sized.
This pattern should be rewritten. There are a few possible ways to do this:

- change the original fn declaration to match the expected signature,
  and do the cast in the fn body (the preferred option)
- cast the fn item fo a fn pointer before calling transmute, as shown here:

    ```
    # extern "C" fn foo(_: Box<i32>) {}
    # use std::mem::transmute;
    # unsafe {
    let f: extern "C" fn(*mut i32) = transmute(foo as extern "C" fn(_));
    let f: extern "C" fn(*mut i32) = transmute(foo as usize); // works too
    # }
    ```

The same applies to transmutes to `*mut fn()`, which were observed in practice.
Note though that use of this type is generally incorrect.
The intention is typically to describe a function pointer, but just `fn()`
alone suffices for that. `*mut fn()` is a pointer to a fn pointer.
(Since these values are typically just passed to C code, however, this rarely
makes a difference in practice.)

[rfc401]: https://github.com/rust-lang/rfcs/blob/master/text/0401-coercions.md
"##,

E0601: r##"
No `main` function was found in a binary crate. To fix this error, add a
`main` function. For example:

```
fn main() {
    // Your program will start here.
    println!("Hello world!");
}
```

If you don't know the basics of Rust, you can go look to the Rust Book to get
started: https://doc.rust-lang.org/book/
"##,

E0642: r##"
Trait methods currently cannot take patterns as arguments.

Example of erroneous code:

```compile_fail,E0642
trait Foo {
    fn foo((x, y): (i32, i32)); // error: patterns aren't allowed
                                //        in trait methods
}
```

You can instead use a single name for the argument:

```
trait Foo {
    fn foo(x_and_y: (i32, i32)); // ok!
}
```
"##,

E0695: r##"
A `break` statement without a label appeared inside a labeled block.

Example of erroneous code:

```compile_fail,E0695
# #![feature(label_break_value)]
loop {
    'a: {
        break;
    }
}
```

Make sure to always label the `break`:

```
# #![feature(label_break_value)]
'l: loop {
    'a: {
        break 'l;
    }
}
```

Or if you want to `break` the labeled block:

```
# #![feature(label_break_value)]
loop {
    'a: {
        break 'a;
    }
    break;
}
```
"##,

E0670: r##"
Rust 2015 does not permit the use of `async fn`.

Example of erroneous code:

```compile_fail,E0670
async fn foo() {}
```

Switch to the Rust 2018 edition to use `async fn`.
"##,

;
    E0226, // only a single explicit lifetime bound is permitted
    E0472, // asm! is unsupported on this target
    E0561, // patterns aren't allowed in function pointer types
    E0567, // auto traits can not have generic parameters
    E0568, // auto traits can not have super traits
    E0666, // nested `impl Trait` is illegal
    E0667, // `impl Trait` in projections
    E0696, // `continue` pointing to a labeled block
    E0706, // `async fn` in trait
}
<|endoftext|>


<commit_before>/// Construct a `serde_json::Value` from a JSON literal.
///
/// ```rust
/// # #![allow(unused_variables)]
/// # #[macro_use] extern crate serde_json;
/// # fn main() {
/// let value = json!({
///     "code": 200,
///     "success": true,
///     "payload": {
///         "features": [
///             "serde",
///             "json"
///         ]
///     }
/// });
/// # }
/// ```
///
/// Any variable or expression that implements Serde's `Serialize` trait can be
/// interpolated into the JSON literal just by referring to it.
///
/// ```rust
/// # #![allow(unused_variables)]
/// # #[macro_use] extern crate serde_json;
/// # fn main() {
/// let code = 200;
/// let features = vec!["serde", "json"];
///
/// let value = json!({
///    "code": code,
///    "success": code == 200,
///    "payload": {
///        features[0]: features[1]
///    }
/// });
/// # }
/// ```
///
/// Trailing commas are allowed inside both arrays and objects.
///
/// ```rust
/// # #![allow(unused_variables)]
/// # #[macro_use] extern crate serde_json;
/// # fn main() {
/// let value = json!([
///     "notice",
///     "the",
///     "trailing",
///     "comma -->",
/// ]);
/// # }
/// ```
#[macro_export]
macro_rules! json {
    // Hide distracting implementation details from the generated rustdoc.
    ($($json:tt)+) => {
        json_internal!($($json)+)
    };
}

#[macro_export]
#[doc(hidden)]
macro_rules! json_internal {
    (null) => {
        $crate::Value::Null
    };

    (true) => {
        $crate::Value::Bool(true)
    };

    (false) => {
        $crate::Value::Bool(false)
    };

    ([]) => {
        $crate::Value::Array(Vec::new())
    };

    ([ $($tt:tt)+ ]) => {{
        let mut array = Vec::new();
        json_within_array!(array () $($tt)+);
        $crate::Value::Array(array)
    }};

    ({}) => {
        $crate::Value::Object($crate::Map::new())
    };

    ({ $($tt:tt)+ }) => {{
        let mut object = $crate::Map::new();
        json_within_object!(object () () $($tt)+);
        $crate::Value::Object(object)
    }};

    // Any Serialize type: numbers, strings, struct literals, variables etc.
    ($other:expr) => {
        $crate::to_value($other).unwrap()
    };
}

// TT muncher for parsing the inside of an array [...]. Each element is pushed
// into the given array variable.
//
// Must be invoked as: json_within_array!(var () $($tt)*)
#[macro_export]
#[doc(hidden)]
macro_rules! json_within_array {
    // Done.
    ($array:ident ()) => {};

    // Push a single element. The element must be more than zero tokens.
    ($array:ident ($($elem:tt)+)) => {
        $array.push(json!($($elem)+));
    };

    // Misplaced comma. Trigger a reasonable error message by failing to match
    // the comma in the recursive call.
    ($array:ident () , $($rest:tt)*) => {
        json_within_array!($array ,);
    };

    // Found a comma separator. Push whatever we have so far and move on to
    // remaining elements. Trailing comma is allowed.
    ($array:ident ($($elem:tt)+) , $($rest:tt)*) => {
        json_within_array!($array ($($elem)+));
        json_within_array!($array () $($rest)*);
    };

    // Munch a token into the current element.
    ($array:ident ($($elem:tt)*) $tt:tt $($rest:tt)*) => {
        json_within_array!($array ($($elem)* $tt) $($rest)*);
    };
}

// TT muncher for parsing the inside of an object {...}. Each entry is inserted
// into the given map variable.
//
// Must be invoked as: json_within_object!(var () () $($tt)*)
#[macro_export]
#[doc(hidden)]
macro_rules! json_within_object {
    // Done.
    ($object:ident () ()) => {};

    // Insert a single entry. The key and value must both be more than zero
    // tokens. The key must be Into-convertible to String.
    ($object:ident ($($key:tt)+) : ($($value:tt)+)) => {
        $object.insert(($($key)+).into(), json!($($value)+));
    };

    // Misplaced colon. Trigger a reasonable error message by failing to match
    // the colon in the recursive call.
    ($object:ident () () : $($rest:tt)*) => {
        json_within_object!($object :);
    };

    // Found a comma inside a key. Trigger a reasonable error message by failing
    // to match the comma in the recursive call.
    ($object:ident ($($key:tt)*) () , $($rest:tt)*) => {
        json_within_object!($object ,);
    };

    // Found a colon after a key. Move on to the value.
    ($object:ident ($($key:tt)+) () : $($rest:tt)*) => {
        json_within_object!($object ($($key)+) : () $($rest)*);
    };

    // Misplaced comma. Trigger a reasonable error message by failing to match
    // the comma in the recursive call.
    ($object:ident ($($key:tt)+) : () , $($rest:tt)*) => {
        json_within_object!($object ,);
    };

    // Found a comma after a value. Insert whatever we have so far and move on
    // to remaining elements. Trailing comma is allowed.
    ($object:ident ($($key:tt)+) : ($($value:tt)+) , $($rest:tt)*) => {
        json_within_object!($object ($($key)+) : ($($value)+));
        json_within_object!($object () () $($rest)*);
    };

    // Munch a token into the current key.
    ($object:ident ($($key:tt)*) () $tt:tt $($rest:tt)*) => {
        json_within_object!($object ($($key)* $tt) () $($rest)*)
    };

    // Munch a token into the current value.
    ($object:ident ($($key:tt)+) : ($($value:tt)*) $tt:tt $($rest:tt)*) => {
        json_within_object!($object ($($key)+) : ($($value)* $tt) $($rest)*)
    };
}
<commit_msg>Rearrange json macro to make top-level structure clear<commit_after>/// Construct a `serde_json::Value` from a JSON literal.
///
/// ```rust
/// # #![allow(unused_variables)]
/// # #[macro_use] extern crate serde_json;
/// # fn main() {
/// let value = json!({
///     "code": 200,
///     "success": true,
///     "payload": {
///         "features": [
///             "serde",
///             "json"
///         ]
///     }
/// });
/// # }
/// ```
///
/// Any variable or expression that implements Serde's `Serialize` trait can be
/// interpolated into the JSON literal just by referring to it.
///
/// ```rust
/// # #![allow(unused_variables)]
/// # #[macro_use] extern crate serde_json;
/// # fn main() {
/// let code = 200;
/// let features = vec!["serde", "json"];
///
/// let value = json!({
///    "code": code,
///    "success": code == 200,
///    "payload": {
///        features[0]: features[1]
///    }
/// });
/// # }
/// ```
///
/// Trailing commas are allowed inside both arrays and objects.
///
/// ```rust
/// # #![allow(unused_variables)]
/// # #[macro_use] extern crate serde_json;
/// # fn main() {
/// let value = json!([
///     "notice",
///     "the",
///     "trailing",
///     "comma -->",
/// ]);
/// # }
/// ```
#[macro_export]
macro_rules! json {
    // Hide distracting implementation details from the generated rustdoc.
    ($($json:tt)+) => {
        json_internal!($($json)+)
    };
}

#[macro_export]
#[doc(hidden)]
macro_rules! json_internal {
    (null) => {
        $crate::Value::Null
    };

    (true) => {
        $crate::Value::Bool(true)
    };

    (false) => {
        $crate::Value::Bool(false)
    };

    ([]) => {
        $crate::Value::Array(Vec::new())
    };

    ([ $($tt:tt)+ ]) => {
        $crate::Value::Array({
            let mut array = Vec::new();
            json_within_array!(array () $($tt)+);
            array
        })
    };

    ({}) => {
        $crate::Value::Object($crate::Map::new())
    };

    ({ $($tt:tt)+ }) => {
        $crate::Value::Object({
            let mut object = $crate::Map::new();
            json_within_object!(object () () $($tt)+);
            object
        })
    };

    // Any Serialize type: numbers, strings, struct literals, variables etc.
    ($other:expr) => {
        $crate::to_value($other).unwrap()
    };
}

// TT muncher for parsing the inside of an array [...]. Each element is pushed
// into the given array variable.
//
// Must be invoked as: json_within_array!(var () $($tt)*)
#[macro_export]
#[doc(hidden)]
macro_rules! json_within_array {
    // Done.
    ($array:ident ()) => {};

    // Push a single element. The element must be more than zero tokens.
    ($array:ident ($($elem:tt)+)) => {
        $array.push(json!($($elem)+));
    };

    // Misplaced comma. Trigger a reasonable error message by failing to match
    // the comma in the recursive call.
    ($array:ident () , $($rest:tt)*) => {
        json_within_array!($array ,);
    };

    // Found a comma separator. Push whatever we have so far and move on to
    // remaining elements. Trailing comma is allowed.
    ($array:ident ($($elem:tt)+) , $($rest:tt)*) => {
        json_within_array!($array ($($elem)+));
        json_within_array!($array () $($rest)*);
    };

    // Munch a token into the current element.
    ($array:ident ($($elem:tt)*) $tt:tt $($rest:tt)*) => {
        json_within_array!($array ($($elem)* $tt) $($rest)*);
    };
}

// TT muncher for parsing the inside of an object {...}. Each entry is inserted
// into the given map variable.
//
// Must be invoked as: json_within_object!(var () () $($tt)*)
#[macro_export]
#[doc(hidden)]
macro_rules! json_within_object {
    // Done.
    ($object:ident () ()) => {};

    // Insert a single entry. The key and value must both be more than zero
    // tokens. The key must be Into-convertible to String.
    ($object:ident ($($key:tt)+) : ($($value:tt)+)) => {
        $object.insert(($($key)+).into(), json!($($value)+));
    };

    // Misplaced colon. Trigger a reasonable error message by failing to match
    // the colon in the recursive call.
    ($object:ident () () : $($rest:tt)*) => {
        json_within_object!($object :);
    };

    // Found a comma inside a key. Trigger a reasonable error message by failing
    // to match the comma in the recursive call.
    ($object:ident ($($key:tt)*) () , $($rest:tt)*) => {
        json_within_object!($object ,);
    };

    // Found a colon after a key. Move on to the value.
    ($object:ident ($($key:tt)+) () : $($rest:tt)*) => {
        json_within_object!($object ($($key)+) : () $($rest)*);
    };

    // Misplaced comma. Trigger a reasonable error message by failing to match
    // the comma in the recursive call.
    ($object:ident ($($key:tt)+) : () , $($rest:tt)*) => {
        json_within_object!($object ,);
    };

    // Found a comma after a value. Insert whatever we have so far and move on
    // to remaining elements. Trailing comma is allowed.
    ($object:ident ($($key:tt)+) : ($($value:tt)+) , $($rest:tt)*) => {
        json_within_object!($object ($($key)+) : ($($value)+));
        json_within_object!($object () () $($rest)*);
    };

    // Munch a token into the current key.
    ($object:ident ($($key:tt)*) () $tt:tt $($rest:tt)*) => {
        json_within_object!($object ($($key)* $tt) () $($rest)*)
    };

    // Munch a token into the current value.
    ($object:ident ($($key:tt)+) : ($($value:tt)*) $tt:tt $($rest:tt)*) => {
        json_within_object!($object ($($key)+) : ($($value)* $tt) $($rest)*)
    };
}
<|endoftext|>


<commit_before>use hyper::Uri as HyperUri;
use std::path::Path;

/// A convenience type that can be used to construct Unix Domain Socket URIs
///
/// This type implements `Into<hyper::Uri>`.
///
/// # Example
/// ```
/// use hyperlocal::Uri;
/// use hyper::Uri as HyperUri;
///
/// let uri: HyperUri = Uri::new("/tmp/hyperlocal.sock", "/").into();
/// ```
#[derive(Debug)]
pub struct Uri {
    hyper_uri: HyperUri,
}

impl Uri {
    /// Create a new `[Uri]` from a socket address and a path
    pub fn new(socket: impl AsRef<Path>, path: &str) -> Self {
        let host = hex::encode(socket.as_ref().to_string_lossy().as_bytes());
        let host_str = format!("unix://{}:0{}", host, path);
        let hyper_uri: HyperUri = host_str.parse().unwrap();

        Self { hyper_uri }
    }
}

impl From<Uri> for HyperUri {
    fn from(uri: Uri) -> Self {
        uri.hyper_uri
    }
}

#[cfg(test)]
mod tests {
    use super::Uri;
    use hyper::Uri as HyperUri;

    #[test]
    fn test_unix_uri_into_hyper_uri() {
        let unix: HyperUri = Uri::new("foo.sock", "/").into();
        let expected: HyperUri = "unix://666f6f2e736f636b:0/".parse().unwrap();
        assert_eq!(unix, expected);
    }
}
<commit_msg>Make the wrapper type for Uri cloneable<commit_after>use hyper::Uri as HyperUri;
use std::path::Path;

/// A convenience type that can be used to construct Unix Domain Socket URIs
///
/// This type implements `Into<hyper::Uri>`.
///
/// # Example
/// ```
/// use hyperlocal::Uri;
/// use hyper::Uri as HyperUri;
///
/// let uri: HyperUri = Uri::new("/tmp/hyperlocal.sock", "/").into();
/// ```
#[derive(Debug, Clone)]
pub struct Uri {
    hyper_uri: HyperUri,
}

impl Uri {
    /// Create a new `[Uri]` from a socket address and a path
    pub fn new(socket: impl AsRef<Path>, path: &str) -> Self {
        let host = hex::encode(socket.as_ref().to_string_lossy().as_bytes());
        let host_str = format!("unix://{}:0{}", host, path);
        let hyper_uri: HyperUri = host_str.parse().unwrap();

        Self { hyper_uri }
    }
}

impl From<Uri> for HyperUri {
    fn from(uri: Uri) -> Self {
        uri.hyper_uri
    }
}

#[cfg(test)]
mod tests {
    use super::Uri;
    use hyper::Uri as HyperUri;

    #[test]
    fn test_unix_uri_into_hyper_uri() {
        let unix: HyperUri = Uri::new("foo.sock", "/").into();
        let expected: HyperUri = "unix://666f6f2e736f636b:0/".parse().unwrap();
        assert_eq!(unix, expected);
    }
}
<|endoftext|>


<commit_before>// High-level bindings to Azure.

import bindgen::{AzCreateColorPattern, AzCreateDrawTargetForCairoSurface};
import AzDrawSurfaceOptions;
import bindgen::AzDrawTargetClearRect;
import bindgen::AzDrawTargetCreateSourceSurfaceFromData;
import bindgen::{AzDrawTargetDrawSurface, AzDrawTargetFillRect, AzDrawTargetFlush};
import bindgen::{AzDrawTargetStrokeRect};
import AzFilter;
import bindgen::{AzReleaseColorPattern, AzReleaseDrawTarget};
import bindgen::AzReleaseSourceSurface;
import bindgen::AzRetainDrawTarget;
import AzSurfaceFormat;
import cairo_hl::ImageSurface;
import geom::rect::Rect;
import geom::size::Size2D;
import ptr::{addr_of, null};

trait AsAzureRect {
    fn as_azure_rect() -> AzRect;
}

impl Rect<AzFloat> : AsAzureRect {
    fn as_azure_rect() -> AzRect {
        {
            x: self.origin.x,
            y: self.origin.y,
            width: self.size.width,
            height: self.size.height
        }
    }
}

trait AsAzureIntSize {
    fn as_azure_int_size() -> AzIntSize;
}

impl Size2D<i32> : AsAzureIntSize {
    fn as_azure_int_size() -> AzIntSize {
        {
            width: self.width,
            height: self.height
        }
    }
}

class Color {
    let r: AzFloat;
    let g: AzFloat;
    let b: AzFloat;
    let a: AzFloat;

    new(r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloat) {
        self.r = r;
        self.g = g;
        self.b = b;
        self.a = a;
    }

    fn as_azure_color() -> AzColor {
        { r: self.r, g: self.g, b: self.b, a: self.a }
    }
}

// FIXME: Should have a class hierarchy here starting with Pattern.
class ColorPattern {
    let azure_color_pattern: AzColorPatternRef;

    new(+color: Color) {
        self.azure_color_pattern = AzCreateColorPattern(addr_of(color.as_azure_color()));
    }

    drop {
        AzReleaseColorPattern(self.azure_color_pattern);
    }
}

class StrokeOptions {
    let line_width: AzFloat;
    let miter_limit: AzFloat;
    let fields: uint16_t;

    new(line_width: AzFloat, miter_limit: AzFloat, fields: uint16_t) {
        self.line_width = line_width;
        self.miter_limit = miter_limit;
        self.fields = fields;
    }

    fn as_azure_stroke_options() -> AzStrokeOptions {
        {
            mLineWidth: self.line_width,
            mMiterLimit: self.miter_limit,
            mDashPattern: null(),
            mDashLength: 0,
            mDashOffset: 0.0f as AzFloat,
            fields: 0
        }
    }
}

class DrawOptions {
    let alpha: AzFloat;
    let fields: uint16_t;

    new(alpha: AzFloat, fields: uint16_t) {
        self.alpha = alpha;
        self.fields = fields;
    }

    fn as_azure_draw_options() -> AzDrawOptions {
        {
            mAlpha: self.alpha,
            fields: self.fields
        }
    }
}

enum SurfaceFormat {
    B8G8R8A8,
    R8G8R8X8,
    R5G6B5,
    A8
}

impl SurfaceFormat {
    fn as_azure_surface_format() -> AzSurfaceFormat {
        self as AzSurfaceFormat
    }
}

enum Filter {
    Linear,
    Point
}

impl Filter {
    fn as_azure_filter() -> AzFilter {
        self as AzFilter
    }
}

struct DrawSurfaceOptions {
    filter: Filter;
    sampling_bounds: bool;

    new(filter: Filter, sampling_bounds: bool) {
        self.filter = filter;
        self.sampling_bounds = sampling_bounds;
    }

    fn as_azure_draw_surface_options() -> AzDrawSurfaceOptions {
        { fields: ((self.filter as int) | (if self.sampling_bounds { 8 } else { 0 })) as u32 }
    }
}

class DrawTarget {
    let azure_draw_target: AzDrawTargetRef;

    new(&&cairo_surface: ImageSurface) {
        self.azure_draw_target = AzCreateDrawTargetForCairoSurface(cairo_surface.cairo_surface);
    }

    drop {
        AzReleaseDrawTarget(self.azure_draw_target);
    }

    fn flush() {
        AzDrawTargetFlush(self.azure_draw_target);
    }

    fn clear_rect(&&rect: Rect<AzFloat>) {
        AzDrawTargetClearRect(self.azure_draw_target, addr_of(rect.as_azure_rect()));
    }

    fn fill_rect(&&rect: Rect<AzFloat>, &&pattern: ColorPattern) {
        AzDrawTargetFillRect(self.azure_draw_target,
                             addr_of(rect.as_azure_rect()),
                             pattern.azure_color_pattern);
    }

    fn stroke_rect(&&rect: Rect<AzFloat>, &&pattern: ColorPattern, &&stroke_options: StrokeOptions,
                   &&draw_options: DrawOptions) {
        AzDrawTargetStrokeRect(self.azure_draw_target,
                               addr_of(rect.as_azure_rect()),
                               pattern.azure_color_pattern,
                               addr_of(stroke_options.as_azure_stroke_options()),
                               addr_of(draw_options.as_azure_draw_options()));
    }

    fn draw_surface(surface: SourceSurface, dest: Rect<AzFloat>, source: Rect<AzFloat>,
                    surf_options: DrawSurfaceOptions, options: DrawOptions) {

        AzDrawTargetDrawSurface(self.azure_draw_target,
                                surface.azure_source_surface,
                                addr_of(dest.as_azure_rect()),
                                addr_of(source.as_azure_rect()),
                                addr_of(surf_options.as_azure_draw_surface_options()),
                                addr_of(options.as_azure_draw_options()));
    }

    fn create_source_surface_from_data(data: &[u8], size: Size2D<i32>, stride: i32,
                                       format: SurfaceFormat) -> SourceSurface {

        assert data.len() as i32 == stride * size.height;
        let azure_surface =
            AzDrawTargetCreateSourceSurfaceFromData(self.azure_draw_target,
                                                    addr_of(data[0]),
                                                    addr_of(size.as_azure_int_size()),
                                                    stride,
                                                    format.as_azure_surface_format());
        SourceSurface(azure_surface)
    }
}

fn new_draw_target(cairo_surface: &ImageSurface) -> DrawTarget {
    DrawTarget {
        azure_draw_target: AzCreateDrawTargetForCairoSurface(cairo_surface.cairo_surface)
    }
}

fn new_draw_target_from_azure_draw_target(azure_draw_target: AzDrawTargetRef) -> DrawTarget {
    AzRetainDrawTarget(azure_draw_target);
    DrawTarget {
        azure_draw_target: azure_draw_target
    }
}

struct SourceSurface {
    azure_source_surface: AzSourceSurfaceRef;

    new(azure_source_surface: AzSourceSurfaceRef) {
        self.azure_source_surface = azure_source_surface;
    }

    drop {
        AzReleaseSourceSurface(self.azure_source_surface);
    }
}

<commit_msg>Add some clone functions for DrawTargets<commit_after>// High-level bindings to Azure.

import bindgen::{AzCreateColorPattern, AzCreateDrawTargetForCairoSurface};
import AzDrawSurfaceOptions;
import bindgen::AzDrawTargetClearRect;
import bindgen::AzDrawTargetCreateSourceSurfaceFromData;
import bindgen::{AzDrawTargetDrawSurface, AzDrawTargetFillRect, AzDrawTargetFlush};
import bindgen::{AzDrawTargetStrokeRect};
import AzFilter;
import bindgen::{AzReleaseColorPattern, AzReleaseDrawTarget};
import bindgen::AzReleaseSourceSurface;
import bindgen::AzRetainDrawTarget;
import AzSurfaceFormat;
import cairo_hl::ImageSurface;
import geom::rect::Rect;
import geom::size::Size2D;
import ptr::{addr_of, null};

trait AsAzureRect {
    fn as_azure_rect() -> AzRect;
}

impl Rect<AzFloat> : AsAzureRect {
    fn as_azure_rect() -> AzRect {
        {
            x: self.origin.x,
            y: self.origin.y,
            width: self.size.width,
            height: self.size.height
        }
    }
}

trait AsAzureIntSize {
    fn as_azure_int_size() -> AzIntSize;
}

impl Size2D<i32> : AsAzureIntSize {
    fn as_azure_int_size() -> AzIntSize {
        {
            width: self.width,
            height: self.height
        }
    }
}

class Color {
    let r: AzFloat;
    let g: AzFloat;
    let b: AzFloat;
    let a: AzFloat;

    new(r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloat) {
        self.r = r;
        self.g = g;
        self.b = b;
        self.a = a;
    }

    fn as_azure_color() -> AzColor {
        { r: self.r, g: self.g, b: self.b, a: self.a }
    }
}

// FIXME: Should have a class hierarchy here starting with Pattern.
class ColorPattern {
    let azure_color_pattern: AzColorPatternRef;

    new(+color: Color) {
        self.azure_color_pattern = AzCreateColorPattern(addr_of(color.as_azure_color()));
    }

    drop {
        AzReleaseColorPattern(self.azure_color_pattern);
    }
}

class StrokeOptions {
    let line_width: AzFloat;
    let miter_limit: AzFloat;
    let fields: uint16_t;

    new(line_width: AzFloat, miter_limit: AzFloat, fields: uint16_t) {
        self.line_width = line_width;
        self.miter_limit = miter_limit;
        self.fields = fields;
    }

    fn as_azure_stroke_options() -> AzStrokeOptions {
        {
            mLineWidth: self.line_width,
            mMiterLimit: self.miter_limit,
            mDashPattern: null(),
            mDashLength: 0,
            mDashOffset: 0.0f as AzFloat,
            fields: 0
        }
    }
}

class DrawOptions {
    let alpha: AzFloat;
    let fields: uint16_t;

    new(alpha: AzFloat, fields: uint16_t) {
        self.alpha = alpha;
        self.fields = fields;
    }

    fn as_azure_draw_options() -> AzDrawOptions {
        {
            mAlpha: self.alpha,
            fields: self.fields
        }
    }
}

enum SurfaceFormat {
    B8G8R8A8,
    R8G8R8X8,
    R5G6B5,
    A8
}

impl SurfaceFormat {
    fn as_azure_surface_format() -> AzSurfaceFormat {
        self as AzSurfaceFormat
    }
}

enum Filter {
    Linear,
    Point
}

impl Filter {
    fn as_azure_filter() -> AzFilter {
        self as AzFilter
    }
}

struct DrawSurfaceOptions {
    filter: Filter;
    sampling_bounds: bool;

    new(filter: Filter, sampling_bounds: bool) {
        self.filter = filter;
        self.sampling_bounds = sampling_bounds;
    }

    fn as_azure_draw_surface_options() -> AzDrawSurfaceOptions {
        { fields: ((self.filter as int) | (if self.sampling_bounds { 8 } else { 0 })) as u32 }
    }
}

class DrawTarget {
    let azure_draw_target: AzDrawTargetRef;

    new(&&cairo_surface: ImageSurface) {
        self.azure_draw_target = AzCreateDrawTargetForCairoSurface(cairo_surface.cairo_surface);
    }

    drop {
        AzReleaseDrawTarget(self.azure_draw_target);
    }

    fn clone() -> DrawTarget {
        return new_draw_target_from_azure_draw_target(self.azure_draw_target);
    }

    fn flush() {
        AzDrawTargetFlush(self.azure_draw_target);
    }

    fn clear_rect(&&rect: Rect<AzFloat>) {
        AzDrawTargetClearRect(self.azure_draw_target, addr_of(rect.as_azure_rect()));
    }

    fn fill_rect(&&rect: Rect<AzFloat>, &&pattern: ColorPattern) {
        AzDrawTargetFillRect(self.azure_draw_target,
                             addr_of(rect.as_azure_rect()),
                             pattern.azure_color_pattern);
    }

    fn stroke_rect(&&rect: Rect<AzFloat>, &&pattern: ColorPattern, &&stroke_options: StrokeOptions,
                   &&draw_options: DrawOptions) {
        AzDrawTargetStrokeRect(self.azure_draw_target,
                               addr_of(rect.as_azure_rect()),
                               pattern.azure_color_pattern,
                               addr_of(stroke_options.as_azure_stroke_options()),
                               addr_of(draw_options.as_azure_draw_options()));
    }

    fn draw_surface(surface: SourceSurface, dest: Rect<AzFloat>, source: Rect<AzFloat>,
                    surf_options: DrawSurfaceOptions, options: DrawOptions) {

        AzDrawTargetDrawSurface(self.azure_draw_target,
                                surface.azure_source_surface,
                                addr_of(dest.as_azure_rect()),
                                addr_of(source.as_azure_rect()),
                                addr_of(surf_options.as_azure_draw_surface_options()),
                                addr_of(options.as_azure_draw_options()));
    }

    fn create_source_surface_from_data(data: &[u8], size: Size2D<i32>, stride: i32,
                                       format: SurfaceFormat) -> SourceSurface {

        assert data.len() as i32 == stride * size.height;
        let azure_surface =
            AzDrawTargetCreateSourceSurfaceFromData(self.azure_draw_target,
                                                    addr_of(data[0]),
                                                    addr_of(size.as_azure_int_size()),
                                                    stride,
                                                    format.as_azure_surface_format());
        SourceSurface(azure_surface)
    }
}

// Ugly workaround for the lack of explicit self.
fn clone_mutable_draw_target(draw_target: &mut DrawTarget) -> DrawTarget {
    return new_draw_target_from_azure_draw_target(draw_target.azure_draw_target);
}

fn new_draw_target(cairo_surface: &ImageSurface) -> DrawTarget {
    DrawTarget {
        azure_draw_target: AzCreateDrawTargetForCairoSurface(cairo_surface.cairo_surface)
    }
}

fn new_draw_target_from_azure_draw_target(azure_draw_target: AzDrawTargetRef) -> DrawTarget {
    AzRetainDrawTarget(azure_draw_target);
    DrawTarget {
        azure_draw_target: azure_draw_target
    }
}

struct SourceSurface {
    azure_source_surface: AzSourceSurfaceRef;

    new(azure_source_surface: AzSourceSurfaceRef) {
        self.azure_source_surface = azure_source_surface;
    }

    drop {
        AzReleaseSourceSurface(self.azure_source_surface);
    }
}

<|endoftext|>