Refactor out pattern matching.

In preparation for more general pattern matching of things other than return values, refactor out the match-generation code into a separate function.
Check expected-constant parameters, too.