Bad puns aside, there’s many theories in the scientific literature (from cognitive psychology, linguistics and AI) that describe the mechanisms of puns (and many other types of jokes, really), and they mostly talk about deviations from a script/subverting expectations and norms (Hanks’ theory of norms)/accessing a non-default interpretation that is different from the default one (Giora’s optimal innovation hypothesis).
For the interested reader, i suggest starting with Raskin https://www.degruyter.com/document/doi/10.1515/9783110198492...