<commit_before>//! Serialization for TimeSteward data.
//!
//! TimeSteward has a few special requirements for serialization:
//! * DataTimelineHandle objects get special consideration, to support DAGs and cyclic data structures.
//! * The serialization needs to not block other operations for more than O(1) time at a time.
//! * The serialization must be lossless and platform-independent. For this reason, we always use bincode in low-endian mode.

macro_rules! time_steward_serialization_impls_for_handle {
  (
    [$($bounds:tt)*]
    [$($concrete:tt)*]
    (&$self_hack: ident)
    Data located at (| $handle: ident | &mut $data: expr)
  ) => {

/*thread_local! {
  static SERIALIZATION_CONTEXT: RefCell<Option <SerializationContext>> = RefCell::new (None);
  static DESERIALIZATION_CONTEXT: RefCell<Option <DeserializationContext>> = RefCell::new (None);
}*/

impl <$($bounds)*> $crate::serde::Serialize for $($concrete)* {
  fn serialize <S: $crate::serde::Serializer> (&$self_hack, serializer: S)->Result <S::Ok, S::Error> {
    unimplemented!()
    /*
    SERIALIZATION_CONTEXT.with (| cell | {
      let mut guard = cell.borrow_mut();
      let mut map = &mut guard.unwrap().map;
      map.insert (
    })
    identifier.serialize (serializer)
    */
  }
}

impl <'a, $($bounds)*> $crate::serde::Deserialize <'a> for $($concrete)* {
  fn deserialize <D: $crate::serde::Deserializer<'a>> (deserializer: D)->Result <Self, D::Error> {
    unimplemented!()
    /*
    let old_identifier = Identifier::deserialize (deserializer)?;
    DESERIALIZATION_CONTEXT.with (| cell | {
      let mut guard = cell.borrow_mut();
      let mut map = &mut guard.unwrap().map;
      Ok(map.entry (old_pointer).or_insert_with (| | {
        unimplemented!()
        /*DataTimelineHandle {
          inner: Arc::new (unsafe {::std::mem::uninitialized()}),
        }*/
      }).clone().downcast::<T> ())
    })
    */
  }
}

/*
impl DeserializationContext {
  fn deserialize_(deserializer: D)->Result <(), D::Error> {
    let old_pointer = usize::deserialize (deserializer)?;
    DESERIALIZATION_CONTEXT.with (| cell | {
      let mut guard = cell.borrow_mut();
      let mut map = &mut guard.unwrap().map;
      let $handle = map.entry (old_pointer).or_insert_with (| | {
        unimplemented!()
        /*DataTimelineHandle {
          inner: Arc::new (unsafe {::std::mem::uninitialized()}),
        }*/
      });
      let new_pointer = &mut $data;
      unsafe {::std::ptr::write (
        new_pointer as *mut DataTimelineHandle,
        unimplemented!() //DataTimeline::deserialize (D)
      )?;}
    })?;
    Ok(())
  }
}*/

  };
}

macro_rules! time_steward_serialization_impls {
  () => {
  fn deserialize_something <R: Read> (reader: &mut R)->$crate::bincode::Result <()> {
    DESERIALIZATION_CONTEXT.with (| cell | {
      {
        let guard = cell.borrow_mut();
        assert!(guard.is_none(), "deserializing recursively breaks my hacks probably makes no sense");
        *guard = Some(DeserializationContext::new());
      }
      // deserialize inside a closure so that errors can be collected and we still clear the context afterwards
      let result = || {
        let time: ExtendedTime <B> = deserialize_from (reader, ::std::mem::size_of::<ExtendedTime <B>>())?;
        let global_timeline: DataTimelineHandle <B::GlobalTimeline> = deserialize_from (reader, $crate::bincode::Infinite)?;

        while !cell.borrow().uninitialized.is_empty() {
          let next: ????? = deserialize_from (reader, $crate::bincode::Infinite)?;
          match next {
            ?????::DataTimeline (type_id) => {
              let deserialize_function = cell.borrow().?????.get (type_id);
              (*deserialize_function)();
            }
            ?????::Event (type_id) => {
              let deserialize_function = cell.borrow().?????.get (type_id);
              (*deserialize_function)();
            }
          };
        }
      }();

      {
        let guard = cell.borrow_mut();
        *guard = None;
      }
      result
    })
  }
  };
}

<commit_msg>Worked on serialization<commit_after>//! Serialization for TimeSteward data.
//!
//! TimeSteward has a few special requirements for serialization:
//! * DataTimelineHandle objects get special consideration, to support DAGs and cyclic data structures.
//! * The serialization needs to not block other operations for more than O(1) time at a time.
//! * The serialization must be lossless and platform-independent. For this reason, we always use bincode in low-endian mode.

macro_rules! time_steward_serialization_impls_for_handle {
  (
    [$($bounds:tt)*]
    [$($concrete:tt)*]
    (&$self_hack: ident)
    Data located at (| $handle: ident | &mut $data: expr)
  ) => {

/*thread_local! {
  static SERIALIZATION_CONTEXT: RefCell<Option <SerializationContext>> = RefCell::new (None);
  static DESERIALIZATION_CONTEXT: RefCell<Option <DeserializationContext>> = RefCell::new (None);
}*/

impl <$($bounds)*> $crate::serde::Serialize for $($concrete)* {
  fn serialize <S: $crate::serde::Serializer> (&$self_hack, serializer: S)->Result <S::Ok, S::Error> {
    unimplemented!()
    /*
    SERIALIZATION_CONTEXT.with (| cell | {
      let mut guard = cell.borrow_mut();
      let mut map = &mut guard.unwrap().map;
      map.insert (
    })
    identifier.serialize (serializer)
    */
  }
}

impl <'a, $($bounds)*> $crate::serde::Deserialize <'a> for $($concrete)* {
  fn deserialize <D: $crate::serde::Deserializer<'a>> (deserializer: D)->Result <Self, D::Error> {
    unimplemented!()
    /*
    let old_identifier = Identifier::deserialize (deserializer)?;
    DESERIALIZATION_CONTEXT.with (| cell | {
      let mut guard = cell.borrow_mut();
      let mut map = &mut guard.unwrap().map;
      Ok(map.entry (old_pointer).or_insert_with (| | {
        unimplemented!()
        /*DataTimelineHandle {
          inner: Arc::new (unsafe {::std::mem::uninitialized()}),
        }*/
      }).clone().downcast::<T> ())
    })
    */
  }
}

/*
impl DeserializationContext {
  fn deserialize_(deserializer: D)->Result <(), D::Error> {
    let old_pointer = usize::deserialize (deserializer)?;
    DESERIALIZATION_CONTEXT.with (| cell | {
      let mut guard = cell.borrow_mut();
      let mut map = &mut guard.unwrap().map;
      let $handle = map.entry (old_pointer).or_insert_with (| | {
        unimplemented!()
        /*DataTimelineHandle {
          inner: Arc::new (unsafe {::std::mem::uninitialized()}),
        }*/
      });
      let new_pointer = &mut $data;
      unsafe {::std::ptr::write (
        new_pointer as *mut DataTimelineHandle,
        unimplemented!() //DataTimeline::deserialize (D)
      )?;}
    })?;
    Ok(())
  }
}*/

  };
}

