Clean, 386 bytes
There's almost certainly huge savings I can get out of the helper function, probably by using another one instead of case
and until
. Working on that.
import StdEnv,Data.List
i=isPrefixOf
$['if(':s]=g')'s\x h=h++['?':x]
$['else if(':s]=g')'s\x h=[':':h]++['?':x]
$['else ':s]=g'='s\x _=[':':x]
$[]=[]
g c s f#(h,t)=span((<>)c)s
#(v,x,y)=case(until(\(_,k)=k==[]||i['if']k||i['else']k)(\q=:(x,y)|y>[]=(x++[hd y],tl y)=q)([],tl t))of([v,'=':x],y)=([v,'='],x,y);(x,y)=([],x,y)
#z= $y
#x=f(init x)h
|z%(1,1)==['=']=z%(0,1)++x++drop 2z=v++x++z