Remove catchall receive and return errors from port

This fixes an issue when multiple processes call SPI.transfer. The
catchall receive incorrectly handles a GenServer.call message and this
causes an exception.

Thanks to sandromehic for finding the issue and providing an easy way to
reproduce. See https://github.com/fhunleth/elixir_ale/issues/53.

defmodule ElixirALE.SPI do
  use GenServer

  @moduledoc """
  This module enables Elixir programs to interact with hardware that's connected
  via a SPI bus.
  """

  defmodule State do
    @moduledoc false
    defstruct port: nil, devname: nil
  end

  # NOTE: for :bits_per_word, 0 is interpreted as 8-bits
  @type spi_option ::
          {:mode, 0..3}
          | {:bits_per_word, 0..16}
          | {:speed_hz, pos_integer}
          | {:delay_us, non_neg_integer}

  # Public API
  @doc """
  Return a list of available SPI bus device names.  If nothing is returned,
  it's possible that the kernel driver for that SPI bus is not enabled or the
  kernel's device tree is not configured. On Raspbian, run `raspi-config` and
  look in the advanced options.

  ```
  iex> ElixirALE.SPI.device_names
  ["spidev0.0", "spidev0.1"]
  ```
  """
  @spec device_names() :: [binary]
  def device_names() do
    Path.wildcard("/dev/spidev*")
    |> Enum.map(fn p -> String.replace_prefix(p, "/dev/", "") end)
  end

  @doc """
  Start and link a SPI GenServer.

  SPI bus options include:
   * `mode`: This specifies the clock polarity and phase to use. (0)
   * `bits_per_word`: bits per word on the bus (8)
   * `speed_hz`: bus speed (1000000)
   * `delay_us`: delay between transaction (10)

  Parameters:
   * `devname` is the Linux device name for the bus (e.g., "spidev0.0")
   * `spi_opts` is a keyword list to configure the bus
   * `opts` are any options to pass to GenServer.start_link
  """
  @spec start_link(binary, [spi_option], [term]) :: {:ok, pid}
  def start_link(devname, spi_opts \\ [], opts \\ []) do
    GenServer.start_link(__MODULE__, {devname, spi_opts}, opts)
  end

  @doc """
  Stop the GenServer and release the SPI resources.
  """
  @spec release(pid) :: :ok
  def release(pid) do
    GenServer.cast(pid, :release)
  end

  @doc """
  Perform a SPI transfer. The `data` should be a binary containing the bytes to
  send. Since SPI transfers simultaneously send and receive, the return value
  will be a binary of the same length or an error.
  """
  @spec transfer(pid, binary) :: binary | {:error, term}
  def transfer(pid, data) do
    GenServer.call(pid, {:transfer, data})
  end

  # gen_server callbacks
  def init({devname, spi_opts}) do
    mode = Keyword.get(spi_opts, :mode, 0)
    bits_per_word = Keyword.get(spi_opts, :bits_per_word, 8)
    speed_hz = Keyword.get(spi_opts, :speed_hz, 1_000_000)
    delay_us = Keyword.get(spi_opts, :delay_us, 10)

    executable = :code.priv_dir(:elixir_ale) ++ '/ale'

    port =
      Port.open({:spawn_executable, executable}, [
        {
          :args,
          [
            "spi",
            "/dev/#{devname}",
            Integer.to_string(mode),
            Integer.to_string(bits_per_word),
            Integer.to_string(speed_hz),
            Integer.to_string(delay_us)
          ]
        },
        {:packet, 2},
        :use_stdio,
        :binary,
        :exit_status
      ])

    state = %State{port: port, devname: devname}
    {:ok, state}
  end

  def handle_call({:transfer, data}, _from, state) do
    response = call_port(state, :transfer, data)
    {:reply, response, state}
  end

  def handle_cast(:release, state) do
    {:stop, :normal, state}
  end

  # Private helper functions
  defp call_port(state, command, arguments) do
    msg = {command, arguments}
    send(state.port, {self(), {:command, :erlang.term_to_binary(msg)}})

    receive do
      {_, {:data, response}} ->
        :erlang.binary_to_term(response)
    after
      500 -> {:error, :timeout}
    end
  end
end

defmodule ElixirALE.SPI do
  use GenServer

  @moduledoc """
  This module enables Elixir programs to interact with hardware that's connected
  via a SPI bus.
  """

  defmodule State do
    @moduledoc false
    defstruct port: nil, devname: nil
  end

  # NOTE: for :bits_per_word, 0 is interpreted as 8-bits
  @type spi_option ::
          {:mode, 0..3}
          | {:bits_per_word, 0..16}
          | {:speed_hz, pos_integer}
          | {:delay_us, non_neg_integer}

  # Public API
  @doc """
  Return a list of available SPI bus device names.  If nothing is returned,
  it's possible that the kernel driver for that SPI bus is not enabled or the
  kernel's device tree is not configured. On Raspbian, run `raspi-config` and
  look in the advanced options.

  ```
  iex> ElixirALE.SPI.device_names
  ["spidev0.0", "spidev0.1"]
  ```
  """
  @spec device_names() :: [binary]
  def device_names() do
    Path.wildcard("/dev/spidev*")
    |> Enum.map(fn p -> String.replace_prefix(p, "/dev/", "") end)
  end

  @doc """
  Start and link a SPI GenServer.

  SPI bus options include:
   * `mode`: This specifies the clock polarity and phase to use. (0)
   * `bits_per_word`: bits per word on the bus (8)
   * `speed_hz`: bus speed (1000000)
   * `delay_us`: delay between transaction (10)

  Parameters:
   * `devname` is the Linux device name for the bus (e.g., "spidev0.0")
   * `spi_opts` is a keyword list to configure the bus
   * `opts` are any options to pass to GenServer.start_link
  """
  @spec start_link(binary, [spi_option], [term]) :: {:ok, pid}
  def start_link(devname, spi_opts \\ [], opts \\ []) do
    GenServer.start_link(__MODULE__, {devname, spi_opts}, opts)
  end

  @doc """
  Stop the GenServer and release the SPI resources.
  """
  @spec release(pid) :: :ok
  def release(pid) do
    GenServer.cast(pid, :release)
  end

  @doc """
  Perform a SPI transfer. The `data` should be a binary containing the bytes to
  send. Since SPI transfers simultaneously send and receive, the return value
  will be a binary of the same length.
  """
  @spec transfer(pid, binary) :: binary | {:error, term}
  def transfer(pid, data) do
    GenServer.call(pid, {:transfer, data})
  end

  # gen_server callbacks
  def init({devname, spi_opts}) do
    mode = Keyword.get(spi_opts, :mode, 0)
    bits_per_word = Keyword.get(spi_opts, :bits_per_word, 8)
    speed_hz = Keyword.get(spi_opts, :speed_hz, 1_000_000)
    delay_us = Keyword.get(spi_opts, :delay_us, 10)

    executable = :code.priv_dir(:elixir_ale) ++ '/ale'

    port =
      Port.open({:spawn_executable, executable}, [
        {
          :args,
          [
            "spi",
            "/dev/#{devname}",
            Integer.to_string(mode),
            Integer.to_string(bits_per_word),
            Integer.to_string(speed_hz),
            Integer.to_string(delay_us)
          ]
        },
        {:packet, 2},
        :use_stdio,
        :binary,
        :exit_status
      ])

    state = %State{port: port, devname: devname}
    {:ok, state}
  end

  def handle_call({:transfer, data}, _from, state) do
    {:ok, response} = call_port(state, :transfer, data)
    {:reply, response, state}
  end

  def handle_cast(:release, state) do
    {:stop, :normal, state}
  end

  # Private helper functions
  defp call_port(state, command, arguments) do
    msg = {command, arguments}
    send(state.port, {self(), {:command, :erlang.term_to_binary(msg)}})

    receive do
      {_, {:data, response}} ->
        {:ok, :erlang.binary_to_term(response)}

      _ ->
        :error
    end
  end
end


remve moduledoc

remve moduledoc

