What are Tor Node Selection Rules?

What are the rules by which Tor Proxies select entry, exit, and middle nodes from the list of Tor nodes? Where is this implemented in the source code?