syntax error at or near TO (ROLLBACK TO SAVEPOINT)
You cannot use transaction management statements in PostgreSQL functions.

Limited support for that was added in procedures, introduced in v11.

But you can (implicitly) use savepoints by using an EXCEPTION clause in a block.

So instead of

LOOP
   SAVEPOINT a;

   /* something */

   IF /* something else */ THEN
      ROLLBACK TO SAVEPOINT a;
      /* still more */
   END IF;
END LOOP;


you should use

LOOP
   BEGIN
      /* something */

      IF /* something else */ THEN
         RAISE EXCEPTION 'catchme';
      END IF;
   EXCEPTION
      WHEN raise_exception THEN
         /* still more */
   END;
END LOOP;