TeX typesets material a paragraph at a time (at least for the main vertical list), and as a result by the time the space on the last page is known most of the typesetting is already done. That means that a multi-pass approach is the only way to make the adjustments required. However, it will not be a simple as scaling the font size and/or margins for a second pass, as the line-breaking in a second run will be different, and this may alter the total number of lines typeset.
There are also some wider concerns. First, what algorithm would be used to decide on what changes to make. If both font size and margins can change, there needs to be a decision on which one to go for. There would also need to be some setting for how much change is acceptable.
That takes me on to the biggest worry of all here, and one which is not programmatic at all. (La)TeX is a typesetting system, and typesetting is all about the balance between text and the rest of the page. Read something like The Elements of Typographic Style by Bringhurst to see how complicated this is. Arbitrary changes of page layout are really well outside of the scope of good-quality typesetting. Now, not every LaTeX user cares about typesetting, but the TeX engine itself was designed to address the typesetting challenge. So it is not surprising that human input on this type of issue is required. You might also want to take a look at Squeezing scientific paper to fit within page limits.
With all of that said, I can imagine how one might program this. On the first pass, you'd typeset at 'natural' size, then save the position of the last item on the last page along with the total pages. For the second run, you'd then need decide one whether to make the material larger or smaller, which of course would require a set of thresholds for this. Within this, there would need to be a window of 'ideal' size (i.e. I think that some variation on the number of lines on the last page would be needed). Based on the amount of stretch/shrink, you'd then set font size and margins and do the typesetting. You're then looking at an iterative process, storing each set of trial values in the .aux
file and doing typesetting runs until the page looks 'right'. That would be handled with a log message, I guess.
savepos
module ofzref
package may help.