#[doc (hidden)]
#[macro_export]
macro_rules! time_steward_serialization_impls {
  () => {

  enum SerializationElement {
    DataHandleData(u64, PersistentTypeId),
    EventHandleData(u64, PersistentTypeId),
    Finished,
  }

  trait SerializeTargetInto {
    fn serialize_target_into(&self, writer: &mut Write, object_id: u64)->$crate::bincode::Result <()>;
  }
  trait SerializeInto {
    fn serialize_into(&self, writer: &mut Write)->$crate::bincode::Result <()>;
  }
  impl<T: StewardData> SerializeTargetInto for DataHandle <T> {
    fn serialize_into(&self, writer: &mut Write, object_id: u64)->$crate::bincode::Result <()> {
      $crate::bincode::serialize_into (writer, SerializationElement::DataHandleData (T::ID), $crate::bincode::Infinite)?;
      $crate::bincode::serialize_into (writer, &*self.data, $crate::bincode::Infinite)?;
    }
  }
  fn data_handle_initialize_function <T: StewardData>(writer: &mut Write) {

  }

  impl<B: Basics> SerializeTargetInto for EventHandle <B> {
    fn serialize_into(&self, writer: &mut Write, object_id: u64)->$crate::bincode::Result <()> {
      $crate::bincode::serialize_into (writer, SerializationElement::DataHandleData (self.data.data.persistent_type_id()), $crate::bincode::Infinite)?;
      $crate::bincode::serialize_into (writer, self.extended_time(), $crate::bincode::Infinite)?;
      self.data.data.serialize_into (writer)
    }
  }
  impl<T: EventInnerTrait> SerializeInto for T {
    fn serialize_into(&self, writer: &mut Write)->$crate::bincode::Result <()> {
      $crate::bincode::serialize_into (writer, self, $crate::bincode::Infinite)?;
    }
  }

  struct SerializationContext {
    time: Box<Any>,
    data_handle_targets_observed: HashMap <*const (), u64>
    data_handles_to_serialize_target: Vec<(u64, Box <SerializeTargetInto>)>;
    event_handle_targets_observed: HashMap <*const (), u64>
    event_handles_to_serialize_target: Vec<(u64, Box <SerializeTargetInto>)>;
    next_object_identifier: u64,
  }
  struct DeserializationContext {
    data_handle_initialize_functions: ::std::collections::HashMap <
      PersistentTypeId, fn (&mut Write)>,
    event_handle_initialize_functions: ::std::collections::HashMap <
      PersistentTypeId, fn (&mut Write)>,
    data_handles: ::std::collections::HashMap <u64, Box <Any>>,
    uninitialized_data_handles: ::std::collections::HashSet <u64>,
  }

  thread_local! {
    static SERIALIZATION_CONTEXT: RefCell<Option <SerializationContext>> = RefCell::new (None);
    static DESERIALIZATION_CONTEXT: RefCell<Option <DeserializationContext>> = RefCell::new (None);
  }

  impl <T: StewardData> $crate::serde::Serialize for DataHandle <T> {
    fn serialize <S: $crate::serde::Serializer> (&self, serializer: S)->Result <S::Ok, S::Error> {
      SERIALIZATION_CONTEXT.with (| cell | {
        let mut guard = cell.borrow_mut();
        let mut context = match guard.as_mut() {Some(x)=>x, None=>return S::Error::Custom("You can't serialize a DataHandle without a serialization context.")};

        let object_identifier = context.data_handle_targets_observed.entry (self.data as *const ()).or_insert_with (|| {
          let result = context.next_object_identifier;
          context.next_object_identifier += 1;
          context.data_handles_to_serialize_target.insert (object_identifier, Box::new (self.clone()));
          result
        });
        object_identifier.serialize (serializer)
      })
    }
  }
  impl <'a, T: StewardData> $crate::serde::Deserialize <'a> for DataHandle <T> {
    fn deserialize <D: $crate::serde::Deserializer<'a>> (deserializer: D)->Result <Self, D::Error> {
      let object_identifier = u64::deserialize (deserializer)?;
      DESERIALIZATION_CONTEXT.with (| cell | {
        let mut guard = cell.borrow_mut();
        let mut context = match guard.as_mut() {Some(x)=>x, None=>return D::Error::Custom("You can't deserialize a DataHandle without a deserialization context.")};
        let entry = context.data_handles.entry (object_identifier).or_insert_with (|| {
          let created = DataHandle::new(unsafe {::std::mem::uninitialized()});
          context.uninitialized_data_handles.insert (Box::new (created.clone()));
          Box::new (created)
        });
        match entry.downcast_ref::<Box<DataHandle<T>>() {
          Some (result) => Ok((**result).clone()),
          None => D::Error::Custom("In the serialized snapshot, DataHandles of different types pointed to the same object."),
        }
      })
    }
  }

  impl <B: Basics> $crate::serde::Serialize for EventHandle <B> {
          //let type_id = T::ID;
      //type_id.serialize (serializer)
  }
  impl <'a, B: Basics> $crate::serde::Deserialize <'a> for EventHandle <B> {

  }

  impl <T: DataTimeline> $crate::serde::Serialize for DataTimelineCell <T> {
    fn serialize <S: $crate::serde::Serializer> (&self, serializer: S)->Result <S::Ok, S::Error> {
      SERIALIZATION_CONTEXT.with (| cell | {
        let mut guard = cell.borrow_mut();
        let mut context = match guard.as_mut() {Some(x)=>x, None=>return S::Error::Custom("You can't serialize a DataTimelineCell without a serialization context.")};

        self.data().clone_for_snapshot(&**context.time.downcast_ref::<Box<ExtendedTime <T::Basics >>()).serialize (serializer)
      })
    }
  }
  impl <'a, T: DataTimeline> $crate::serde::Deserialize <'a> for DataTimelineCell <T> {
    fn deserialize <D: $crate::serde::Deserializer<'a>> (deserializer: D)->Result <Self, D::Error> {
      Self::new (T::deserialize (deserializer))
    }
  }

  fn serialize_something <W: Write> (writer: &mut W)->$crate::bincode::Result <()> {
    SERIALIZATION_CONTEXT.with (| cell | {
      {
        let guard = cell.borrow_mut();
        assert!(guard.is_none(), "serializing recursively breaks my hacks and probably makes no sense");
        *guard = Some(SerializationContext::new());
      }
      // serialize inside a closure so that errors can be collected and we still clear the context afterwards
      let result = || {
        $crate::bincode::serialize_into (writer, time, ::std::mem::size_of::<ExtendedTime <B>>())?;
        $crate::bincode::serialize_into (writer, globals, $crate::bincode::Infinite)?;

        loop {
          if let (object_identifier, handle_box) = cell.borrow().data_handles_to_serialize_target.pop() {
            handle_box.serialize_into (writer);
          }
          if let (object_identifier, event_handle) = cell.borrow().event_handles_to_serialize_target.pop() {
            event_handle.serialize_into (writer);
          }
        }

        $crate::bincode::serialize_into (writer, SerializationElement::Finished, $crate::bincode::Infinite)?;

      }();

      {
        let guard = cell.borrow_mut();
        *guard = None;
      }
      result
    })
  }

  fn deserialize_something <R: Read> (reader: &mut R)->$crate::bincode::Result <()> {
    DESERIALIZATION_CONTEXT.with (| cell | {
      {
        let guard = cell.borrow_mut();
        assert!(guard.is_none(), "deserializing recursively breaks my hacks and probably makes no sense");
        *guard = Some(DeserializationContext::new());
      }
      // deserialize inside a closure so that errors can be collected and we still clear the context afterwards
      let result = || {
        let time: ExtendedTime <B> = deserialize_from (reader, ::std::mem::size_of::<ExtendedTime <B>>())?;
        let globals: B::Globals = deserialize_from (reader, $crate::bincode::Infinite)?;

        while !cell.borrow().uninitialized_handles.is_empty() {
          // TODO: use actual size limits
          let next: SerializationElement = $crate::bincode::deserialize_from (reader, $crate::bincode::Infinite)?;
          match next {
            SerializationElement::DataTimeline (object_id, type_id) => {
              let deserialize_function = cell.borrow().?????.get (type_id);

              (*deserialize_function)(reader);
            }
            SerializationElement::Event (object_id, type_id) => {
              let deserialize_function = cell.borrow().?????.get (type_id);
              (*deserialize_function)(reader);
            }
            SerializationElement::Finished => {
              // TODO: clean up broken state
              return $crate::bincode::Result::Custom("Premature end of serialized snapshot")
            }
          };
        }

        let next: SerializationElement = $crate::bincode::deserialize_from (reader, $crate::bincode::Infinite)?;
        match next {
          SerializationElement::Finished => (),
          _ => {
            return $crate::bincode::Result::Custom("Serialized snapshot included additional elements after successfully deserializing the state")
          }
        };

        Ok(Steward::from_globals (globals, ValidSince::Before (time)))
      }();

      {
        let guard = cell.borrow_mut();
        *guard = None;
      }
      result
    })
  }

  };
}

<|endoftext|>


<commit_before>use std::collections::HashMap;

pub trait StaticSymbolTable<'a>
{
	/// Return all symbols in this table with the specified name (in any namespace)
	fn lookup_by_name(&self, name: &str) -> Vec<Symbol<'a>>;

	/// Return all symbols in this table with the specified namespace
	fn lookup_by_namespace(&self, namespace: &str) -> Vec<Symbol<'a>>;

	/// Lookup a variable by its name and namespace. Duplicate symbols are not allowed, so the result will be unique
	/// @return the specified symbol or None if the specified symbol is not in this namespace
	fn lookup_variable(&self, namespace: &str, name: &str) -> Option<Symbol<'a>>;

	/// Lookup a function by its name and namespace. Functions with the same signature are not allowed, so the result will be unique
	/// If no result is found in the direct namespace, the parent namespaces will be searched
	/// @return the specified symbol or None if the specified symbol is not in this namespace or a parent namespace
	fn lookup_function(&self, namespace: &str, name: &str, argument_types: &Vec<&str>) -> Option<Symbol<'a>>;

