/* Transforms
 *
 *     try {
 *         // ...
 *     } catch (ex) {
 *         // ...
 *     }
 *
 * into
 *
 *     {
 *         var ex;
 *         try {
 *             // ...
 *         } catch (_ex) {
 *             ex = _ex;
 *         }
 *     }
 */

module.exports = (args) => ({
	type: "BlockStatement",
	body: [
		{
			type: "VariableDeclaration",
			declarations: [
				{
					type: "VariableDeclarator",
					id: args.handler.param,
					init: null,
				},
			],
			kind: "var",
		},
		{
			autogenerated: true,
			type: args.type,
			block: args.block,
			handler: {
				type: "CatchClause",
				param: {
					type: "Identifier",
					name: "_" + args.handler.param.name,
				},
				body: {
					type: "BlockStatement",
					body: [
						{
							type: "ExpressionStatement",
							expression: {
								type: "AssignmentExpression",
								operator: "=",
								left: args.handler.param,
								right: {
									type: "Identifier",
									name: "_" + args.handler.param.name,
								},
							},
						},
						args.handler.body,
					],
				},
			},
			finalizer: args.finalizer,
		},
	],
});