The default parsetree mapper rebuilt every node, list, option and located name, so the built-in PPX and the JSX transform copied the whole tree of every file. Now a node whose parts all come back physically unchanged is returned as is. Parts are mapped in the same order as before, which a trace of every mapper call over the 3038 .res/.resi files in the repository confirms. The PPX overrides for functions, let bindings and structures, and the JSX structure and signature mappers, share the same way.
Parsing with the built-in PPX (bsc -bs-ast) on 77 Belt and tests/tests files allocates 8.9% less (2.1% to 12.2% per file), and 16.0% less with -bs-jsx 4. Whole compiles of 56 of them allocate 1.4% less. The JS output and diagnostics are byte-identical; the .ast files hold equal trees, but 37 of 77 differ in bytes, since Marshal records the new sharing.
Ast_mapper's map_list and Ext_list's map_sharing recursed once per element, so the built-in PPX needed a stack frame per element of a long array, record type or structure, where master's List.map needed none. Now they recurse over the first 1000 elements only, which allocates nothing for an unchanged list, and continue in a loop after that. The loop keeps the result up to the last change in a reversed list and shares the unchanged rest. Elements are still mapped once each, in list order.
map_snd_sharing gets the same fallback, and the JSX transform's concat_map_sharing moves to Ext_list with it. The unit tests check the result, the visiting order and the sharing around the switch from recursion to the loop.
Parsing with the built-in PPX now needs about 4k words of stack for an array of 50,000 elements and 8k for a record type of 20,000 fields, where it needed 263k and 66k before (master: under 1k). A 1-million-element array compiles as fast as before, with master's peak memory. JS output and diagnostics are byte-identical on 77 benchmark files, and allocation is unchanged (+0.0004%).
The depth counter added to every sharing map costs a few instructions per element. That is negligible in the built-in PPX but not in the Lambda and JS passes, which call Ext_list.map_sharing all the time: the CI benchmarks measured +0.12% instructions in total and +1.49% for stress/RefsInLoop.
These two maps have recursed once per element since long before this pull request, so they go back to master's code. The fallback stays where this pull request made lists deeper than on master: Ast_mapper's map_list and the JSX transform's concat_map_sharing, which replaced List.map and List.concat_map. Parsing with the built-in PPX still needs about 4k words of stack for a 50,000-element array and 8k for a 20,000-field record type. JS output and diagnostics are byte-identical on 77 benchmark files.