defmodule Floki.RawHTML do
  @moduledoc false

  @self_closing_tags [
    "area",
    "base",
    "br",
    "col",
    "command",
    "embed",
    "hr",
    "img",
    "input",
    "keygen",
    "link",
    "meta",
    "param",
    "source",
    "track",
    "wbr"
  ]

  def raw_html(html_tree), do: raw_html(html_tree, "")
  defp raw_html([], html), do: html
  defp raw_html(string, _html) when is_binary(string), do: HtmlEntities.encode(string)
  defp raw_html(tuple, html) when is_tuple(tuple), do: raw_html([tuple], html)

  defp raw_html([string | tail], html) when is_binary(string) do
    raw_html(tail, html <> HtmlEntities.encode(string))
  end

  defp raw_html([{:comment, comment} | tail], html),
    do: raw_html(tail, html <> "<!--#{comment}-->")

  defp raw_html([{:pi, "xml", attrs} | tail], html) do
    raw_html(tail, html <> "<?xml " <> tag_attrs(attrs) <> "?>")
  end

  defp raw_html([{:doctype, type, public, system} | tail], html) do
    attr =
      case {public, system} do
        {"", ""} -> ""
        {"", system} -> " SYSTEM \"#{system}\""
        {public, system} -> " PUBLIC \"#{public}\" \"#{system}\""
      end

    raw_html(tail, html <> "<!DOCTYPE #{type}#{attr}>")
  end

  defp raw_html([{type, attrs, children} | tail], html) do
    raw_html(tail, html <> tag_for(type, attrs, children))
  end

  defp tag_attrs(attr_list) do
    attr_list
    |> Enum.reduce("", &build_attrs/2)
    |> String.trim()
  end

  defp tag_with_attrs(type, [], children), do: "<#{type}" <> close_open_tag(type, children)

  defp tag_with_attrs(type, attrs, children) do
    "<#{type} #{tag_attrs(attrs)}" <> close_open_tag(type, children)
  end

  defp close_open_tag(type, []) when type in @self_closing_tags, do: "/>"
  defp close_open_tag(_type, _), do: ">"

  defp close_end_tag(type, []) when type in @self_closing_tags, do: ""
  defp close_end_tag(type, _), do: "</#{type}>"

  defp build_attrs({attr, value}, attrs), do: ~s(#{attrs} #{attr}="#{value}")
  defp build_attrs(attr, attrs), do: "#{attrs} #{attr}"

  defp tag_for(type, attrs, content) when type in ["script", "style"] do
    tag_with_attrs(type, attrs, []) <> Enum.join(content) <> "</#{type}>"
  end

  defp tag_for(type, attrs, children) do
    tag_with_attrs(type, attrs, children) <> raw_html(children) <> close_end_tag(type, children)
  end
end

defmodule Floki.RawHTML do
  @moduledoc"""
  Converts html parse trees back into binary html
  """

  @self_closing_tags [
    "area",
    "base",
    "br",
    "col",
    "command",
    "embed",
    "hr",
    "img",
    "input",
    "keygen",
    "link",
    "meta",
    "param",
    "source",
    "track",
    "wbr"
  ]

  def raw_html(html_tree), do: raw_html(html_tree, "")
  defp raw_html([], html), do: html
  defp raw_html(string, _html) when is_binary(string), do: HtmlEntities.encode(string)
  defp raw_html(tuple, html) when is_tuple(tuple), do: raw_html([tuple], html)

  defp raw_html([string | tail], html) when is_binary(string) do
    raw_html(tail, html <> HtmlEntities.encode(string))
  end

  defp raw_html([{:comment, comment} | tail], html),
    do: raw_html(tail, html <> "<!--#{comment}-->")

  defp raw_html([{:pi, "xml", attrs} | tail], html) do
    raw_html(tail, html <> "<?xml " <> tag_attrs(attrs) <> "?>")
  end

  defp raw_html([{:doctype, type, public, system} | tail], html) do
    attr =
      case {public, system} do
        {"", ""} -> ""
        {"", system} -> " SYSTEM \"#{system}\""
        {public, system} -> " PUBLIC \"#{public}\" \"#{system}\""
      end

    raw_html(tail, html <> "<!DOCTYPE #{type}#{attr}>")
  end

  defp raw_html([{type, attrs, children} | tail], html) do
    raw_html(tail, html <> tag_for(type, attrs, children))
  end

  defp tag_attrs(attr_list) do
    attr_list
    |> Enum.reduce("", &build_attrs/2)
    |> String.trim()
  end

  defp tag_with_attrs(type, [], children), do: "<#{type}" <> close_open_tag(type, children)

  defp tag_with_attrs(type, attrs, children) do
    "<#{type} #{tag_attrs(attrs)}" <> close_open_tag(type, children)
  end

  defp close_open_tag(type, []) when type in @self_closing_tags, do: "/>"
  defp close_open_tag(_type, _), do: ">"

  defp close_end_tag(type, []) when type in @self_closing_tags, do: ""
  defp close_end_tag(type, _), do: "</#{type}>"

  defp build_attrs({attr, value}, attrs), do: ~s(#{attrs} #{attr}="#{value}")
  defp build_attrs(attr, attrs), do: "#{attrs} #{attr}"

  defp tag_for(type, attrs, content) when type in ["script", "style"] do
    tag_with_attrs(type, attrs, []) <> Enum.join(content) <> "</#{type}>"
  end

  defp tag_for(type, attrs, children) do
    tag_with_attrs(type, attrs, children) <> raw_html(children) <> close_end_tag(type, children)
  end
end


default-world > Remove touches for now.

default-world > Remove touches for now.

defmodule Default.Pools.Character do
  import Moongate.Pool

  @move_transform %{
    mode: "linear",
    tag: "movement"
  }
  @standing 0
  @walking 1
  @attacking 2

  attributes %{
    name:         {:string, "a noob"},
    speed:        {:float, 0.125},
    height:       {:int, 24},
    width:        {:int, 24},
    x:            {:float, 50.0},
    y:            {:float, 50.0},
    direction:    {:string, "up"},
    stance:       {:int, @standing},

    archetype:    {:string, "elf"},
    attack:       {:int, 0},
    attack_delay: {:int, 100},
    dead:         {:int, 0},
    defense:      {:int, 0},
    health:       {:int, 3},
    max_health:   {:int, 3},
    rupees:       {:int, 0}
  }
  cascades [
    {:sync_movement, {:every, 100}},
    {:sync_all, {:upon, Character, :sync}},
    {:check_if_hurt, {:upon, Character, :attack}},
    {:reset_stance, {:upon, Character, :reset_stance}},
    {:sync_initial, {:upon, Character, :create}},
    {:sync_drop, {:upon, Character, :drop}},
    {:sync_other, {:upon, Pickup, :sync}},
    {:sync_other, {:upon, Particle, :sync}}
  ]
  touches []

  def move(event, params) do
    char = event.this
    speed = attr(char, :speed)
    stance = attr(char, :stance)

    if stance != @attacking do
      set_direction(char, params)
      start_moving(char, params, speed)
      set(char, :stance, @walking)
    end
  end

  def start_moving(char, {x_delta, y_delta}, speed) do
    cond do
      x_delta < 0 -> mutate(char, :x, -speed, @move_transform)
      y_delta < 0 -> mutate(char, :y, -speed, @move_transform)
      x_delta > 0 -> mutate(char, :x, speed, @move_transform)
      y_delta > 0 -> mutate(char, :y, speed, @move_transform)
    end
  end

  def set_direction(char, {x_delta, y_delta}) do
    cond do
      x_delta < 0 -> set(char, :direction, "left")
      y_delta < 0 -> set(char, :direction, "up")
      x_delta > 0 -> set(char, :direction, "right")
      y_delta > 0 -> set(char, :direction, "down")
    end
  end

  def touches(event, {Projectile, projectile}) do
  end

  def stop(event, params) do
    stance = attr(event.this, :stance)

    if stance != @attacking do
      stop_moving(event.this, params)
      bubble(event, :sync)
    end
  end

  def stop_moving(char, {x_delta, y_delta}) do
    if (x_delta != 0), do: mutate(char, :x, 0, @move_transform)
    if (y_delta != 0), do: mutate(char, :y, 0, @move_transform)
    if (x_delta != 0 && y_delta != 0), edo: set(char, :stance, @standing)
  end

  def attack(event) do
    char = event.this
    archetype = attr(char, :archetype)
    dead = attr(char, :dead)
    delay = attr(char, :attack_delay)

    unless dead == 1 do
      stop(event, {1, 1})
      set(char, :stance, @attacking)
      echo_after(delay, event, {:reset_stance})
      attack = attack_for(archetype, char)
      bubble(event, :attack, attack)
      add_particle(event, attack)
    end
  end

  def reset_stance(event) do
    char = event.this
    set(char, :stance, @standing)
  end

  def attack_for("elf", char) do
    id = attr(char, :origin).id
    {x, y, w, h, d} = positional_attributes(char)

    case d do
      "up" -> {id, x, y - 16, 32, 32, "slash", d}
      "down" -> {id, x, y + h + 2, 32, 32, "slash", d}
      "left" -> {id, x - 34, y, 32, 32, "slash", d}
      "right" -> {id, x + w + 2, y, 32, 32, "slash", d}
    end
  end

  def attack_for("mage", char) do
    id = attr(char, :origin).id
    {x, y, w, h, d} = positional_attributes(char)

    case d do
      "up" -> {id, d, x + 6, y - 48, 20, 20, "sparkles"}
      "down" -> {id, d, x + 6, y + h + 12, 20, 20, "sparkles"}
      "left" -> {id, d, x - 48, y + 6, 20, 20, "sparkles"}
      "right" -> {id, d, x + w + 12, y + 6, 20, 20, "sparkles"}
    end
  end

  def attack_for("skeleton", char) do
    IO.puts "TODO"
  end

  def add_particle(event, attack) do
    case attack do
      {a_id, a_x, a_y, a_w, a_h, "slash"} ->
        echo(event, {:add_particle, {a_x, a_y, "slash", 400}})
      {a_id, a_x, a_y, a_w, a_h, "slash", a_d} ->
        echo(event, {:add_particle, {a_x, a_y, "slash", 400, a_d}})
      _ -> nil
    end
  end

  def check_if_hurt(event, attack) do
    char = event.this

    if hit?(char, attack) do
      health = attr(char, :health)

      if health > 1 do
        set(char, :health, health - 1)
      else
        set(char, :health, 0)
        set(char, :dead, 1)
      end
    end
  end

  def hit?(char, {a_id, a_x, a_y, a_w, a_h, a_type}) do
    hit?(char, {a_id, a_x, a_y, a_w, a_h, a_type, "default"})
  end

  def hit?(char, {a_id, a_x, a_y, a_w, a_h, _a_type, _a_direction}) do
    id = attr(char, :origin).id
    {x, y, w, h, d} = positional_attributes(char)

    id != a_id &&
      x < a_x + a_w &&
      x + w > a_x &&
      y < a_y + a_h &&
      y + h > a_y
  end

  def positional_attributes(char) do
    direction = attr(char, :direction)
    x = attr(char, :x)
    y = attr(char, :y)
    width = attr(char, :width)
    height = attr(char, :height)

    {x, y, width, height, direction}
  end

  # Sync

  def sync_movement(event, params), do: sync_movement(event)
  def sync_movement(event) do
    if attr(event.this, :stance) == @walking do
      bubble(event, :sync)
    end
  end

  def sync_all(event, params), do: sync_all(event)
  def sync_all(event) do
    packet = sync(event, Character, [:name, :x, :y, :direction, :stance, :health])
    tell(event.this, packet)
  end

  def sync_initial(event, params), do: sync_all(event)
  def sync_initial(event) do
    packet = sync(event, Character, [
      :archetype,
      :direction,
      :health,
      :max_health,
      :name,
      :origin,
      :rupees,
      :stance,
      :x,
      :y,
    ])
    tell(event.this, packet)
  end

  def sync_drop(event, {char}) do
    packet = tagged(event, char, "drop")
    tell(event.this, packet)
  end

  def sync_one(event, params) do
    packet = sync(event, {Character, hd(params)}, [:name, :x, :y, :direction, :stance])
    tell(event.this, packet)
  end

  def sync_other(event, {packet}) do
    tell(event.this, packet)
  end
end

defmodule Default.Pools.Character do
  import Moongate.Pool

  @move_transform %{
    mode: "linear",
    tag: "movement"
  }
  @standing 0
  @walking 1
  @attacking 2

  attributes %{
    name:         {:string, "a noob"},
    speed:        {:float, 0.125},
    height:       {:int, 24},
    width:        {:int, 24},
    x:            {:float, 50.0},
    y:            {:float, 50.0},
    direction:    {:string, "up"},
    stance:       {:int, @standing},

    archetype:    {:string, "elf"},
    attack:       {:int, 0},
    attack_delay: {:int, 100},
    dead:         {:int, 0},
    defense:      {:int, 0},
    health:       {:int, 3},
    max_health:   {:int, 3},
    rupees:       {:int, 0}
  }
  cascades [
    {:sync_movement, {:every, 100}},
    {:sync_all, {:upon, Character, :sync}},
    {:check_if_hurt, {:upon, Character, :attack}},
    {:reset_stance, {:upon, Character, :reset_stance}},
    {:sync_initial, {:upon, Character, :create}},
    {:sync_drop, {:upon, Character, :drop}},
    {:sync_other, {:upon, Pickup, :sync}},
    {:sync_other, {:upon, Particle, :sync}}
  ]
  touches [
    {Projectile, :box, {:x, :y, :height, :width}}
  ]

  def move(event, params) do
    char = event.this
    speed = attr(char, :speed)
    stance = attr(char, :stance)

    if stance != @attacking do
      set_direction(char, params)
      start_moving(char, params, speed)
      set(char, :stance, @walking)
    end
  end

  def start_moving(char, {x_delta, y_delta}, speed) do
    cond do
      x_delta < 0 -> mutate(char, :x, -speed, @move_transform)
      y_delta < 0 -> mutate(char, :y, -speed, @move_transform)
      x_delta > 0 -> mutate(char, :x, speed, @move_transform)
      y_delta > 0 -> mutate(char, :y, speed, @move_transform)
    end
  end

  def set_direction(char, {x_delta, y_delta}) do
    cond do
      x_delta < 0 -> set(char, :direction, "left")
      y_delta < 0 -> set(char, :direction, "up")
      x_delta > 0 -> set(char, :direction, "right")
      y_delta > 0 -> set(char, :direction, "down")
    end
  end

  def touches(event, {Projectile, projectile}) do
  end

  def stop(event, params) do
    stance = attr(event.this, :stance)

    if stance != @attacking do
      stop_moving(event.this, params)
      bubble(event, :sync)
    end
  end

  def stop_moving(char, {x_delta, y_delta}) do
    if (x_delta != 0), do: mutate(char, :x, 0, @move_transform)
    if (y_delta != 0), do: mutate(char, :y, 0, @move_transform)
    if (x_delta != 0 && y_delta != 0), edo: set(char, :stance, @standing)
  end

  def attack(event) do
    char = event.this
    archetype = attr(char, :archetype)
    dead = attr(char, :dead)
    delay = attr(char, :attack_delay)

    unless dead == 1 do
      stop(event, {1, 1})
      set(char, :stance, @attacking)
      echo_after(delay, event, {:reset_stance})
      attack = attack_for(archetype, char)
      bubble(event, :attack, attack)
      add_particle(event, attack)
    end
  end

  def reset_stance(event) do
    char = event.this
    set(char, :stance, @standing)
  end

  def attack_for("elf", char) do
    id = attr(char, :origin).id
    {x, y, w, h, d} = positional_attributes(char)

    case d do
      "up" -> {id, x, y - 16, 32, 32, "slash", d}
      "down" -> {id, x, y + h + 2, 32, 32, "slash", d}
      "left" -> {id, x - 34, y, 32, 32, "slash", d}
      "right" -> {id, x + w + 2, y, 32, 32, "slash", d}
    end
  end

  def attack_for("mage", char) do
    id = attr(char, :origin).id
    {x, y, w, h, d} = positional_attributes(char)

    case d do
      "up" -> {id, d, x + 6, y - 48, 20, 20, "sparkles"}
      "down" -> {id, d, x + 6, y + h + 12, 20, 20, "sparkles"}
      "left" -> {id, d, x - 48, y + 6, 20, 20, "sparkles"}
      "right" -> {id, d, x + w + 12, y + 6, 20, 20, "sparkles"}
    end
  end

  def attack_for("skeleton", char) do
    IO.puts "TODO"
  end

  def add_particle(event, attack) do
    case attack do
      {a_id, a_x, a_y, a_w, a_h, "slash"} ->
        echo(event, {:add_particle, {a_x, a_y, "slash", 400}})
      {a_id, a_x, a_y, a_w, a_h, "slash", a_d} ->
        echo(event, {:add_particle, {a_x, a_y, "slash", 400, a_d}})
      _ -> nil
    end
  end

  def check_if_hurt(event, attack) do
    char = event.this

    if hit?(char, attack) do
      health = attr(char, :health)

      if health > 1 do
        set(char, :health, health - 1)
      else
        set(char, :health, 0)
        set(char, :dead, 1)
      end
    end
  end

  def hit?(char, {a_id, a_x, a_y, a_w, a_h, a_type}) do
    hit?(char, {a_id, a_x, a_y, a_w, a_h, a_type, "default"})
  end

  def hit?(char, {a_id, a_x, a_y, a_w, a_h, _a_type, _a_direction}) do
    id = attr(char, :origin).id
    {x, y, w, h, d} = positional_attributes(char)

    id != a_id &&
      x < a_x + a_w &&
      x + w > a_x &&
      y < a_y + a_h &&
      y + h > a_y
  end

  def positional_attributes(char) do
    direction = attr(char, :direction)
    x = attr(char, :x)
    y = attr(char, :y)
    width = attr(char, :width)
    height = attr(char, :height)

    {x, y, width, height, direction}
  end

  # Sync

  def sync_movement(event, params), do: sync_movement(event)
  def sync_movement(event) do
    if attr(event.this, :stance) == @walking do
      bubble(event, :sync)
    end
  end

  def sync_all(event, params), do: sync_all(event)
  def sync_all(event) do
    packet = sync(event, Character, [:name, :x, :y, :direction, :stance, :health])
    tell(event.this, packet)
  end

  def sync_initial(event, params), do: sync_all(event)
  def sync_initial(event) do
    packet = sync(event, Character, [
      :archetype,
      :direction,
      :health,
      :max_health,
      :name,
      :origin,
      :rupees,
      :stance,
      :x,
      :y,
    ])
    tell(event.this, packet)
  end

  def sync_drop(event, {char}) do
    packet = tagged(event, char, "drop")
    tell(event.this, packet)
  end

  def sync_one(event, params) do
    packet = sync(event, {Character, hd(params)}, [:name, :x, :y, :direction, :stance])
    tell(event.this, packet)
  end

  def sync_other(event, {packet}) do
    tell(event.this, packet)
  end
end


Removed forgotten test

Removed forgotten test

A test was added during generation of json resources. It is now
deleted.

defmodule Vutuv.UserControllerTest do
  use Vutuv.ConnCase

  alias Vutuv.User
  @valid_attrs %{}
  @invalid_attrs %{}

  setup %{conn: conn} do
    {:ok, conn: put_req_header(conn, "accept", "application/json")}
  end

  test "lists all entries on index", %{conn: conn} do
    conn = get conn, user_path(conn, :index)
    assert json_response(conn, 200)["data"] == []
  end

  test "shows chosen resource", %{conn: conn} do
    user = Repo.insert! %User{}
    conn = get conn, user_path(conn, :show, user)
    assert json_response(conn, 200)["data"] == %{"id" => user.id}
  end

  test "renders page not found when id is nonexistent", %{conn: conn} do
    assert_error_sent 404, fn ->
      get conn, user_path(conn, :show, -1)
    end
  end

  test "creates and renders resource when data is valid", %{conn: conn} do
    conn = post conn, user_path(conn, :create), user: @valid_attrs
    assert json_response(conn, 201)["data"]["id"]
    assert Repo.get_by(User, @valid_attrs)
  end

  test "does not create resource and renders errors when data is invalid", %{conn: conn} do
    conn = post conn, user_path(conn, :create), user: @invalid_attrs
    assert json_response(conn, 422)["errors"] != %{}
  end

  test "updates and renders chosen resource when data is valid", %{conn: conn} do
    user = Repo.insert! %User{}
    conn = put conn, user_path(conn, :update, user), user: @valid_attrs
    assert json_response(conn, 200)["data"]["id"]
    assert Repo.get_by(User, @valid_attrs)
  end

  test "does not update chosen resource and renders errors when data is invalid", %{conn: conn} do
    user = Repo.insert! %User{}
    conn = put conn, user_path(conn, :update, user), user: @invalid_attrs
    assert json_response(conn, 422)["errors"] != %{}
  end

  test "deletes chosen resource", %{conn: conn} do
    user = Repo.insert! %User{}
    conn = delete conn, user_path(conn, :delete, user)
    assert response(conn, 204)
    refute Repo.get(User, user.id)
  end
end


make test match description

make test match description

defmodule Dogma.Rule.QuotesInStringTest do
  use ShouldI

  alias Dogma.Rule.QuotesInString
  alias Dogma.Script
  alias Dogma.Error

  defp lint(script) do
    script |> Script.parse!( "foo.ex" ) |> QuotesInString.test
  end

  should "error for a quote in a string" do
    errors = ~S"""
    "Hello, \" world!"
    """ |> lint
    expected_errors = [
      %Error{
        rule:    QuotesInString,
        message: ~s(Prefer the S sigil for strings containing `"`),
        line: 1,
      }
    ]
    assert expected_errors == errors
  end

  should "not error for a quote free string" do
    errors = """
    "Hello, world!"
    """ |> lint
    assert [] == errors
  end

  should "not error for an interpolation-only string" do
    errors = ~S"""
      "#{inspect app_servers_pids}"
    """ |> lint
    assert [] == errors
  end

  should "not error for a quote in a ~s string" do
    errors = """
    ~s(hello, quote -> " <-)
    """ |> lint
    assert [] == errors
  end

  should "not error for a quote in a ~r regex" do
    errors = """
    ~r/"/
    """ |> lint
    assert [] == errors
  end

  should "not error for a quote in a ~R regex" do
    errors = """
    ~R/"/
    """ |> lint
    assert [] == errors
  end

  should "not error for a quote in a ~S string" do
    errors = """
    ~S(hello, quote -> " <-)
    """ |> lint
    assert [] == errors
  end

  should "not error for a quote in a heredoc" do
    errors = ~s(
    """
    Hey look, a quote -> "
    """) |> lint
    assert [] == errors
  end

  should """
  not error for a quote in a binary literal, as sigils are not valid in the
  binary syntax.
  """ do
    errors = ~S"""
    << "\""::utf8, cs::binary >> = string
    """ |> lint
    assert [] == errors
  end
end

defmodule Dogma.Rule.QuotesInStringTest do
  use ShouldI

  alias Dogma.Rule.QuotesInString
  alias Dogma.Script
  alias Dogma.Error

  defp lint(script) do
    script |> Script.parse!( "foo.ex" ) |> QuotesInString.test
  end

  should "error for a quote in a string" do
    errors = ~S"""
    "Hello, \" world!"
    """ |> lint
    expected_errors = [
      %Error{
        rule:    QuotesInString,
        message: ~s(Prefer the S sigil for strings containing `"`),
        line: 1,
      }
    ]
    assert expected_errors == errors
  end

  should "not error for a quote free string" do
    errors = """
    "Hello, world!"
    """ |> lint
    assert [] == errors
  end

  should "not error for an interpolation-only string" do
    errors = ~S"""
      "#{inspect app_servers_pids}"
    """ |> lint
    assert [] == errors
  end

  should "not error for a quote in a ~s string" do
    errors = """
    ~s(hello, quote -> " <-)
    """ |> lint
    assert [] == errors
  end

  should "not error for a quote in a ~r regex" do
    errors = """
    ~r/"/
    """ |> lint
    assert [] == errors
  end

  should "not error for a quote in a ~R regex" do
    errors = """
    ~r/"/
    """ |> lint
    assert [] == errors
  end

  should "not error for a quote in a ~S string" do
    errors = """
    ~S(hello, quote -> " <-)
    """ |> lint
    assert [] == errors
  end

  should "not error for a quote in a heredoc" do
    errors = ~s(
    """
    Hey look, a quote -> "
    """) |> lint
    assert [] == errors
  end

  should """
  not error for a quote in a binary literal, as sigils are not valid in the
  binary syntax.
  """ do
    errors = ~S"""
    << "\""::utf8, cs::binary >> = string
    """ |> lint
    assert [] == errors
  end
end


Fix function argument inconsistencies in docs for scope (#2268)

Add examples to demonstrate the usage of various scope functions

defmodule Phoenix.Router do
  defmodule NoRouteError do
    @moduledoc """
    Exception raised when no route is found.
    """
    defexception plug_status: 404, message: "no route found", conn: nil, router: nil

    def exception(opts) do
      conn   = Keyword.fetch!(opts, :conn)
      router = Keyword.fetch!(opts, :router)
      path   = "/" <> Enum.join(conn.path_info, "/")

      %NoRouteError{message: "no route found for #{conn.method} #{path} (#{inspect router})",
                    conn: conn, router: router}
    end
  end

  @moduledoc """
  Defines a Phoenix router.

  The router provides a set of macros for generating routes
  that dispatch to specific controllers and actions. Those
  macros are named after HTTP verbs. For example:

      defmodule MyApp.Web.Router do
        use Phoenix.Router

        get "/pages/:page", PageController, :show
      end

  The `get/3` macro above accepts a request of format `"/pages/VALUE"` and
  dispatches it to the show action in the `PageController`.

  Routes can also match glob-like patterns, routing any path with a common
  base to the same controller. For example:

      get "/dynamic*anything", DynamicController, :show

  Phoenix's router is extremely efficient, as it relies on Elixir
  pattern matching for matching routes and serving requests.

  ## Helpers

  Phoenix automatically generates a module `Helpers` inside your router
  which contains named helpers to help developers generate and keep
  their routes up to date.

  Helpers are automatically generated based on the controller name.
  For example, the route:

      get "/pages/:page", PageController, :show

  will generate the following named helper:

      MyApp.Web.Router.Helpers.page_path(conn_or_endpoint, :show, "hello")
      "/pages/hello"

      MyApp.Web.Router.Helpers.page_path(conn_or_endpoint, :show, "hello", some: "query")
      "/pages/hello?some=query"

      MyApp.Web.Router.Helpers.page_url(conn_or_endpoint, :show, "hello")
      "http://example.com/pages/hello"

      MyApp.Web.Router.Helpers.page_url(conn_or_endpoint, :show, "hello", some: "query")
      "http://example.com/pages/hello?some=query"

  If the route contains glob-like patterns, parameters for those have to be given as
  list:

      MyApp.Web.Router.Helpers.dynamic_path(conn_or_endpoint, :show, ["dynamic", "something"])
      "/dynamic/something"

  The URL generated in the named URL helpers is based on the configuration for
  `:url`, `:http` and `:https`. However, if for some reason you need to manually
  control the URL generation, the url helpers also allow you to pass in a [`URI`](http://elixir-lang.org/docs/stable/elixir/URI.html)
  struct:

      uri = %URI{scheme: "https", host: "other.example.com"}
      MyApp.Web.Router.Helpers.page_url(uri, :show, "hello")
      "https://other.example.com/pages/hello"

  The named helper can also be customized with the `:as` option. Given
  the route:

      get "/pages/:page", PageController, :show, as: :special_page

  the named helper will be:

      MyApp.Web.Router.Helpers.special_page_path(conn, :show, "hello")
      "/pages/hello"

  ## Scopes and Resources

  It is very common in Phoenix applications to namespace all of your
  routes under the application scope:

      scope "/", MyApp do
        get "/pages/:id", PageController, :show
      end

  The route above will dispatch to `MyApp.PageController`. This syntax
  is not only convenient for developers, since we don't have to repeat
  the `MyApp.` prefix on all routes, but it also allows Phoenix to put
  less pressure in the Elixir compiler. If instead we had written:

    get "/pages/:id", MyApp.PageController, :show

  The Elixir compiler would infer that the router depends directly on
  `MyApp.PageController`, which is not true. By using scopes, Phoenix
  can properly hint to the Elixir compiler the controller is not an
  actual dependency of the router. This provides more efficient
  compilation times.

  Scopes allow us to scope on any path or even on the helper name:

      scope "/api/v1", MyApp, as: :api_v1 do
        get "/pages/:id", PageController, :show
      end

  For example, the route above will match on the path `"/api/v1/pages/:id"`
  and the named route will be `api_v1_page_path`, as expected from the
  values given to `scope/2` option.

  Phoenix also provides a `resources/4` macro that allows developers
  to generate "RESTful" routes to a given resource:

      defmodule MyApp.Web.Router do
        use Phoenix.Router

        resources "/pages", PageController, only: [:show]
        resources "/users", UserController, except: [:delete]
      end

  Finally, Phoenix ships with a `mix phoenix.routes` task that nicely
  formats all routes in a given router. We can use it to verify all
  routes included in the router above:

      $ mix phoenix.routes
      page_path  GET    /pages/:id       PageController.show/2
      user_path  GET    /users           UserController.index/2
      user_path  GET    /users/:id/edit  UserController.edit/2
      user_path  GET    /users/new       UserController.new/2
      user_path  GET    /users/:id       UserController.show/2
      user_path  POST   /users           UserController.create/2
      user_path  PATCH  /users/:id       UserController.update/2
                 PUT    /users/:id       UserController.update/2

  One can also pass a router explicitly as an argument to the task:

      $ mix phoenix.routes MyApp.Web.Router

  Check `scope/2` and `resources/4` for more information.

  ## Pipelines and plugs

  Once a request arrives at the Phoenix router, it performs
  a series of transformations through pipelines until the
  request is dispatched to a desired end-point.

  Such transformations are defined via plugs, as defined
  in the [Plug](http://github.com/elixir-lang/plug) specification.
  Once a pipeline is defined, it can be piped through per scope.

  For example:

      defmodule MyApp.Web.Router do
        use Phoenix.Router

        pipeline :browser do
          plug :fetch_session
          plug :accepts, ["html"]
        end

        scope "/" do
          pipe_through :browser

          # browser related routes and resources
        end
      end

  `Phoenix.Router` imports functions from both `Plug.Conn` and `Phoenix.Controller`
  to help define plugs. In the example above, `fetch_session/2`
  comes from `Plug.Conn` while `accepts/2` comes from `Phoenix.Controller`.

  Note that router pipelines are only invoked after a route is found.
  No plug is invoked in case no matches were found.
  """

  alias Phoenix.Router.Resource
  alias Phoenix.Router.Scope
  alias Phoenix.Router.Route
  alias Phoenix.Router.Helpers

  @http_methods [:get, :post, :put, :patch, :delete, :options, :connect, :trace, :head]

  @doc false
  defmacro __using__(_) do
    quote do
      unquote(prelude())
      unquote(defs())
      unquote(match_dispatch())
    end
  end

  defp prelude() do
    quote do
      Module.register_attribute __MODULE__, :phoenix_routes, accumulate: true
      @phoenix_forwards %{}

      import Phoenix.Router

      # TODO v2: No longer automatically import dependencies
      import Plug.Conn
      import Phoenix.Controller

      # Set up initial scope
      @phoenix_pipeline nil
      Phoenix.Router.Scope.init(__MODULE__)
      @before_compile unquote(__MODULE__)
    end
  end

  # Because those macros are executed multiple times,
  # we end-up generating a huge scope that drastically
  # affects compilation. We work around it by defining
  # those functions only once and calling it over and
  # over again.
  defp defs() do
    quote unquote: false do
      var!(add_resources, Phoenix.Router) = fn resource ->
        path = resource.path
        ctrl = resource.controller
        opts = resource.route

        if resource.singleton do
          Enum.each resource.actions, fn
            :show    -> get    path,            ctrl, :show, opts
            :new     -> get    path <> "/new",  ctrl, :new, opts
            :edit    -> get    path <> "/edit", ctrl, :edit, opts
            :create  -> post   path,            ctrl, :create, opts
            :delete  -> delete path,            ctrl, :delete, opts
            :update  ->
              patch path, ctrl, :update, opts
              put   path, ctrl, :update, Keyword.put(opts, :as, nil)
          end
        else
          param = resource.param

          Enum.each resource.actions, fn
            :index   -> get    path,                             ctrl, :index, opts
            :show    -> get    path <> "/:" <> param,            ctrl, :show, opts
            :new     -> get    path <> "/new",                   ctrl, :new, opts
            :edit    -> get    path <> "/:" <> param <> "/edit", ctrl, :edit, opts
            :create  -> post   path,                             ctrl, :create, opts
            :delete  -> delete path <> "/:" <> param,            ctrl, :delete, opts
            :update  ->
              patch path <> "/:" <> param, ctrl, :update, opts
              put   path <> "/:" <> param, ctrl, :update, Keyword.put(opts, :as, nil)
          end
        end
      end
    end
  end

  @doc false
  def __call__({%Plug.Conn{private: %{phoenix_router: router, phoenix_bypass: {router, pipes}}} = conn, _pipeline, _dispatch}) do
    Enum.reduce(pipes, conn, fn pipe, acc -> apply(router, pipe, [acc, []]) end)
  end
  def __call__({%Plug.Conn{private: %{phoenix_bypass: :all}} = conn, _pipeline, _dispatch}) do
    conn
  end
  def __call__({conn, pipeline, dispatch}) do
    case pipeline.(conn) do
      %Plug.Conn{halted: true} = halted_conn ->
        halted_conn
      %Plug.Conn{} = piped_conn ->
        try do
          dispatch.(piped_conn)
        catch
          :error, reason -> Plug.Conn.WrapperError.reraise(piped_conn, :error, reason)
        end
    end
  end

  defp match_dispatch() do
    quote location: :keep do
      @behaviour Plug

      @doc """
      Callback required by Plug that initializes the router
      for serving web requests.
      """
      def init(opts) do
        opts
      end

      @doc """
      Callback invoked by Plug on every request.
      """
      def call(conn, _opts) do
        conn
        |> prepare()
        |> __match_route__(conn.method, Enum.map(conn.path_info, &URI.decode/1), conn.host)
        |> Phoenix.Router.__call__()
      end

      defoverridable [init: 1, call: 2]
    end
  end

  @anno (if :erlang.system_info(:otp_release) >= '19' do
    [generated: true]
  else
    [line: -1]
  end)

  @doc false
  defmacro __before_compile__(env) do
    routes = env.module |> Module.get_attribute(:phoenix_routes) |> Enum.reverse
    routes_with_exprs = Enum.map(routes, &{&1, Route.exprs(&1)})

    Helpers.define(env, routes_with_exprs)
    matches = Enum.map(routes_with_exprs, &build_match/1)

    # @anno is used here to avoid warnings if forwarding to root path
    match_404 =
      quote @anno do
        def __match_route__(conn, _method, _path_info, _host) do
          raise NoRouteError, conn: conn, router: __MODULE__
        end
      end

    quote do
      @doc false
      def __routes__,  do: unquote(Macro.escape(routes))

      @doc false
      def __helpers__, do: __MODULE__.Helpers

      defp prepare(conn) do
        update_in conn.private,
          &(&1 |> Map.put(:phoenix_pipelines, [])
          |> Map.put(:phoenix_router, __MODULE__)
          |> Map.put(__MODULE__, {conn.script_name, @phoenix_forwards}))
      end

      unquote(matches)
      unquote(match_404)
    end
  end

  defp build_match({_route, exprs}) do
    {conn_block, pipelines, dispatch} = exprs.route_match

    quote do
      @doc false
      def __match_route__(var!(conn), unquote(exprs.verb_match), unquote(exprs.path),
                 unquote(exprs.host)) do

        unquote(conn_block)
        {var!(conn), unquote(pipelines), unquote(dispatch)}
      end
    end
  end

  @doc """
  Generates a route match based on an arbitrary HTTP method.

  Useful for defining routes not included in the builtin macros:

  #{Enum.map_join(@http_methods, ", ", &"`#{&1}`")}

  The catch-all verb, `:*`, may also be used to match all HTTP methods.

  ## Examples

      match(:move, "/events/:id", EventController, :move)

      match(:*, "/any", SomeController, :any)
  """
  defmacro match(verb, path, plug, plug_opts, options \\ []) do
    add_route(:match, verb, path, plug, plug_opts, options)
  end

  for verb <- @http_methods do
    @doc """
    Generates a route to handle a #{verb} request to the given path.
    """
    defmacro unquote(verb)(path, plug, plug_opts, options \\ []) do
      verb = unquote(verb)
      quote bind_quoted: binding() do
        match(verb, path, plug, plug_opts, options)
      end
    end
  end

  defp add_route(kind, verb, path, plug, plug_opts, options) do
    quote do
      @phoenix_routes Scope.route(__MODULE__, unquote(kind), unquote(verb), unquote(path),
                                  unquote(plug), unquote(plug_opts), unquote(options))
    end
  end

  @doc """
  Defines a plug pipeline.

  Pipelines are defined at the router root and can be used
  from any scope.

  ## Examples

      pipeline :api do
        plug :token_authentication
        plug :dispatch
      end

  A scope may then use this pipeline as:

      scope "/" do
        pipe_through :api
      end

  Every time `pipe_through/1` is called, the new pipelines
  are appended to the ones previously given.
  """
  defmacro pipeline(plug, do: block) do
    block =
      quote do
        plug = unquote(plug)
        @phoenix_pipeline []
        unquote(block)
      end

    compiler =
      quote unquote: false do
        Scope.pipeline(__MODULE__, plug)
        {conn, body} = Plug.Builder.compile(__ENV__, @phoenix_pipeline, [])
        def unquote(plug)(unquote(conn), _) do
          try do
            unquote(body)
          catch
            :error, reason ->
              Plug.Conn.WrapperError.reraise(unquote(conn), :error, reason)
          end
        end
        @phoenix_pipeline nil
      end

    quote do
      try do
        unquote(block)
        unquote(compiler)
      after
        :ok
      end
    end
  end

  @doc """
  Defines a plug inside a pipeline.

  See `pipeline/2` for more information.
  """
  defmacro plug(plug, opts \\ []) do
    quote do
      if pipeline = @phoenix_pipeline do
        @phoenix_pipeline [{unquote(plug), unquote(opts), true}|pipeline]
      else
        raise "cannot define plug at the router level, plug must be defined inside a pipeline"
      end
    end
  end

  @doc """
  Defines a pipeline to send the connection through.

  See `pipeline/2` for more information.
  """
  defmacro pipe_through(pipes) do
    quote do
      if pipeline = @phoenix_pipeline do
        raise "cannot pipe_through inside a pipeline"
      else
        Scope.pipe_through(__MODULE__, unquote(pipes))
      end
    end
  end

  @doc """
  Defines "RESTful" routes for a resource.

  The given definition:

      resources "/users", UserController

  will include routes to the following actions:

    * `GET /users` => `:index`
    * `GET /users/new` => `:new`
    * `POST /users` => `:create`
    * `GET /users/:id` => `:show`
    * `GET /users/:id/edit` => `:edit`
    * `PATCH /users/:id` => `:update`
    * `PUT /users/:id` => `:update`
    * `DELETE /users/:id` => `:delete`

  ## Options

  This macro accepts a set of options:

    * `:only` - a list of actions to generate routes for, for example: `[:show, :edit]`
    * `:except` - a list of actions to exclude generated routes from, for example: `[:delete]`
    * `:param` - the name of the parameter for this resource, defaults to `"id"`
    * `:name` - the prefix for this resource. This is used for the named helper
      and as the prefix for the parameter in nested resources. The default value
      is automatically derived from the controller name, i.e. `UserController` will
      have name `"user"`
    * `:as` - configures the named helper exclusively
    * `:singleton` - defines routes for a singleton resource that is looked up by
      the client without referencing an ID. Read below for more information

  ## Singleton resources

  When a resource needs to be looked up without referencing an ID, because
  it contains only a single entry in the given context, the `:singleton`
  option can be used to generate a set of routes that are specific to
  such single resource:

    * `GET /user` => `:show`
    * `GET /user/new` => `:new`
    * `POST /user` => `:create`
    * `GET /user/edit` => `:edit`
    * `PATCH /user` => `:update`
    * `PUT /user` => `:update`
    * `DELETE /user` => `:delete`

  Usage example:

      resources "/account", AccountController, only: [:show], singleton: true

  """
  defmacro resources(path, controller, opts, do: nested_context) do
    add_resources path, controller, opts, do: nested_context
  end

  @doc """
  See `resources/4`.
  """
  defmacro resources(path, controller, do: nested_context) do
    add_resources path, controller, [], do: nested_context
  end

  @doc """
  See `resources/4`.
  """
  defmacro resources(path, controller, opts) do
    add_resources path, controller, opts, do: nil
  end

  @doc """
  See `resources/4`.
  """
  defmacro resources(path, controller) do
    add_resources path, controller, [], do: nil
  end

  defp add_resources(path, controller, options, do: context) do
    scope =
      if context do
        quote do
          scope resource.member, do: unquote(context)
        end
      end

    quote do
      resource = Resource.build(unquote(path), unquote(controller), unquote(options))
      var!(add_resources, Phoenix.Router).(resource)
      unquote(scope)
    end
  end

  @doc """
  Defines a scope in which routes can be nested.

  ## Examples

      scope path: "/api/v1", as: :api_v1, alias: API.V1 do
        get "/pages/:id", PageController, :show
      end

  The generated route above will match on the path `"/api/v1/pages/:id"`
  and will dispatch to `:show` action in `API.V1.PageController`. A named
  helper `api_v1_page_path` will also be generated.

  ## Options

  The supported options are:

    * `:path` - a string containing the path scope
    * `:as` - a string or atom containing the named helper scope
    * `:alias` - an alias (atom) containing the controller scope
    * `:host` - a string containing the host scope, or prefix host scope,
      ie `"foo.bar.com"`, `"foo."`
    * `:private` - a map of private data to merge into the connection when a route matches
    * `:assigns` - a map of data to merge into the connection when a route matches

  """
  defmacro scope(options, do: context) do
    do_scope(options, context)
  end

  @doc """
  Define a scope with the given path.

  This function is a shortcut for:

      scope path: path do
        ...
      end

  ## Examples

      scope "/api/v1", as: :api_v1, alias: API.V1 do
        get "/pages/:id", PageController, :show
      end

  """
  defmacro scope(path, options, do: context) do
    options = quote do
      path = unquote(path)
      case unquote(options) do
        alias when is_atom(alias) -> [path: path, alias: alias]
        options when is_list(options) -> Keyword.put(options, :path, path)
      end
    end
    do_scope(options, context)
  end

  @doc """
  Defines a scope with the given path and alias.

  This function is a shortcut for:

      scope path: path, alias: alias do
        ...
      end

  ## Examples

      scope "/api/v1", API.V1, as: :api_v1 do
        get "/pages/:id", PageController, :show
      end

  """
  defmacro scope(path, alias, options, do: context) do
    options = quote do
      unquote(options)
      |> Keyword.put(:path, unquote(path))
      |> Keyword.put(:alias, unquote(alias))
    end
    do_scope(options, context)
  end

  defp do_scope(options, context) do
    quote do
      Scope.push(__MODULE__, unquote(options))
      try do
        unquote(context)
      after
        Scope.pop(__MODULE__)
      end
    end
  end

  @doc """
  Forwards a request at the given path to a plug.

  All paths that match the forwarded prefix will be sent to
  the forwarded plug. This is useful for sharing a router between
  applications or even breaking a big router into smaller ones.
  The router pipelines will be invoked prior to forwarding the
  connection.

  The forwarded plug will be initialized at compile time.

  Note, however, that we don't advise forwarding to another
  endpoint. The reason is that plugs defined by your app
  and the forwarded endpoint would be invoked twice, which
  may lead to errors.

  ## Examples

      scope "/", MyApp do
        pipe_through [:browser, :admin]

        forward "/admin", SomeLib.AdminDashboard
        forward "/api", ApiRouter
      end

  """
  defmacro forward(path, plug, plug_opts \\ [], router_opts \\ []) do
    router_opts = Keyword.put(router_opts, :as, nil)

    quote unquote: true, bind_quoted: [path: path, plug: plug] do
      path_segments = Route.forward_path_segments(path, plug, @phoenix_forwards)
      @phoenix_forwards Map.put(@phoenix_forwards, plug, path_segments)
      unquote(add_route(:forward, :*, path, plug, plug_opts, router_opts))
    end
  end
end

defmodule Phoenix.Router do
  defmodule NoRouteError do
    @moduledoc """
    Exception raised when no route is found.
    """
    defexception plug_status: 404, message: "no route found", conn: nil, router: nil

    def exception(opts) do
      conn   = Keyword.fetch!(opts, :conn)
      router = Keyword.fetch!(opts, :router)
      path   = "/" <> Enum.join(conn.path_info, "/")

      %NoRouteError{message: "no route found for #{conn.method} #{path} (#{inspect router})",
                    conn: conn, router: router}
    end
  end

  @moduledoc """
  Defines a Phoenix router.

  The router provides a set of macros for generating routes
  that dispatch to specific controllers and actions. Those
  macros are named after HTTP verbs. For example:

      defmodule MyApp.Web.Router do
        use Phoenix.Router

        get "/pages/:page", PageController, :show
      end

  The `get/3` macro above accepts a request of format `"/pages/VALUE"` and
  dispatches it to the show action in the `PageController`.

  Routes can also match glob-like patterns, routing any path with a common
  base to the same controller. For example:

      get "/dynamic*anything", DynamicController, :show

  Phoenix's router is extremely efficient, as it relies on Elixir
  pattern matching for matching routes and serving requests.

  ## Helpers

  Phoenix automatically generates a module `Helpers` inside your router
  which contains named helpers to help developers generate and keep
  their routes up to date.

  Helpers are automatically generated based on the controller name.
  For example, the route:

      get "/pages/:page", PageController, :show

  will generate the following named helper:

      MyApp.Web.Router.Helpers.page_path(conn_or_endpoint, :show, "hello")
      "/pages/hello"

      MyApp.Web.Router.Helpers.page_path(conn_or_endpoint, :show, "hello", some: "query")
      "/pages/hello?some=query"

      MyApp.Web.Router.Helpers.page_url(conn_or_endpoint, :show, "hello")
      "http://example.com/pages/hello"

      MyApp.Web.Router.Helpers.page_url(conn_or_endpoint, :show, "hello", some: "query")
      "http://example.com/pages/hello?some=query"

  If the route contains glob-like patterns, parameters for those have to be given as
  list:

      MyApp.Web.Router.Helpers.dynamic_path(conn_or_endpoint, :show, ["dynamic", "something"])
      "/dynamic/something"

  The URL generated in the named URL helpers is based on the configuration for
  `:url`, `:http` and `:https`. However, if for some reason you need to manually
  control the URL generation, the url helpers also allow you to pass in a [`URI`](http://elixir-lang.org/docs/stable/elixir/URI.html)
  struct:

      uri = %URI{scheme: "https", host: "other.example.com"}
      MyApp.Web.Router.Helpers.page_url(uri, :show, "hello")
      "https://other.example.com/pages/hello"

  The named helper can also be customized with the `:as` option. Given
  the route:

      get "/pages/:page", PageController, :show, as: :special_page

  the named helper will be:

      MyApp.Web.Router.Helpers.special_page_path(conn, :show, "hello")
      "/pages/hello"

  ## Scopes and Resources

  It is very common in Phoenix applications to namespace all of your
  routes under the application scope:

      scope "/", MyApp do
        get "/pages/:id", PageController, :show
      end

  The route above will dispatch to `MyApp.PageController`. This syntax
  is not only convenient for developers, since we don't have to repeat
  the `MyApp.` prefix on all routes, but it also allows Phoenix to put
  less pressure in the Elixir compiler. If instead we had written:

    get "/pages/:id", MyApp.PageController, :show

  The Elixir compiler would infer that the router depends directly on
  `MyApp.PageController`, which is not true. By using scopes, Phoenix
  can properly hint to the Elixir compiler the controller is not an
  actual dependency of the router. This provides more efficient
  compilation times.

  Scopes allow us to scope on any path or even on the helper name:

      scope "/api/v1", MyApp, as: :api_v1 do
        get "/pages/:id", PageController, :show
      end

  For example, the route above will match on the path `"/api/v1/pages/:id"`
  and the named route will be `api_v1_page_path`, as expected from the
  values given to `scope/2` option.

  Phoenix also provides a `resources/4` macro that allows developers
  to generate "RESTful" routes to a given resource:

      defmodule MyApp.Web.Router do
        use Phoenix.Router

        resources "/pages", PageController, only: [:show]
        resources "/users", UserController, except: [:delete]
      end

  Finally, Phoenix ships with a `mix phoenix.routes` task that nicely
  formats all routes in a given router. We can use it to verify all
  routes included in the router above:

      $ mix phoenix.routes
      page_path  GET    /pages/:id       PageController.show/2
      user_path  GET    /users           UserController.index/2
      user_path  GET    /users/:id/edit  UserController.edit/2
      user_path  GET    /users/new       UserController.new/2
      user_path  GET    /users/:id       UserController.show/2
      user_path  POST   /users           UserController.create/2
      user_path  PATCH  /users/:id       UserController.update/2
                 PUT    /users/:id       UserController.update/2

  One can also pass a router explicitly as an argument to the task:

      $ mix phoenix.routes MyApp.Web.Router

  Check `scope/2` and `resources/4` for more information.

  ## Pipelines and plugs

  Once a request arrives at the Phoenix router, it performs
  a series of transformations through pipelines until the
  request is dispatched to a desired end-point.

  Such transformations are defined via plugs, as defined
  in the [Plug](http://github.com/elixir-lang/plug) specification.
  Once a pipeline is defined, it can be piped through per scope.

  For example:

      defmodule MyApp.Web.Router do
        use Phoenix.Router

        pipeline :browser do
          plug :fetch_session
          plug :accepts, ["html"]
        end

        scope "/" do
          pipe_through :browser

          # browser related routes and resources
        end
      end

  `Phoenix.Router` imports functions from both `Plug.Conn` and `Phoenix.Controller`
  to help define plugs. In the example above, `fetch_session/2`
  comes from `Plug.Conn` while `accepts/2` comes from `Phoenix.Controller`.

  Note that router pipelines are only invoked after a route is found.
  No plug is invoked in case no matches were found.
  """

  alias Phoenix.Router.Resource
  alias Phoenix.Router.Scope
  alias Phoenix.Router.Route
  alias Phoenix.Router.Helpers

  @http_methods [:get, :post, :put, :patch, :delete, :options, :connect, :trace, :head]

  @doc false
  defmacro __using__(_) do
    quote do
      unquote(prelude())
      unquote(defs())
      unquote(match_dispatch())
    end
  end

  defp prelude() do
    quote do
      Module.register_attribute __MODULE__, :phoenix_routes, accumulate: true
      @phoenix_forwards %{}

      import Phoenix.Router

      # TODO v2: No longer automatically import dependencies
      import Plug.Conn
      import Phoenix.Controller

      # Set up initial scope
      @phoenix_pipeline nil
      Phoenix.Router.Scope.init(__MODULE__)
      @before_compile unquote(__MODULE__)
    end
  end

  # Because those macros are executed multiple times,
  # we end-up generating a huge scope that drastically
  # affects compilation. We work around it by defining
  # those functions only once and calling it over and
  # over again.
  defp defs() do
    quote unquote: false do
      var!(add_resources, Phoenix.Router) = fn resource ->
        path = resource.path
        ctrl = resource.controller
        opts = resource.route

        if resource.singleton do
          Enum.each resource.actions, fn
            :show    -> get    path,            ctrl, :show, opts
            :new     -> get    path <> "/new",  ctrl, :new, opts
            :edit    -> get    path <> "/edit", ctrl, :edit, opts
            :create  -> post   path,            ctrl, :create, opts
            :delete  -> delete path,            ctrl, :delete, opts
            :update  ->
              patch path, ctrl, :update, opts
              put   path, ctrl, :update, Keyword.put(opts, :as, nil)
          end
        else
          param = resource.param

          Enum.each resource.actions, fn
            :index   -> get    path,                             ctrl, :index, opts
            :show    -> get    path <> "/:" <> param,            ctrl, :show, opts
            :new     -> get    path <> "/new",                   ctrl, :new, opts
            :edit    -> get    path <> "/:" <> param <> "/edit", ctrl, :edit, opts
            :create  -> post   path,                             ctrl, :create, opts
            :delete  -> delete path <> "/:" <> param,            ctrl, :delete, opts
            :update  ->
              patch path <> "/:" <> param, ctrl, :update, opts
              put   path <> "/:" <> param, ctrl, :update, Keyword.put(opts, :as, nil)
          end
        end
      end
    end
  end

  @doc false
  def __call__({%Plug.Conn{private: %{phoenix_router: router, phoenix_bypass: {router, pipes}}} = conn, _pipeline, _dispatch}) do
    Enum.reduce(pipes, conn, fn pipe, acc -> apply(router, pipe, [acc, []]) end)
  end
  def __call__({%Plug.Conn{private: %{phoenix_bypass: :all}} = conn, _pipeline, _dispatch}) do
    conn
  end
  def __call__({conn, pipeline, dispatch}) do
    case pipeline.(conn) do
      %Plug.Conn{halted: true} = halted_conn ->
        halted_conn
      %Plug.Conn{} = piped_conn ->
        try do
          dispatch.(piped_conn)
        catch
          :error, reason -> Plug.Conn.WrapperError.reraise(piped_conn, :error, reason)
        end
    end
  end

  defp match_dispatch() do
    quote location: :keep do
      @behaviour Plug

      @doc """
      Callback required by Plug that initializes the router
      for serving web requests.
      """
      def init(opts) do
        opts
      end

      @doc """
      Callback invoked by Plug on every request.
      """
      def call(conn, _opts) do
        conn
        |> prepare()
        |> __match_route__(conn.method, Enum.map(conn.path_info, &URI.decode/1), conn.host)
        |> Phoenix.Router.__call__()
      end

      defoverridable [init: 1, call: 2]
    end
  end

  @anno (if :erlang.system_info(:otp_release) >= '19' do
    [generated: true]
  else
    [line: -1]
  end)

  @doc false
  defmacro __before_compile__(env) do
    routes = env.module |> Module.get_attribute(:phoenix_routes) |> Enum.reverse
    routes_with_exprs = Enum.map(routes, &{&1, Route.exprs(&1)})

    Helpers.define(env, routes_with_exprs)
    matches = Enum.map(routes_with_exprs, &build_match/1)

    # @anno is used here to avoid warnings if forwarding to root path
    match_404 =
      quote @anno do
        def __match_route__(conn, _method, _path_info, _host) do
          raise NoRouteError, conn: conn, router: __MODULE__
        end
      end

    quote do
      @doc false
      def __routes__,  do: unquote(Macro.escape(routes))

      @doc false
      def __helpers__, do: __MODULE__.Helpers

      defp prepare(conn) do
        update_in conn.private,
          &(&1 |> Map.put(:phoenix_pipelines, [])
          |> Map.put(:phoenix_router, __MODULE__)
          |> Map.put(__MODULE__, {conn.script_name, @phoenix_forwards}))
      end

      unquote(matches)
      unquote(match_404)
    end
  end

  defp build_match({_route, exprs}) do
    {conn_block, pipelines, dispatch} = exprs.route_match

    quote do
      @doc false
      def __match_route__(var!(conn), unquote(exprs.verb_match), unquote(exprs.path),
                 unquote(exprs.host)) do

        unquote(conn_block)
        {var!(conn), unquote(pipelines), unquote(dispatch)}
      end
    end
  end

  @doc """
  Generates a route match based on an arbitrary HTTP method.

  Useful for defining routes not included in the builtin macros:

  #{Enum.map_join(@http_methods, ", ", &"`#{&1}`")}

  The catch-all verb, `:*`, may also be used to match all HTTP methods.

  ## Examples

      match(:move, "/events/:id", EventController, :move)

      match(:*, "/any", SomeController, :any)
  """
  defmacro match(verb, path, plug, plug_opts, options \\ []) do
    add_route(:match, verb, path, plug, plug_opts, options)
  end

  for verb <- @http_methods do
    @doc """
    Generates a route to handle a #{verb} request to the given path.
    """
    defmacro unquote(verb)(path, plug, plug_opts, options \\ []) do
      verb = unquote(verb)
      quote bind_quoted: binding() do
        match(verb, path, plug, plug_opts, options)
      end
    end
  end

  defp add_route(kind, verb, path, plug, plug_opts, options) do
    quote do
      @phoenix_routes Scope.route(__MODULE__, unquote(kind), unquote(verb), unquote(path),
                                  unquote(plug), unquote(plug_opts), unquote(options))
    end
  end

  @doc """
  Defines a plug pipeline.

  Pipelines are defined at the router root and can be used
  from any scope.

  ## Examples

      pipeline :api do
        plug :token_authentication
        plug :dispatch
      end

  A scope may then use this pipeline as:

      scope "/" do
        pipe_through :api
      end

  Every time `pipe_through/1` is called, the new pipelines
  are appended to the ones previously given.
  """
  defmacro pipeline(plug, do: block) do
    block =
      quote do
        plug = unquote(plug)
        @phoenix_pipeline []
        unquote(block)
      end

    compiler =
      quote unquote: false do
        Scope.pipeline(__MODULE__, plug)
        {conn, body} = Plug.Builder.compile(__ENV__, @phoenix_pipeline, [])
        def unquote(plug)(unquote(conn), _) do
          try do
            unquote(body)
          catch
            :error, reason ->
              Plug.Conn.WrapperError.reraise(unquote(conn), :error, reason)
          end
        end
        @phoenix_pipeline nil
      end

    quote do
      try do
        unquote(block)
        unquote(compiler)
      after
        :ok
      end
    end
  end

  @doc """
  Defines a plug inside a pipeline.

  See `pipeline/2` for more information.
  """
  defmacro plug(plug, opts \\ []) do
    quote do
      if pipeline = @phoenix_pipeline do
        @phoenix_pipeline [{unquote(plug), unquote(opts), true}|pipeline]
      else
        raise "cannot define plug at the router level, plug must be defined inside a pipeline"
      end
    end
  end

  @doc """
  Defines a pipeline to send the connection through.

  See `pipeline/2` for more information.
  """
  defmacro pipe_through(pipes) do
    quote do
      if pipeline = @phoenix_pipeline do
        raise "cannot pipe_through inside a pipeline"
      else
        Scope.pipe_through(__MODULE__, unquote(pipes))
      end
    end
  end

  @doc """
  Defines "RESTful" routes for a resource.

  The given definition:

      resources "/users", UserController

  will include routes to the following actions:

    * `GET /users` => `:index`
    * `GET /users/new` => `:new`
    * `POST /users` => `:create`
    * `GET /users/:id` => `:show`
    * `GET /users/:id/edit` => `:edit`
    * `PATCH /users/:id` => `:update`
    * `PUT /users/:id` => `:update`
    * `DELETE /users/:id` => `:delete`

  ## Options

  This macro accepts a set of options:

    * `:only` - a list of actions to generate routes for, for example: `[:show, :edit]`
    * `:except` - a list of actions to exclude generated routes from, for example: `[:delete]`
    * `:param` - the name of the parameter for this resource, defaults to `"id"`
    * `:name` - the prefix for this resource. This is used for the named helper
      and as the prefix for the parameter in nested resources. The default value
      is automatically derived from the controller name, i.e. `UserController` will
      have name `"user"`
    * `:as` - configures the named helper exclusively
    * `:singleton` - defines routes for a singleton resource that is looked up by
      the client without referencing an ID. Read below for more information

  ## Singleton resources

  When a resource needs to be looked up without referencing an ID, because
  it contains only a single entry in the given context, the `:singleton`
  option can be used to generate a set of routes that are specific to
  such single resource:

    * `GET /user` => `:show`
    * `GET /user/new` => `:new`
    * `POST /user` => `:create`
    * `GET /user/edit` => `:edit`
    * `PATCH /user` => `:update`
    * `PUT /user` => `:update`
    * `DELETE /user` => `:delete`

  Usage example:

      resources "/account", AccountController, only: [:show], singleton: true

  """
  defmacro resources(path, controller, opts, do: nested_context) do
    add_resources path, controller, opts, do: nested_context
  end

  @doc """
  See `resources/4`.
  """
  defmacro resources(path, controller, do: nested_context) do
    add_resources path, controller, [], do: nested_context
  end

  @doc """
  See `resources/4`.
  """
  defmacro resources(path, controller, opts) do
    add_resources path, controller, opts, do: nil
  end

  @doc """
  See `resources/4`.
  """
  defmacro resources(path, controller) do
    add_resources path, controller, [], do: nil
  end

  defp add_resources(path, controller, options, do: context) do
    scope =
      if context do
        quote do
          scope resource.member, do: unquote(context)
        end
      end

    quote do
      resource = Resource.build(unquote(path), unquote(controller), unquote(options))
      var!(add_resources, Phoenix.Router).(resource)
      unquote(scope)
    end
  end

  @doc """
  Defines a scope in which routes can be nested.

  ## Examples

      scope "/api/v1", as: :api_v1, alias: API.V1 do
        get "/pages/:id", PageController, :show
      end

  The generated route above will match on the path `"/api/v1/pages/:id"`
  and will dispatch to `:show` action in `API.V1.PageController`. A named
  helper `api_v1_page_path` will also be generated.

  ## Options

  The supported options are:

    * `:path` - a string containing the path scope
    * `:as` - a string or atom containing the named helper scope
    * `:alias` - an alias (atom) containing the controller scope
    * `:host` - a string containing the host scope, or prefix host scope,
      ie `"foo.bar.com"`, `"foo."`
    * `:private` - a map of private data to merge into the connection when a route matches
    * `:assigns` - a map of data to merge into the connection when a route matches

  """
  defmacro scope(options, do: context) do
    do_scope(options, context)
  end

  @doc """
  Define a scope with the given path.

  This function is a shortcut for:

      scope path: path do
        ...
      end

  """
  defmacro scope(path, options, do: context) do
    options = quote do
      path = unquote(path)
      case unquote(options) do
        alias when is_atom(alias) -> [path: path, alias: alias]
        options when is_list(options) -> Keyword.put(options, :path, path)
      end
    end
    do_scope(options, context)
  end

  @doc """
  Defines a scope with the given path and alias.

  This function is a shortcut for:

      scope path: path, alias: alias do
        ...
      end

  """
  defmacro scope(path, alias, options, do: context) do
    options = quote do
      unquote(options)
      |> Keyword.put(:path, unquote(path))
      |> Keyword.put(:alias, unquote(alias))
    end
    do_scope(options, context)
  end

  defp do_scope(options, context) do
    quote do
      Scope.push(__MODULE__, unquote(options))
      try do
        unquote(context)
      after
        Scope.pop(__MODULE__)
      end
    end
  end

  @doc """
  Forwards a request at the given path to a plug.

  All paths that match the forwarded prefix will be sent to
  the forwarded plug. This is useful for sharing a router between
  applications or even breaking a big router into smaller ones.
  The router pipelines will be invoked prior to forwarding the
  connection.

  The forwarded plug will be initialized at compile time.

  Note, however, that we don't advise forwarding to another
  endpoint. The reason is that plugs defined by your app
  and the forwarded endpoint would be invoked twice, which
  may lead to errors.

  ## Examples

      scope "/", MyApp do
        pipe_through [:browser, :admin]

        forward "/admin", SomeLib.AdminDashboard
        forward "/api", ApiRouter
      end

  """
  defmacro forward(path, plug, plug_opts \\ [], router_opts \\ []) do
    router_opts = Keyword.put(router_opts, :as, nil)

    quote unquote: true, bind_quoted: [path: path, plug: plug] do
      path_segments = Route.forward_path_segments(path, plug, @phoenix_forwards)
      @phoenix_forwards Map.put(@phoenix_forwards, plug, path_segments)
      unquote(add_route(:forward, :*, path, plug, plug_opts, router_opts))
    end
  end
end