Change to conventional algebra notations
Ruby, 112 + 1 (p flag) = 113 bytes
Run as ruby -pe with the code surrounded by single quotes. Full program, even if it looks like just a recursive function at the beginning.
f=-&gt;s{s.scan(/(\w)(\^.+)?/).map{|a,b|[a,b&amp;&amp;?^,b&amp;&amp;f[b]]}.sort_by &amp;:first};gsub(/[\w^]+/){f[$&amp;]*&quot;&quot;};gsub(/\s+/,&quot;&quot;)