	/// Lookup a structure (class, enum) by its name and namespace.
	/// Duplicate classes in the same namespace are not allowed, so the result will be unique
	/// If no result is found in the direct namespace, the parent namespaces will be searched
	/// @return the specified symbol or None if the specified symbol is not in this namespace or a parent namespace
	fn lookup_structure(&self, namespace: &str, name: &str) -> Option<(Symbol<'a>)>;

	/// Adds a symbol to this table and allocates it's location
	/// Returns true if the symbol could be added; false otherwise
	/// Duplicate symbols are not allowed
	/// TODO: support overloaded methods
	fn add(&self, class: SymbolClass<'a>, namespace: &'a str, name: &'a str) -> bool;
}

pub enum SymbolLocation<'a>
{
	/// Indicates that a register has been reserved for a specific use (e.g. by a variable)
	/// tuple: (name)
	Register(&'a str),

	/// Indicates a location in memory (e.g. for static variables)
	/// tuple: (address)
	Memory(MemoryAddress<'a>),

	/// Indicates an offset location from a structured entity (e.g. a member variable of a class)
	/// tuple: offset
	InstancedMemory(u16),

	/// Indicates that the symbol should not be accessed, as it represents a structured entity
	Structured
}

pub enum SymbolClass<'a>
{
	Variable { variable_type: &'a str },

	/// Function signature //TODO: support exceptions
	Function { return_type: &'a str, argument_types: &'a Vec<&'a str> },

	/// Includes class, enum, and interface
	Structure { subtype: &'a str },
}

pub struct Symbol<'a>
{
	/// Namespace of this symbol, without the final "." or the name of this symbol
	pub namespace: &'a str,

	/// Identifier for the symbol (e.g. name of variable, function, class, etc. without it's namespace)
	pub name: &'a str,

	/// What this symbol represents (class, enum, variable, function, etc)
	pub symbol_class: SymbolClass<'a>,

	/// Memory location of this symbol. Methods will always map to a SymbolLocation::Memory label with a 0 offset
	pub location: SymbolLocation<'a>,
}

pub struct MemoryAddress<'a>
{
	/// Label marking the base address where the symbol is stored
	pub label_name: &'a str,

	/// Offset from the base address to access the symbol. Methods will always have an offset of 0
	pub offset: u16,
}
<commit_msg>Make SymbolTable public<commit_after>pub mod symbol_table;
use std::collections::HashMap;

pub trait StaticSymbolTable<'a>
{
	/// Return all symbols in this table with the specified name (in any namespace)
	fn lookup_by_name(&self, name: &str) -> Vec<Symbol<'a>>;

	/// Return all symbols in this table with the specified namespace
	fn lookup_by_namespace(&self, namespace: &str) -> Vec<Symbol<'a>>;

	/// Lookup a variable by its name and namespace. Duplicate symbols are not allowed, so the result will be unique
	/// @return the specified symbol or None if the specified symbol is not in this namespace
	fn lookup_variable(&self, namespace: &str, name: &str) -> Option<Symbol<'a>>;

	/// Lookup a function by its name and namespace. Functions with the same signature are not allowed, so the result will be unique
	/// If no result is found in the direct namespace, the parent namespaces will be searched
	/// @return the specified symbol or None if the specified symbol is not in this namespace or a parent namespace
	fn lookup_function(&self, namespace: &str, name: &str, argument_types: &Vec<&str>) -> Option<Symbol<'a>>;

	/// Lookup a structure (class, enum) by its name and namespace.
	/// Duplicate classes in the same namespace are not allowed, so the result will be unique
	/// If no result is found in the direct namespace, the parent namespaces will be searched
	/// @return the specified symbol or None if the specified symbol is not in this namespace or a parent namespace
	fn lookup_structure(&self, namespace: &str, name: &str) -> Option<(Symbol<'a>)>;

	/// Adds a symbol to this table and allocates it's location
	/// Returns true if the symbol could be added; false otherwise
	/// Duplicate symbols are not allowed
	/// TODO: support overloaded methods
	fn add(&self, class: SymbolClass<'a>, namespace: &'a str, name: &'a str) -> bool;
}

pub enum SymbolLocation<'a>
{
	/// Indicates that a register has been reserved for a specific use (e.g. by a variable)
	/// tuple: (name)
	Register(&'a str),

	/// Indicates a location in memory (e.g. for static variables)
	/// tuple: (address)
	Memory(MemoryAddress<'a>),

	/// Indicates an offset location from a structured entity (e.g. a member variable of a class)
	/// tuple: offset
	InstancedMemory(u16),

	/// Indicates that the symbol should not be accessed, as it represents a structured entity
	Structured
}

pub enum SymbolClass<'a>
{
	Variable { variable_type: &'a str },

	/// Function signature //TODO: support exceptions
	Function { return_type: &'a str, argument_types: &'a Vec<&'a str> },

	/// Includes class, enum, and interface
	Structure { subtype: &'a str },
}

pub struct Symbol<'a>
{
	/// Namespace of this symbol, without the final "." or the name of this symbol
	pub namespace: &'a str,

	/// Identifier for the symbol (e.g. name of variable, function, class, etc. without it's namespace)
	pub name: &'a str,

	/// What this symbol represents (class, enum, variable, function, etc)
	pub symbol_class: SymbolClass<'a>,

	/// Memory location of this symbol. Methods will always map to a SymbolLocation::Memory label with a 0 offset
	pub location: SymbolLocation<'a>,
}

pub struct MemoryAddress<'a>
{
	/// Label marking the base address where the symbol is stored
	pub label_name: &'a str,

	/// Offset from the base address to access the symbol. Methods will always have an offset of 0
	pub offset: u16,
}
<|endoftext|>


<commit_before>use std::marker::PhantomData;
use std::collections::{HashMap, HashSet};
use context::Context;
use framebuffer::FramebufferBinding;
use program::ProgramAttrib;
use vertex_data::{VertexData, VertexBytes, VertexAttribute};
use index_data::{IndexData, IndexDatum};
use buffer::{Buffer, BufferBinding,
             ArrayBufferBinding, ElementArrayBufferBinding};
use types::DrawingMode;

#[derive(Debug)]
pub enum AttribAddError {
    DuplicateAttrib(String)
}

#[derive(Debug)]
pub struct AttribError {
    missing_attribs: Vec<String>,
    unknown_attribs: Vec<String>
}

pub struct AttribBinder {
    attribs: HashMap<String, ProgramAttrib>
}

impl AttribBinder {
    pub fn new() -> Self {
        AttribBinder {
            attribs: HashMap::new()
        }
    }

    pub fn add(&mut self, name: &str, attrib: ProgramAttrib)
        -> Result<(), AttribAddError>
    {
        match self.attribs.insert(name.into(), attrib) {
            None => Ok(()),
            Some(_) => Err(AttribAddError::DuplicateAttrib(name.into()))
        }
    }

    fn for_each<T, F>(&self, mut f: F) -> Result<(), AttribError>
        where T: VertexData, F: FnMut(VertexAttribute, ProgramAttrib)
    {
        // TODO: Avoid heap allocations
        // TODO: Avoid redundant calls to T::visit_attributes
        let mut attribs =
            HashMap::<String, (VertexAttribute, ProgramAttrib)>::new();
        let mut missing = Vec::<String>::new();

        T::visit_attributes(|vertex_attrib| {
            match self.attribs.get(&vertex_attrib.name) {
                Some(program_attrib) => {
                    let pair = (vertex_attrib.clone(), *program_attrib);
                    attribs.insert(vertex_attrib.name, pair);
                },
                None => {
                    missing.push(vertex_attrib.name);
                }
            }
        });

        let unknown: Vec<_> = {
            let expected: HashSet<_> = self.attribs.keys().collect();
            let actual: HashSet<_> = attribs.keys().collect();
            expected.difference(&actual).cloned().cloned().collect()
        };

        if missing.is_empty() && unknown.is_empty() {
            for (_, (vertex_attrib, program_attrib)) in attribs.into_iter() {
                f(vertex_attrib, program_attrib);
            }
            Ok(())
        }
        else {
            Err(AttribError {
                missing_attribs: missing,
                unknown_attribs: unknown
            })
        }
    }

    pub fn enable<T: VertexData>(&self, gl: &Context)
        -> Result<(), AttribError>
    {
        self.for_each::<T, _>(|_, program_attrib| {
            gl.enable_vertex_attrib_array(program_attrib)
        })
    }

    pub fn bind<T: VertexData>(&self, gl_buffer: &ArrayBufferBinding)
        -> Result<(), AttribError>
    {
        self.for_each::<T, _>(|vertex_attrib, program_attrib| {
            unsafe {
                gl_buffer.vertex_attrib_pointer(
                    program_attrib,
                    vertex_attrib.ty.components,
                    vertex_attrib.ty.data,
                    vertex_attrib.ty.normalize,
                    vertex_attrib.stride,
                    vertex_attrib.offset
                );
            }
        })
    }
}

#[derive(Debug)]
pub enum VertexBindError {
    BindingError(AttribError),
    NoAttributeBindings
}

impl From<AttribError> for VertexBindError {
    fn from(attrib_error: AttribError) -> VertexBindError {
        VertexBindError::BindingError(attrib_error)
    }
}

pub struct VertexBuffer<T: VertexData> {
    attrib_binder: Option<AttribBinder>,
    buffer: Buffer,
    count: usize,
    phantom: PhantomData<*const T>
}

impl<T: VertexData> VertexBuffer<T> {
    pub fn bind_attrib_pointers(&mut self, binder: AttribBinder) {
        self.attrib_binder = Some(binder);
    }

    pub fn bind(&self, gl_buffer: &ArrayBufferBinding)
        -> Result<(), VertexBindError>
    {
        match self.attrib_binder {
            Some(ref binder) => {
                let mut gl = unsafe { Context::current_context() };
                try!(binder.enable::<T>(&mut gl));
                try!(binder.bind::<T>(gl_buffer));
                Ok(())
            },
            None => { Err(VertexBindError::NoAttributeBindings) }
        }
    }

    pub fn buffer(&self) -> &Buffer {
        &self.buffer
    }

    pub fn buffer_mut(&mut self) -> &mut Buffer {
        &mut self.buffer
    }
}

pub struct VertexBufferBinding<'a, T: VertexData + 'a> {
    gl_buffer: ArrayBufferBinding<'a>,
    vbo: &'a mut VertexBuffer<T>
}

impl<'a, T: VertexData + 'a> VertexBufferBinding<'a, T> {
    pub fn new(gl_buffer: ArrayBufferBinding<'a>, vbo: &'a mut VertexBuffer<T>)
        -> Self
    {
        VertexBufferBinding {
            gl_buffer: gl_buffer,
            vbo: vbo
        }
    }

    pub fn buffer_data(&mut self, data: &[T], usage: super::BufferDataUsage)
        where [T]: VertexBytes
    {
        self.vbo.count = data.len();
        self.gl_buffer.buffer_bytes(data.vertex_bytes(), usage);
    }
}

impl<'a> FramebufferBinding<'a> {
    pub fn draw_arrays_range_vbo<T>(&mut self,
                                    gl_vbo: &VertexBufferBinding<T>,
                                    mode: DrawingMode,
                                    start: u32,
                                    length: usize)
        where T: VertexData
    {
        debug_assert!((start as usize) + length <= gl_vbo.vbo.count);

        unsafe {
            self.draw_arrays_range(&gl_vbo.gl_buffer, mode, start, length);
        }
    }

    pub fn draw_arrays_vbo<T>(&mut self,
                              gl_vbo: &VertexBufferBinding<T>,
                              mode: DrawingMode)
        where T: VertexData
    {
        unsafe {
            self.draw_arrays_range(&gl_vbo.gl_buffer,
                                   mode,
                                   0,
                                   gl_vbo.vbo.count);
        }
    }

    pub fn draw_n_elements_buffered_vbo<T, I>(&mut self,
                                              gl_vbo: &VertexBufferBinding<T>,
                                              gl_ibo: &IndexBufferBinding<I>,
                                              mode: DrawingMode,
                                              length: usize)
        where T: VertexData, I: IndexDatum
    {
        debug_assert!(length <= gl_ibo.ibo.count);

        unsafe {
            self.draw_n_elements_buffered(&gl_vbo.gl_buffer,
                                          &gl_ibo.gl_buffer,
                                          mode,
                                          length,
                                          I::index_datum_type());
        }
    }

    pub fn draw_elements_buffered_vbo<T, I>(&mut self,
                                            gl_vbo: &VertexBufferBinding<T>,
                                            gl_ibo: &IndexBufferBinding<I>,
                                            mode: DrawingMode)
        where T: VertexData, I: IndexDatum
    {
        unsafe {
            self.draw_n_elements_buffered(&gl_vbo.gl_buffer,
                                          &gl_ibo.gl_buffer,
                                          mode,
                                          gl_ibo.ibo.count,
                                          I::index_datum_type());
        }
    }

    pub fn draw_n_elements_vbo<T, I>(&mut self,
                                     gl_vbo: &VertexBufferBinding<'a, T>,
                                     mode: DrawingMode,
                                     count: usize,
                                     indices: &[I])
        where T: VertexData, I: IndexDatum, [I]: IndexData
    {
        unsafe {
            self.draw_n_elements(&gl_vbo.gl_buffer, mode, count, indices);
        }
    }

    pub fn draw_elements_vbo<T, I>(&mut self,
                                   gl_vbo: &VertexBufferBinding<'a, T>,
                                   mode: DrawingMode,
                                   indices: &[I])
        where T: VertexData, I: IndexDatum, [I]: IndexData
    {
        unsafe {
            self.draw_elements(&gl_vbo.gl_buffer, mode, indices);
        }
    }
}

impl Context {
    pub fn new_vertex_buffer<T: VertexData>(&self) -> VertexBuffer<T> {
        VertexBuffer {
            attrib_binder: None,
            buffer: self.gen_buffer(),
            count: 0,
            phantom: PhantomData
        }
    }
}

pub struct IndexBuffer<T: IndexDatum> {
    buffer: Buffer,
    count: usize,
    phantom: PhantomData<*const T>
}

impl<T: IndexDatum> IndexBuffer<T> {
    pub fn buffer(&self) -> &Buffer {
        &self.buffer
    }

    pub fn buffer_mut(&mut self) -> &mut Buffer {
        &mut self.buffer
    }
}

pub struct IndexBufferBinding<'a, T: IndexDatum + 'a> {
    gl_buffer: ElementArrayBufferBinding<'a>,
    ibo: &'a mut IndexBuffer<T>
}

impl<'a, T: IndexDatum + 'a> IndexBufferBinding<'a, T> {
    pub fn new(gl_buffer: ElementArrayBufferBinding<'a>,
               ibo: &'a mut IndexBuffer<T>)
        -> Self
    {
        IndexBufferBinding {
            gl_buffer: gl_buffer,
            ibo: ibo
        }
    }

    pub fn buffer_data(&mut self, data: &[T], usage: super::BufferDataUsage)
        where [T]: IndexData
    {
        self.ibo.count = data.len();
        self.gl_buffer.buffer_bytes(data.index_bytes(), usage);
    }
}

impl Context {
    pub fn new_index_buffer<T: IndexDatum>(&self) -> IndexBuffer<T> {
        IndexBuffer {
            buffer: self.gen_buffer(),
            count: 0,
            phantom: PhantomData
        }
    }
}

#[macro_export]
macro_rules! attrib_pointers {
    ($gl:expr, $vbo:expr, {
        $($field_name:ident => $field_attrib:expr),*
    }) => {
        {
            let mut binder = $crate::AttribBinder::new();
            $(binder.add(stringify!($field_name), $field_attrib).unwrap());*;
            binder
        }
    }
}

#[macro_export]
macro_rules! bind_attrib_pointers {
    ($gl:expr, $vbo:expr, {
        $($field_name:ident => $field_attrib:expr),*
    }) => {
        {
            let vbo = $vbo;
            let binder = {
                attrib_pointers!($gl, vbo, {
                    $($field_name => $field_attrib),*
                })
            };
            vbo.bind_attrib_pointers(binder);
        }
    }
}

#[macro_export]
macro_rules! bind_vertex_buffer {
    ($gl:expr, $vbo:expr) => {
        {
            let vbo = $vbo;

            let gl_buffer = bind_array_buffer!($gl, vbo.buffer_mut());
            vbo.bind(&gl_buffer).unwrap();
            $crate::VertexBufferBinding::new(gl_buffer, vbo)
        }
    }
}

#[macro_export]
macro_rules! bind_index_buffer {
    ($gl:expr, $ibo:expr) => {
        {
            let ibo = $ibo;

            let gl_buffer = bind_element_array_buffer!($gl, ibo.buffer_mut());
            $crate::IndexBufferBinding::new(gl_buffer, ibo)
        }
    }
}
<commit_msg>Refactor `VertexBuffer` and friends<commit_after>use std::borrow::BorrowMut;
use std::marker::PhantomData;
use std::collections::{HashMap, HashSet};
use context::ContextOf;
use framebuffer::FramebufferBinding;
use program::ProgramAttrib;
use vertex_data::{VertexData, VertexBytes, VertexAttribute};
use index_data::{IndexData, IndexDatum};
use buffer::{Buffer, BufferBinding,
             ArrayBufferBinder, ElementArrayBufferBinder,
             ArrayBufferBinding, ElementArrayBufferBinding};
use types::DrawingMode;

#[derive(Debug)]
pub enum AttribAddError {
    DuplicateAttrib(String)
}

#[derive(Debug)]
pub struct AttribError {
    missing_attribs: Vec<String>,
    unknown_attribs: Vec<String>
}

pub struct AttribBinder {
    attribs: HashMap<String, ProgramAttrib>
}

impl AttribBinder {
    pub fn new() -> Self {
        AttribBinder {
            attribs: HashMap::new()
        }
    }

    pub fn add(&mut self, name: &str, attrib: ProgramAttrib)
        -> Result<(), AttribAddError>
    {
        match self.attribs.insert(name.into(), attrib) {
            None => Ok(()),
            Some(_) => Err(AttribAddError::DuplicateAttrib(name.into()))
        }
    }

    fn for_each<T, F>(&self, mut f: F) -> Result<(), AttribError>
        where T: VertexData, F: FnMut(VertexAttribute, ProgramAttrib)
    {
        // TODO: Avoid heap allocations
        // TODO: Avoid redundant calls to T::visit_attributes
        let mut attribs =
            HashMap::<String, (VertexAttribute, ProgramAttrib)>::new();
        let mut missing = Vec::<String>::new();

        T::visit_attributes(|vertex_attrib| {
            match self.attribs.get(&vertex_attrib.name) {
                Some(program_attrib) => {
                    let pair = (vertex_attrib.clone(), *program_attrib);
                    attribs.insert(vertex_attrib.name, pair);
                },
                None => {
                    missing.push(vertex_attrib.name);
                }
            }
        });

        let unknown: Vec<_> = {
            let expected: HashSet<_> = self.attribs.keys().collect();
            let actual: HashSet<_> = attribs.keys().collect();
            expected.difference(&actual).cloned().cloned().collect()
        };

        if missing.is_empty() && unknown.is_empty() {
            for (_, (vertex_attrib, program_attrib)) in attribs.into_iter() {
                f(vertex_attrib, program_attrib);
            }
            Ok(())
        }
        else {
            Err(AttribError {
                missing_attribs: missing,
                unknown_attribs: unknown
            })
        }
    }

    pub fn enable<T, AB, EAB, P, FB, RB, TU>(&self,
                                             gl: &ContextOf<AB,
                                                            EAB,
                                                            P,
                                                            FB,
                                                            RB,
                                                            TU>)
        -> Result<(), AttribError>
        where T: VertexData
    {
        self.for_each::<T, _>(|_, program_attrib| {
            gl.enable_vertex_attrib_array(program_attrib);
        })
    }

    pub fn bind<T: VertexData>(&self, gl_buffer: &ArrayBufferBinding)
        -> Result<(), AttribError>
    {
        self.for_each::<T, _>(|vertex_attrib, program_attrib| {
            unsafe {
                gl_buffer.vertex_attrib_pointer(
                    program_attrib,
                    vertex_attrib.ty.components,
                    vertex_attrib.ty.data,
                    vertex_attrib.ty.normalize,
                    vertex_attrib.stride,
                    vertex_attrib.offset
                );
            }
        })
    }
}

#[derive(Debug)]
pub enum VertexBindError {
    BindingError(AttribError),
    NoAttributeBindings
}

impl From<AttribError> for VertexBindError {
    fn from(attrib_error: AttribError) -> VertexBindError {
        VertexBindError::BindingError(attrib_error)
    }
}

pub struct VertexBuffer<T: VertexData> {
    attrib_binder: Option<AttribBinder>,
    buffer: Buffer,
    count: usize,
    phantom: PhantomData<*const T>
}

impl<T: VertexData> VertexBuffer<T> {
    pub fn bind_attrib_pointers(&mut self, binder: AttribBinder) {
        self.attrib_binder = Some(binder);
    }

    pub fn bind<AB, EAB, P, FB, RB, TU>(&mut self,
                                        gl: &mut ContextOf<AB,
                                                           EAB,
                                                           P,
                                                           FB,
                                                           RB,
                                                           TU>)
        -> Result<(), VertexBindError>
        where AB: BorrowMut<ArrayBufferBinder>
    {
        match self.attrib_binder {
            Some(ref binder) => {
                let (mut buffer_binder, mut gl) = gl.split_array_buffer_mut();
                let gl_buffer = buffer_binder.bind(&mut self.buffer);
                try!(binder.enable::<T, _, _, _, _, _, _>(&mut gl));
                try!(binder.bind::<T>(&gl_buffer));
                Ok(())
            },
            None => { Err(VertexBindError::NoAttributeBindings) }
        }
    }

    pub fn buffer(&self) -> &Buffer {
        &self.buffer
    }

    pub fn buffer_mut(&mut self) -> &mut Buffer {
        &mut self.buffer
    }
}

pub struct VertexBufferBinding<'a, T: VertexData + 'a> {
    gl_buffer: ArrayBufferBinding<'a>,
    vbo: &'a mut VertexBuffer<T>
}

impl<'a, T: VertexData + 'a> VertexBufferBinding<'a, T> {
    pub fn new(gl_buffer: ArrayBufferBinding<'a>, vbo: &'a mut VertexBuffer<T>)
        -> Self
    {
        VertexBufferBinding {
            gl_buffer: gl_buffer,
            vbo: vbo
        }
    }

    pub fn buffer_data(&mut self, data: &[T], usage: super::BufferDataUsage)
        where [T]: VertexBytes
    {
        self.vbo.count = data.len();
        self.gl_buffer.buffer_bytes(data.vertex_bytes(), usage);
    }
}

impl<'a> FramebufferBinding<'a> {
    pub fn draw_arrays_range_vbo<T>(&mut self,
                                    gl_vbo: &VertexBufferBinding<T>,
                                    mode: DrawingMode,
                                    start: u32,
                                    length: usize)
        where T: VertexData
    {
        debug_assert!((start as usize) + length <= gl_vbo.vbo.count);

        unsafe {
            self.draw_arrays_range(&gl_vbo.gl_buffer, mode, start, length);
        }
    }

    pub fn draw_arrays_vbo<T>(&mut self,
                              gl_vbo: &VertexBufferBinding<T>,
                              mode: DrawingMode)
        where T: VertexData
    {
        unsafe {
            self.draw_arrays_range(&gl_vbo.gl_buffer,
                                   mode,
                                   0,
                                   gl_vbo.vbo.count);
        }
    }

    pub fn draw_n_elements_buffered_vbo<T, I>(&mut self,
                                              gl_vbo: &VertexBufferBinding<T>,
                                              gl_ibo: &IndexBufferBinding<I>,
                                              mode: DrawingMode,
                                              length: usize)
        where T: VertexData, I: IndexDatum
    {
        debug_assert!(length <= gl_ibo.ibo.count);

        unsafe {
            self.draw_n_elements_buffered(&gl_vbo.gl_buffer,
                                          &gl_ibo.gl_buffer,
                                          mode,
                                          length,
                                          I::index_datum_type());
        }
    }

    pub fn draw_elements_buffered_vbo<T, I>(&mut self,
                                            gl_vbo: &VertexBufferBinding<T>,
                                            gl_ibo: &IndexBufferBinding<I>,
                                            mode: DrawingMode)
        where T: VertexData, I: IndexDatum
    {
        unsafe {
            self.draw_n_elements_buffered(&gl_vbo.gl_buffer,
                                          &gl_ibo.gl_buffer,
                                          mode,
                                          gl_ibo.ibo.count,
                                          I::index_datum_type());
        }
    }

    pub fn draw_n_elements_vbo<T, I>(&mut self,
                                     gl_vbo: &VertexBufferBinding<'a, T>,
                                     mode: DrawingMode,
                                     count: usize,
                                     indices: &[I])
        where T: VertexData, I: IndexDatum, [I]: IndexData
    {
        unsafe {
            self.draw_n_elements(&gl_vbo.gl_buffer, mode, count, indices);
        }
    }

    pub fn draw_elements_vbo<T, I>(&mut self,
                                   gl_vbo: &VertexBufferBinding<'a, T>,
                                   mode: DrawingMode,
                                   indices: &[I])
        where T: VertexData, I: IndexDatum, [I]: IndexData
    {
        unsafe {
            self.draw_elements(&gl_vbo.gl_buffer, mode, indices);
        }
    }
}

impl<AB, EAB, P, FB, RB, TU> ContextOf<AB, EAB, P, FB, RB, TU> {
    pub fn new_vertex_buffer<T: VertexData>(&self) -> VertexBuffer<T> {
        VertexBuffer {
            attrib_binder: None,
            buffer: self.gen_buffer(),
            count: 0,
            phantom: PhantomData
        }
    }

    pub fn bind_vertex_buffer<'a, T>(&'a mut self, vbo: &'a mut VertexBuffer<T>)
        -> (
            VertexBufferBinding<T>,
            ContextOf<(),
                      &'a mut EAB,
                      &'a mut P,
                      &'a mut FB,
                      &'a mut RB,
                      &'a mut TU>
        )
        where T: VertexData, AB: BorrowMut<ArrayBufferBinder>
    {
        vbo.bind(self).unwrap();
        let (mut array_buffer, gl) = self.split_array_buffer_mut();
        let gl_array_buffer = array_buffer.bind(vbo.buffer_mut());
        (VertexBufferBinding::new(gl_array_buffer, vbo), gl)
    }

    pub fn bind_index_buffer<'a, T>(&'a mut self, ibo: &'a mut IndexBuffer<T>)
        -> (
            IndexBufferBinding<T>,
            ContextOf<&'a mut AB,
                      (),
                      &'a mut P,
                      &'a mut FB,
                      &'a mut RB,
                      &'a mut TU>
        )
        where T: IndexDatum, EAB: BorrowMut<ElementArrayBufferBinder>
    {
        let (mut eab, gl) = self.split_element_array_buffer_mut();
        let gl_eab = eab.bind(ibo.buffer_mut());
        (IndexBufferBinding::new(gl_eab, ibo), gl)
    }
}

pub struct IndexBuffer<T: IndexDatum> {
    buffer: Buffer,
    count: usize,
    phantom: PhantomData<*const T>
}

impl<T: IndexDatum> IndexBuffer<T> {
    pub fn buffer(&self) -> &Buffer {
        &self.buffer
    }

    pub fn buffer_mut(&mut self) -> &mut Buffer {
        &mut self.buffer
    }
}

pub struct IndexBufferBinding<'a, T: IndexDatum + 'a> {
    gl_buffer: ElementArrayBufferBinding<'a>,
    ibo: &'a mut IndexBuffer<T>
}

impl<'a, T: IndexDatum + 'a> IndexBufferBinding<'a, T> {
    pub fn new(gl_buffer: ElementArrayBufferBinding<'a>,
               ibo: &'a mut IndexBuffer<T>)
        -> Self
    {
        IndexBufferBinding {
            gl_buffer: gl_buffer,
            ibo: ibo
        }
    }

    pub fn buffer_data(&mut self, data: &[T], usage: super::BufferDataUsage)
        where [T]: IndexData
    {
        self.ibo.count = data.len();
        self.gl_buffer.buffer_bytes(data.index_bytes(), usage);
    }
}

impl<AB, EAB, P, FB, RB, TU> ContextOf<AB, EAB, P, FB, RB, TU> {
    pub fn new_index_buffer<T: IndexDatum>(&self) -> IndexBuffer<T> {
        IndexBuffer {
            buffer: self.gen_buffer(),
            count: 0,
            phantom: PhantomData
        }
    }
}

#[macro_export]
macro_rules! attrib_pointers {
    ($gl:expr, $vbo:expr, {
        $($field_name:ident => $field_attrib:expr),*
    }) => {
        {
            let mut binder = $crate::AttribBinder::new();
            $(binder.add(stringify!($field_name), $field_attrib).unwrap());*;
            binder
        }
    }
}

#[macro_export]
macro_rules! bind_attrib_pointers {
    ($gl:expr, $vbo:expr, {
        $($field_name:ident => $field_attrib:expr),*
    }) => {
        {
            let vbo = $vbo;
            let binder = {
                attrib_pointers!($gl, vbo, {
                    $($field_name => $field_attrib),*
                })
            };
            vbo.bind_attrib_pointers(binder);
        }
    }
}

#[macro_export]
macro_rules! bind_vertex_buffer {
    ($gl:expr, $vbo:expr) => {
        {
            use std::borrow::BorrowMut;
            let mut vbo = $vbo;

            let (gl_vbo, _) = $gl.bind_vertex_buffer(vbo.borrow_mut());
            gl_vbo
        }
    }
}

#[macro_export]
macro_rules! bind_index_buffer {
    ($gl:expr, $ibo:expr) => {
        {
            use std::borrow::BorrowMut;
            let mut ibo = $ibo;

            let (gl_ibo, _) = $gl.bind_index_buffer(ibo.borrow_mut());
            gl_ibo
        }
    }
}
<|endoftext|>


<commit_before>use std::collections::HashMap;
use std::collections::hash_map::Entry;

use ast::{InputValue, Selection, Directive, FromInputValue};
use value::Value;

use schema::meta::{Argument, MetaType};
use executor::{Executor, Registry, ExecutionResult};
use parser::Spanning;

/// GraphQL type kind
///
/// The GraphQL specification defines a number of type kinds - the meta type
/// of a type.
#[derive(Clone, Eq, PartialEq, Debug)]
pub enum TypeKind {
    /// ## Scalar types
    ///
    /// Scalar types appear as the leaf nodes of GraphQL queries. Strings,
    /// numbers, and booleans are the built in types, and while it's possible
    /// to define your own, it's relatively uncommon.
    Scalar,

    /// ## Object types
    ///
    /// The most common type to be implemented by users. Objects have fields
    /// and can implement interfaces.
    Object,

    /// ## Interface types
    ///
    /// Interface types are used to represent overlapping fields between
    /// multiple types, and can be queried for their concrete type.
    Interface,

    /// ## Union types
    ///
    /// Unions are similar to interfaces but can not contain any fields on
    /// their own.
    Union,

    /// ## Enum types
    ///
    /// Like scalars, enum types appear as the leaf nodes of GraphQL queries.
    Enum,

    /// ## Input objects
    ///
    /// Represents complex values provided in queries _into_ the system.
    InputObject,

    /// ## List types
    ///
    /// Represent lists of other types. This library provides implementations
    /// for vectors and slices, but other Rust types can be extended to serve
    /// as GraphQL lists.
    List,

    /// ## Non-null types
    ///
    /// In GraphQL, nullable types are the default. By putting a `!` after a
    /// type, it becomes non-nullable.
    NonNull,
}

/// Field argument container
pub struct Arguments<'a> {
    args: Option<HashMap<&'a str, InputValue>>,
}

impl<'a> Arguments<'a> {
    #[doc(hidden)]
    pub fn new(mut args: Option<HashMap<&'a str, InputValue>>, meta_args: &'a Option<Vec<Argument>>) -> Arguments<'a> {
        if meta_args.is_some() && args.is_none() {
            args = Some(HashMap::new());
        }

        if let (&mut Some(ref mut args), &Some(ref meta_args)) = (&mut args, meta_args) {
            for arg in meta_args {
                if !args.contains_key(arg.name.as_str()) || args[arg.name.as_str()].is_null() {
                    if let Some(ref default_value) = arg.default_value {
                        args.insert(arg.name.as_str(), default_value.clone());
                    } else {
                        args.insert(arg.name.as_str(), InputValue::null());
                    }
                }
            }
        }

        Arguments {
            args: args
        }
    }

    /// Get and convert an argument into the desired type.
    ///
    /// If the argument is found, or a default argument has been provided,
    /// the `InputValue` will be converted into the type `T`.
    ///
    /// Returns `Some` if the argument is present _and_ type conversion
    /// succeeeds.
    pub fn get<T>(&self, key: &str) -> Option<T> where T: FromInputValue {
        match self.args {
            Some(ref args) => match args.get(key) {
                Some(v) => Some(v.convert().unwrap()),
                None => None,
            },
            None => None,
        }
    }
}

/**
Primary trait used to expose Rust types in a GraphQL schema

All of the convenience macros ultimately expand into an implementation of
this trait for the given type. The macros remove duplicated definitions of
fields and arguments, and add type checks on all resolve functions
automatically. This can all be done manually.

`GraphQLType` provides _some_ convenience methods for you, in the form of
optional trait methods. The `name` and `meta` methods are mandatory, but
other than that, it depends on what type you're exposing:

* Scalars, enums, lists and non null wrappers only require `resolve`,
* Interfaces and objects require `resolve_field` _or_ `resolve` if you want
  to implement custom resolution logic (probably not),
* Interfaces and unions require `resolve_into_type` and `concrete_type_name`.
* Input objects do not require anything

## Example

Manually deriving an object is straightforward but tedious. This is the
equivalent of the `User` object as shown in the example in the documentation
root:

```rust
use juniper::{GraphQLType, Registry, FieldResult, Context,
              Arguments, Executor, ExecutionResult};
use juniper::meta::MetaType;
# use std::collections::HashMap;

struct User { id: String, name: String, friend_ids: Vec<String>  }
struct Database { users: HashMap<String, User> }

impl Context for Database {}

impl GraphQLType for User {
    type Context = Database;

    fn name() -> Option<&'static str> {
        Some("User")
    }

    fn meta(registry: &mut Registry) -> MetaType {
        // First, we need to define all fields and their types on this type.
        //
        // If we need arguments, want to implement interfaces, or want to add
        // documentation strings, we can do it here.
        registry.build_object_type::<User>()(&[
                registry.field::<&String>("id"),
                registry.field::<&String>("name"),
                registry.field::<Vec<&User>>("friends"),
            ])
            .into_meta()
    }

    fn resolve_field(
        &self,
        field_name: &str,
        args: &Arguments,
        executor: &Executor<Database>
    )
        -> ExecutionResult
    {
        // Next, we need to match the queried field name. All arms of this
        // match statement return `ExecutionResult`, which makes it hard to
        // statically verify that the type you pass on to `executor.resolve*`
        // actually matches the one that you defined in `meta()` above.
        let database = executor.context();
        match field_name {
            // Because scalars are defined with another `Context` associated
            // type, you must use resolve_with_ctx here to make the executor
            // perform automatic type conversion of its argument.
            "id" => executor.resolve_with_ctx(&self.id),
            "name" => executor.resolve_with_ctx(&self.name),

            // You pass a vector of User objects to `executor.resolve`, and it
            // will determine which fields of the sub-objects to actually
            // resolve based on the query. The executor instance keeps track
            // of its current position in the query.
            "friends" => executor.resolve(
                &self.friend_ids.iter()
                    .filter_map(|id| database.users.get(id))
                    .collect::<Vec<_>>()
            ),

            // We can only reach this panic in two cases; either a mismatch
            // between the defined schema in `meta()` above, or a validation
            // in this library failed because of a bug.
            //
            // In either of those two cases, the only reasonable way out is
            // to panic the thread.
            _ => panic!("Field {} not found on type User", field_name),
        }
    }
}
```

*/
pub trait GraphQLType: Sized {
    /// The expected context type for this GraphQL type
    ///
    /// The context is threaded through query execution to all affected nodes,
    /// and can be used to hold common data, e.g. database connections or
    /// request session information.
    type Context;

    /// The name of the GraphQL type to expose.
    ///
    /// This function will be called multiple times during schema construction.
    /// It must _not_ perform any calculation and _always_ return the same
    /// value.
    fn name() -> Option<&'static str>;

    /// The meta type representing this GraphQL type.
    fn meta(registry: &mut Registry) -> MetaType;

    /// Resolve the value of a single field on this type.
    ///
    /// The arguments object contain all specified arguments, with default
    /// values substituted for the ones not provided by the query.
    ///
    /// The executor can be used to drive selections into sub-objects.
    ///
    /// The default implementation panics.
    #[allow(unused_variables)]
    fn resolve_field(&self, field_name: &str, arguments: &Arguments, executor: &Executor<Self::Context>)
        -> ExecutionResult
    {
        panic!("resolve_field must be implemented by object types");
    }

    /// Resolve this interface or union into a concrete type
    ///
    /// Try to resolve the current type into the type name provided. If the
    /// type matches, pass the instance along to `executor.resolve`.
    ///
    /// The default implementation panics.
    #[allow(unused_variables)]
    fn resolve_into_type(&self, type_name: &str, selection_set: Option<&[Selection]>, executor: &Executor<Self::Context>) -> ExecutionResult {
        if Self::name().unwrap() == type_name {
            Ok(self.resolve(selection_set, executor))
        } else {
            panic!("resolve_into_type must be implemented by unions and interfaces");
        }
    }

    /// Return the concrete type name for this instance/union.
    ///
    /// The default implementation panics.
    #[allow(unused_variables)]
    fn concrete_type_name(&self, context: &Self::Context) -> String {
        panic!("concrete_type_name must be implemented by unions and interfaces");
    }

    /// Resolve the provided selection set against the current object.
    ///
    /// For non-object types, the selection set will be `None` and the value
    /// of the object should simply be returned.
    ///
    /// For objects, all fields in the selection set should be resolved.
    ///
    /// The default implementation uses `resolve_field` to resolve all fields,
    /// including those through fragment expansion, for object types. For
    /// non-object types, this method panics.
    fn resolve(&self, selection_set: Option<&[Selection]>, executor: &Executor<Self::Context>) -> Value {
        if let Some(selection_set) = selection_set {
            let mut result = HashMap::new();
            resolve_selection_set_into(self, selection_set, executor, &mut result);
            Value::object(result)
        }
        else {
            panic!("resolve() must be implemented by non-object output types");
        }
    }
}

fn resolve_selection_set_into<T, CtxT>(
    instance: &T,
    selection_set: &[Selection],
    executor: &Executor<CtxT>,
    result: &mut HashMap<String, Value>)
    where T: GraphQLType<Context=CtxT>
{
    let meta_type = executor.schema()
        .concrete_type_by_name(T::name().expect("Resolving named type's selection set"))
        .expect("Type not found in schema");

    for selection in selection_set {
        match selection {
            &Selection::Field(Spanning { item: ref f, start: ref start_pos, .. }) => {
                if is_excluded(
                        &match &f.directives {
                            &Some(ref sel) => Some(sel.iter().cloned().map(|s| s.item).collect()),
                            &None => None,
                        },
                        executor.variables()) {
                    continue;
                }

                let response_name = &f.alias.as_ref().unwrap_or(&f.name).item;

                if &f.name.item == "__typename" {
                    result.insert(
                        response_name.clone(),
                        Value::string(
                            instance.concrete_type_name(executor.context())));
                    continue;
                }

                let meta_field = meta_type.field_by_name(&f.name.item)
                    .expect(&format!("Field {} not found on type {:?}", f.name.item, meta_type.name()));

                let exec_vars = executor.variables();

                let mut sub_exec = executor.sub_executor(
                    Some(response_name),
                    start_pos.clone(),
                    f.selection_set.as_ref().map(|v| &v[..]));

                let field_result = instance.resolve_field(
                    &f.name.item,
                    &Arguments::new(
                        f.arguments.as_ref().map(|m|
                            m.item.iter().map(|&(ref k, ref v)|
                                (k.item.as_str(), v.item.clone().into_const(exec_vars))).collect()),
                        &meta_field.arguments),
                    &mut sub_exec);

                match field_result {
                    Ok(v) => merge_key_into(result, response_name.clone(), v),
                    Err(e) => {
                        sub_exec.push_error(e, start_pos.clone());
                        result.insert(response_name.clone(), Value::null());
                    }
                }
            },
            &Selection::FragmentSpread(Spanning { item: ref spread, .. }) => {
                if is_excluded(
                        &match &spread.directives {
                            &Some(ref sel) => Some(sel.iter().cloned().map(|s| s.item).collect()),
                            &None => None,
                        },
                        executor.variables()) {
                    continue;
                }

                let fragment = &executor.fragment_by_name(&spread.name.item)
                    .expect("Fragment could not be found");

                resolve_selection_set_into(
                    instance, &fragment.selection_set[..], executor, result);
            },
            &Selection::InlineFragment(Spanning { item: ref fragment, start: ref start_pos, .. }) => {
                if is_excluded(
                        &match &fragment.directives {
                            &Some(ref sel) => Some(sel.iter().cloned().map(|s| s.item).collect()),
                            &None => None
                        },
                        executor.variables()) {
                    continue;
                }

                let mut sub_exec = executor.sub_executor(
                    None,
                    start_pos.clone(),
                    Some(&fragment.selection_set[..]));

                if let &Some(ref type_condition) = &fragment.type_condition {
                    let sub_result = instance.resolve_into_type(
                        &type_condition.item,
                        Some(&fragment.selection_set[..]),
                        &mut sub_exec);

                    if let Ok(Value::Object(mut hash_map)) = sub_result {
                        for (k, v) in hash_map.drain() {
                            result.insert(k, v);
                        }
                    }
                    else if let Err(e) = sub_result {
                         sub_exec.push_error(e, start_pos.clone());
                    }
                }
                else {
                    resolve_selection_set_into(
                        instance,
                        &fragment.selection_set[..],
                        &mut sub_exec,
                        result);
                }
            },
        }
    }
}

fn is_excluded(directives: &Option<Vec<Directive>>, vars: &HashMap<String, InputValue>) -> bool {
    if let Some(ref directives) = *directives {
        for directive in directives {
            let condition: bool = directive.arguments.iter()
                .flat_map(|m| m.item.get("if"))
                .flat_map(|v| v.item.clone().into_const(vars).convert())
                .next().unwrap();

            if directive.name.item == "skip" && condition {
                return true
            }
            else if directive.name.item == "include" && !condition {
                return true
            }
        }

        false
    }
    else {
        false
    }
}

fn merge_key_into(
    result: &mut HashMap<String, Value>,
    response_name: String,
    value: Value,
) {
    match result.entry(response_name) {
        Entry::Occupied(mut e) => {
            println!("Merging object at '{}'", e.key());
            match (e.get_mut().as_mut_object_value(), value) {
                (Some(dest_obj), Value::Object(src_obj)) => {
                    merge_maps(dest_obj, src_obj);
                },
                _ => {
                    println!("Not merging object/object - this is bad :(");
                }
            }
        },
        Entry::Vacant(e) => {
            e.insert(value);
        },
    }
}

fn merge_maps(
    dest: &mut HashMap<String, Value>,
    src: HashMap<String, Value>,
) {
    for (key, value) in src {
        if dest.contains_key(&key) {
            merge_key_into(dest, key, value);
        }
        else {
            dest.insert(key, value);
        }
    }
}
<commit_msg>Don't clone directive lists during execution<commit_after>use std::collections::HashMap;
use std::collections::hash_map::Entry;

use ast::{InputValue, Selection, Directive, FromInputValue};
use value::Value;

use schema::meta::{Argument, MetaType};
use executor::{Executor, Registry, ExecutionResult};
use parser::Spanning;

/// GraphQL type kind
///
/// The GraphQL specification defines a number of type kinds - the meta type
/// of a type.
#[derive(Clone, Eq, PartialEq, Debug)]
pub enum TypeKind {
    /// ## Scalar types
    ///
    /// Scalar types appear as the leaf nodes of GraphQL queries. Strings,
    /// numbers, and booleans are the built in types, and while it's possible
    /// to define your own, it's relatively uncommon.
    Scalar,

    /// ## Object types
    ///
    /// The most common type to be implemented by users. Objects have fields
    /// and can implement interfaces.
    Object,

    /// ## Interface types
    ///
    /// Interface types are used to represent overlapping fields between
    /// multiple types, and can be queried for their concrete type.
    Interface,

    /// ## Union types
    ///
    /// Unions are similar to interfaces but can not contain any fields on
    /// their own.
    Union,

    /// ## Enum types
    ///
    /// Like scalars, enum types appear as the leaf nodes of GraphQL queries.
    Enum,

    /// ## Input objects
    ///
    /// Represents complex values provided in queries _into_ the system.
    InputObject,

    /// ## List types
    ///
    /// Represent lists of other types. This library provides implementations
    /// for vectors and slices, but other Rust types can be extended to serve
    /// as GraphQL lists.
    List,

    /// ## Non-null types
    ///
    /// In GraphQL, nullable types are the default. By putting a `!` after a
    /// type, it becomes non-nullable.
    NonNull,
}

/// Field argument container
pub struct Arguments<'a> {
    args: Option<HashMap<&'a str, InputValue>>,
}

impl<'a> Arguments<'a> {
    #[doc(hidden)]
    pub fn new(mut args: Option<HashMap<&'a str, InputValue>>, meta_args: &'a Option<Vec<Argument>>) -> Arguments<'a> {
        if meta_args.is_some() && args.is_none() {
            args = Some(HashMap::new());
        }

        if let (&mut Some(ref mut args), &Some(ref meta_args)) = (&mut args, meta_args) {
            for arg in meta_args {
                if !args.contains_key(arg.name.as_str()) || args[arg.name.as_str()].is_null() {
                    if let Some(ref default_value) = arg.default_value {
                        args.insert(arg.name.as_str(), default_value.clone());
                    } else {
                        args.insert(arg.name.as_str(), InputValue::null());
                    }
                }
            }
        }

        Arguments {
            args: args
        }
    }

    /// Get and convert an argument into the desired type.
    ///
    /// If the argument is found, or a default argument has been provided,
    /// the `InputValue` will be converted into the type `T`.
    ///
    /// Returns `Some` if the argument is present _and_ type conversion
    /// succeeeds.
    pub fn get<T>(&self, key: &str) -> Option<T> where T: FromInputValue {
        match self.args {
            Some(ref args) => match args.get(key) {
                Some(v) => Some(v.convert().unwrap()),
                None => None,
            },
            None => None,
        }
    }
}

/**
Primary trait used to expose Rust types in a GraphQL schema

All of the convenience macros ultimately expand into an implementation of
this trait for the given type. The macros remove duplicated definitions of
fields and arguments, and add type checks on all resolve functions
automatically. This can all be done manually.

`GraphQLType` provides _some_ convenience methods for you, in the form of
optional trait methods. The `name` and `meta` methods are mandatory, but
other than that, it depends on what type you're exposing:

* Scalars, enums, lists and non null wrappers only require `resolve`,
* Interfaces and objects require `resolve_field` _or_ `resolve` if you want
  to implement custom resolution logic (probably not),
* Interfaces and unions require `resolve_into_type` and `concrete_type_name`.
* Input objects do not require anything

## Example

Manually deriving an object is straightforward but tedious. This is the
equivalent of the `User` object as shown in the example in the documentation
root:

```rust
use juniper::{GraphQLType, Registry, FieldResult, Context,
              Arguments, Executor, ExecutionResult};
use juniper::meta::MetaType;
# use std::collections::HashMap;

struct User { id: String, name: String, friend_ids: Vec<String>  }
struct Database { users: HashMap<String, User> }

impl Context for Database {}

impl GraphQLType for User {
    type Context = Database;

    fn name() -> Option<&'static str> {
        Some("User")
    }

    fn meta(registry: &mut Registry) -> MetaType {
        // First, we need to define all fields and their types on this type.
        //
        // If we need arguments, want to implement interfaces, or want to add
        // documentation strings, we can do it here.
        registry.build_object_type::<User>()(&[
                registry.field::<&String>("id"),
                registry.field::<&String>("name"),
                registry.field::<Vec<&User>>("friends"),
            ])
            .into_meta()
    }

    fn resolve_field(
        &self,
        field_name: &str,
        args: &Arguments,
        executor: &Executor<Database>
    )
        -> ExecutionResult
    {
        // Next, we need to match the queried field name. All arms of this
        // match statement return `ExecutionResult`, which makes it hard to
        // statically verify that the type you pass on to `executor.resolve*`
        // actually matches the one that you defined in `meta()` above.
        let database = executor.context();
        match field_name {
            // Because scalars are defined with another `Context` associated
            // type, you must use resolve_with_ctx here to make the executor
            // perform automatic type conversion of its argument.
            "id" => executor.resolve_with_ctx(&self.id),
            "name" => executor.resolve_with_ctx(&self.name),

            // You pass a vector of User objects to `executor.resolve`, and it
            // will determine which fields of the sub-objects to actually
            // resolve based on the query. The executor instance keeps track
            // of its current position in the query.
            "friends" => executor.resolve(
                &self.friend_ids.iter()
                    .filter_map(|id| database.users.get(id))
                    .collect::<Vec<_>>()
            ),

            // We can only reach this panic in two cases; either a mismatch
            // between the defined schema in `meta()` above, or a validation
            // in this library failed because of a bug.
            //
            // In either of those two cases, the only reasonable way out is
            // to panic the thread.
            _ => panic!("Field {} not found on type User", field_name),
        }
    }
}
```

*/
pub trait GraphQLType: Sized {
    /// The expected context type for this GraphQL type
    ///
    /// The context is threaded through query execution to all affected nodes,
    /// and can be used to hold common data, e.g. database connections or
    /// request session information.
    type Context;

    /// The name of the GraphQL type to expose.
    ///
    /// This function will be called multiple times during schema construction.
    /// It must _not_ perform any calculation and _always_ return the same
    /// value.
    fn name() -> Option<&'static str>;

    /// The meta type representing this GraphQL type.
    fn meta(registry: &mut Registry) -> MetaType;

    /// Resolve the value of a single field on this type.
    ///
    /// The arguments object contain all specified arguments, with default
    /// values substituted for the ones not provided by the query.
    ///
    /// The executor can be used to drive selections into sub-objects.
    ///
    /// The default implementation panics.
    #[allow(unused_variables)]
    fn resolve_field(&self, field_name: &str, arguments: &Arguments, executor: &Executor<Self::Context>)
        -> ExecutionResult
    {
        panic!("resolve_field must be implemented by object types");
    }

    /// Resolve this interface or union into a concrete type
    ///
    /// Try to resolve the current type into the type name provided. If the
    /// type matches, pass the instance along to `executor.resolve`.
    ///
    /// The default implementation panics.
    #[allow(unused_variables)]
    fn resolve_into_type(&self, type_name: &str, selection_set: Option<&[Selection]>, executor: &Executor<Self::Context>) -> ExecutionResult {
        if Self::name().unwrap() == type_name {
            Ok(self.resolve(selection_set, executor))
        } else {
            panic!("resolve_into_type must be implemented by unions and interfaces");
        }
    }

    /// Return the concrete type name for this instance/union.
    ///
    /// The default implementation panics.
    #[allow(unused_variables)]
    fn concrete_type_name(&self, context: &Self::Context) -> String {
        panic!("concrete_type_name must be implemented by unions and interfaces");
    }

    /// Resolve the provided selection set against the current object.
    ///
    /// For non-object types, the selection set will be `None` and the value
    /// of the object should simply be returned.
    ///
    /// For objects, all fields in the selection set should be resolved.
    ///
    /// The default implementation uses `resolve_field` to resolve all fields,
    /// including those through fragment expansion, for object types. For
    /// non-object types, this method panics.
    fn resolve(&self, selection_set: Option<&[Selection]>, executor: &Executor<Self::Context>) -> Value {
        if let Some(selection_set) = selection_set {
            let mut result = HashMap::new();
            resolve_selection_set_into(self, selection_set, executor, &mut result);
            Value::object(result)
        }
        else {
            panic!("resolve() must be implemented by non-object output types");
        }
    }
}

fn resolve_selection_set_into<T, CtxT>(
    instance: &T,
    selection_set: &[Selection],
    executor: &Executor<CtxT>,
    result: &mut HashMap<String, Value>)
    where T: GraphQLType<Context=CtxT>
{
    let meta_type = executor.schema()
        .concrete_type_by_name(T::name().expect("Resolving named type's selection set"))
        .expect("Type not found in schema");

    for selection in selection_set {
        match selection {
            &Selection::Field(Spanning { item: ref f, start: ref start_pos, .. }) => {
                if is_excluded(&f.directives, executor.variables()) {
                    continue;
                }

                let response_name = &f.alias.as_ref().unwrap_or(&f.name).item;

                if &f.name.item == "__typename" {
                    result.insert(
                        response_name.clone(),
                        Value::string(
                            instance.concrete_type_name(executor.context())));
                    continue;
                }

                let meta_field = meta_type.field_by_name(&f.name.item)
                    .expect(&format!("Field {} not found on type {:?}", f.name.item, meta_type.name()));

                let exec_vars = executor.variables();

                let mut sub_exec = executor.sub_executor(
                    Some(response_name),
                    start_pos.clone(),
                    f.selection_set.as_ref().map(|v| &v[..]));

                let field_result = instance.resolve_field(
                    &f.name.item,
                    &Arguments::new(
                        f.arguments.as_ref().map(|m|
                            m.item.iter().map(|&(ref k, ref v)|
                                (k.item.as_str(), v.item.clone().into_const(exec_vars))).collect()),
                        &meta_field.arguments),
                    &mut sub_exec);

                match field_result {
                    Ok(v) => merge_key_into(result, response_name.clone(), v),
                    Err(e) => {
                        sub_exec.push_error(e, start_pos.clone());
                        result.insert(response_name.clone(), Value::null());
                    }
                }
            },
            &Selection::FragmentSpread(Spanning { item: ref spread, .. }) => {
                if is_excluded(&spread.directives, executor.variables()) {
                    continue;
                }

                let fragment = &executor.fragment_by_name(&spread.name.item)
                    .expect("Fragment could not be found");

                resolve_selection_set_into(
                    instance, &fragment.selection_set[..], executor, result);
            },
            &Selection::InlineFragment(Spanning { item: ref fragment, start: ref start_pos, .. }) => {
                if is_excluded(&fragment.directives, executor.variables()) {
                    continue;
                }

                let mut sub_exec = executor.sub_executor(
                    None,
                    start_pos.clone(),
                    Some(&fragment.selection_set[..]));

                if let &Some(ref type_condition) = &fragment.type_condition {
                    let sub_result = instance.resolve_into_type(
                        &type_condition.item,
                        Some(&fragment.selection_set[..]),
                        &mut sub_exec);

                    if let Ok(Value::Object(mut hash_map)) = sub_result {
                        for (k, v) in hash_map.drain() {
                            result.insert(k, v);
                        }
                    }
                    else if let Err(e) = sub_result {
                         sub_exec.push_error(e, start_pos.clone());
                    }
                }
                else {
                    resolve_selection_set_into(
                        instance,
                        &fragment.selection_set[..],
                        &mut sub_exec,
                        result);
                }
            },
        }
    }
}

fn is_excluded(directives: &Option<Vec<Spanning<Directive>>>, vars: &HashMap<String, InputValue>) -> bool {
    if let Some(ref directives) = *directives {
        for &Spanning { item: ref directive, .. } in directives {
            let condition: bool = directive.arguments.iter()
                .flat_map(|m| m.item.get("if"))
                .flat_map(|v| v.item.clone().into_const(vars).convert())
                .next().unwrap();

            if directive.name.item == "skip" && condition {
                return true
            }
            else if directive.name.item == "include" && !condition {
                return true
            }
        }

        false
    }
    else {
        false
    }
}

fn merge_key_into(
    result: &mut HashMap<String, Value>,
    response_name: String,
    value: Value,
) {
    match result.entry(response_name) {
        Entry::Occupied(mut e) => {
            println!("Merging object at '{}'", e.key());
            match (e.get_mut().as_mut_object_value(), value) {
                (Some(dest_obj), Value::Object(src_obj)) => {
                    merge_maps(dest_obj, src_obj);
                },
                _ => {
                    println!("Not merging object/object - this is bad :(");
                }
            }
        },
        Entry::Vacant(e) => {
            e.insert(value);
        },
    }
}

fn merge_maps(
    dest: &mut HashMap<String, Value>,
    src: HashMap<String, Value>,
) {
    for (key, value) in src {
        if dest.contains_key(&key) {
            merge_key_into(dest, key, value);
        }
        else {
            dest.insert(key, value);
        }
    }
}
<|endoftext|>


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

use cg;
use darling::util::Override;
use quote::Tokens;
use syn::{self, Ident};
use synstructure;

pub fn derive(input: syn::DeriveInput) -> Tokens {
    let name = &input.ident;
    let trait_path = parse_quote!(style_traits::ToCss);
    let (impl_generics, ty_generics, mut where_clause) =
        cg::trait_parts(&input, &trait_path);

    let input_attrs = cg::parse_input_attrs::<CssInputAttrs>(&input);
    let s = synstructure::Structure::new(&input);

    let match_body = s.each_variant(|variant| {
        let bindings = variant.bindings();
        let identifier = cg::to_css_identifier(variant.ast().ident.as_ref());
        let ast = variant.ast();
        let variant_attrs = cg::parse_variant_attrs::<CssVariantAttrs>(&ast);
        let separator = if variant_attrs.comma { ", " } else { " " };

        if variant_attrs.dimension {
            assert_eq!(bindings.len(), 1);
            assert!(
                variant_attrs.function.is_none() && variant_attrs.keyword.is_none(),
                "That makes no sense"
            );
        }

        let mut expr = if let Some(keyword) = variant_attrs.keyword {
            assert!(bindings.is_empty());
            let keyword = keyword.to_string();
            quote! {
                ::std::fmt::Write::write_str(dest, #keyword)
            }
        } else if !bindings.is_empty() {
            let mut expr = quote! {};
            if variant_attrs.iterable {
                assert_eq!(bindings.len(), 1);
                let binding = &bindings[0];
                expr = quote! {
                    #expr

                    for item in #binding.iter() {
                        writer.item(&item)?;
                    }
                };
            } else {
                for binding in bindings {
                    let attrs = cg::parse_field_attrs::<CssFieldAttrs>(&binding.ast());
                    if attrs.skip {
                        continue;
                    }
                    if !attrs.ignore_bound {
                        where_clause.add_trait_bound(&binding.ast().ty);
                    }
                    expr = quote! {
                        #expr
                        writer.item(#binding)?;
                    };
                }
            }

            quote! {{
                let mut writer = ::style_traits::values::SequenceWriter::new(dest, #separator);
                #expr
                Ok(())
            }}
        } else {
            quote! {
                ::std::fmt::Write::write_str(dest, #identifier)
            }
        };

        if variant_attrs.dimension {
            expr = quote! {
                #expr?;
                ::std::fmt::Write::write_str(dest, #identifier)
            }
        } else if let Some(function) = variant_attrs.function {
            let mut identifier = function.explicit().map_or(identifier, |name| name.to_string());
            identifier.push_str("(");
            expr = quote! {
                ::std::fmt::Write::write_str(dest, #identifier)?;
                #expr?;
                ::std::fmt::Write::write_str(dest, ")")
            }
        }
        Some(expr)
    });

    let mut impls = quote! {
        impl #impl_generics ::style_traits::ToCss for #name #ty_generics #where_clause {
            #[allow(unused_variables)]
            #[inline]
            fn to_css<W>(
                &self,
                dest: &mut ::style_traits::CssWriter<W>,
            ) -> ::std::fmt::Result
            where
                W: ::std::fmt::Write
            {
                match *self {
                    #match_body
                }
            }
        }
    };

    if input_attrs.derive_debug {
        impls.append_all(quote! {
            impl #impl_generics ::std::fmt::Debug for #name #ty_generics #where_clause {
                fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                    ::style_traits::ToCss::to_css(
                        self,
                        &mut ::style_traits::CssWriter::new(f),
                    )
                }
            }
        });
    }

    impls
}

#[darling(attributes(css), default)]
#[derive(Default, FromDeriveInput)]
struct CssInputAttrs {
    derive_debug: bool,
    // Here because structs variants are also their whole type definition.
    function: Option<Override<Ident>>,
    // Here because structs variants are also their whole type definition.
    comma: bool,
    // Here because structs variants are also their whole type definition.
    iterable: bool,
}

#[darling(attributes(css), default)]
#[derive(Default, FromVariant)]
pub struct CssVariantAttrs {
    pub function: Option<Override<Ident>>,
    pub iterable: bool,
    pub comma: bool,
    pub dimension: bool,
    pub keyword: Option<String>,
    pub aliases: Option<String>,
}

#[darling(attributes(css), default)]
#[derive(Default, FromField)]
struct CssFieldAttrs {
    ignore_bound: bool,
    skip: bool,
}
<commit_msg>Qualify path to ToCss in #[derive(ToCss)]<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use cg;
use darling::util::Override;
use quote::Tokens;
use syn::{self, Ident};
use synstructure;

pub fn derive(input: syn::DeriveInput) -> Tokens {
    let name = &input.ident;
    let trait_path = parse_quote!(::style_traits::ToCss);
    let (impl_generics, ty_generics, mut where_clause) =
        cg::trait_parts(&input, &trait_path);

    let input_attrs = cg::parse_input_attrs::<CssInputAttrs>(&input);
    let s = synstructure::Structure::new(&input);

    let match_body = s.each_variant(|variant| {
        let bindings = variant.bindings();
        let identifier = cg::to_css_identifier(variant.ast().ident.as_ref());
        let ast = variant.ast();
        let variant_attrs = cg::parse_variant_attrs::<CssVariantAttrs>(&ast);
        let separator = if variant_attrs.comma { ", " } else { " " };

        if variant_attrs.dimension {
            assert_eq!(bindings.len(), 1);
            assert!(
                variant_attrs.function.is_none() && variant_attrs.keyword.is_none(),
                "That makes no sense"
            );
        }

        let mut expr = if let Some(keyword) = variant_attrs.keyword {
            assert!(bindings.is_empty());
            let keyword = keyword.to_string();
            quote! {
                ::std::fmt::Write::write_str(dest, #keyword)
            }
        } else if !bindings.is_empty() {
            let mut expr = quote! {};
            if variant_attrs.iterable {
                assert_eq!(bindings.len(), 1);
                let binding = &bindings[0];
                expr = quote! {
                    #expr

                    for item in #binding.iter() {
                        writer.item(&item)?;
                    }
                };
            } else {
                for binding in bindings {
                    let attrs = cg::parse_field_attrs::<CssFieldAttrs>(&binding.ast());
                    if attrs.skip {
                        continue;
                    }
                    if !attrs.ignore_bound {
                        where_clause.add_trait_bound(&binding.ast().ty);
                    }
                    expr = quote! {
                        #expr
                        writer.item(#binding)?;
                    };
                }
            }

            quote! {{
                let mut writer = ::style_traits::values::SequenceWriter::new(dest, #separator);
                #expr
                Ok(())
            }}
        } else {
            quote! {
                ::std::fmt::Write::write_str(dest, #identifier)
            }
        };

        if variant_attrs.dimension {
            expr = quote! {
                #expr?;
                ::std::fmt::Write::write_str(dest, #identifier)
            }
        } else if let Some(function) = variant_attrs.function {
            let mut identifier = function.explicit().map_or(identifier, |name| name.to_string());
            identifier.push_str("(");
            expr = quote! {
                ::std::fmt::Write::write_str(dest, #identifier)?;
                #expr?;
                ::std::fmt::Write::write_str(dest, ")")
            }
        }
        Some(expr)
    });

    let mut impls = quote! {
        impl #impl_generics ::style_traits::ToCss for #name #ty_generics #where_clause {
            #[allow(unused_variables)]
            #[inline]
            fn to_css<W>(
                &self,
                dest: &mut ::style_traits::CssWriter<W>,
            ) -> ::std::fmt::Result
            where
                W: ::std::fmt::Write
            {
                match *self {
                    #match_body
                }
            }
        }
    };

    if input_attrs.derive_debug {
        impls.append_all(quote! {
            impl #impl_generics ::std::fmt::Debug for #name #ty_generics #where_clause {
                fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                    ::style_traits::ToCss::to_css(
                        self,
                        &mut ::style_traits::CssWriter::new(f),
                    )
                }
            }
        });
    }

    impls
}

#[darling(attributes(css), default)]
#[derive(Default, FromDeriveInput)]
struct CssInputAttrs {
    derive_debug: bool,
    // Here because structs variants are also their whole type definition.
    function: Option<Override<Ident>>,
    // Here because structs variants are also their whole type definition.
    comma: bool,
    // Here because structs variants are also their whole type definition.
    iterable: bool,
}

#[darling(attributes(css), default)]
#[derive(Default, FromVariant)]
pub struct CssVariantAttrs {
    pub function: Option<Override<Ident>>,
    pub iterable: bool,
    pub comma: bool,
    pub dimension: bool,
    pub keyword: Option<String>,
    pub aliases: Option<String>,
}

#[darling(attributes(css), default)]
#[derive(Default, FromField)]
struct CssFieldAttrs {
    ignore_bound: bool,
    skip: bool,
}
<|endoftext|>