Nonuniform metasurfaces (electrically thin composite layers) can be used for shaping refracted and reflected electromagnetic waves. However, known design approaches based on the generalized refraction and reflection laws do not allow realization of perfectly performing devices: there are always some parasitic reflections into undesired directions. In this paper we introduce and discuss a general approach to the synthesis of metasurfaces for full control of transmitted and reflected plane waves and show that perfect performance can be realized. The method is based on the use of an equivalent impedance matrix model which connects the tangential field components at the two sides on the metasurface. With this approach we are able to understand what physical properties of the metasurface are needed in order to perfectly realize the desired response. Furthermore, we determine the required polarizabilities of the metasurface unit cells and discuss suitable cell structures. It appears that only spatially dispersive metasurfaces allow realization of perfect refraction and reflection of incident plane waves into arbitrary directions. In particular, ideal refraction is possible only if the metasurface is bianisotropic (weak spatial dispersion), and ideal reflection without polarization transformation requires spatial dispersion with a specific, strongly nonlocal response to the fields.