Flatten a Stack Cats program
Retina 0.8.2, 113 107 67 66 bytes

+`\(\)|(\()?(\(((\()|(?&lt;-4&gt;\))|[^()])*(?(4)@)\))(?(1)|(\)))
$5$2$1


Try it online! Includes 3 4 byte saving thanks to @MartinEnder. Explanation:

+`


Repeatedly apply the substitution until there are no matches.

\(\)|


Match an empty loop (in which case nothing is captured so the substitution simply deletes it) or:

(\()?


Optionally match a (. This is captured in group 1 if it matched, but not if it didn't.

(\(


Capture the main body of the match in group 2 and match a (.

(
 (\()
|
 (&lt;-4&gt;\))
|
 [^()]
)*


Repeatedly match either a (, capturing it in group 4, or a ), removing a capture from group 4 (failing if there isn't one), or something else.

(?(4)@)


Ensure that there are no spare captures left in group 4.

\))


End capture group 2 with another ).

(?(1)|(\)))


If capture group 1 was empty, then capture a ) in capture group 5. (So exactly one of those two groups will have a capture).

$5$2$1


Move the bracket captured in either group 1 or group 5 to the other side of group 2. This has the effect of moving the inner loop to the front or the end of the outer loop depending on which side it matched.