| 932 | |
| 933 | // each after those it reads, or undefined where one can't be written into a function |
| 934 | const unitsOf = ( |
| 935 | modules: Record<string, string>, |
| 936 | parsed: Map<string, SourceModule>, |
| 937 | kept: KeptCode |
| 938 | ): UnitModule[] | undefined => { |
| 939 | const units = new Map<string, UnitModule>() |
| 940 | for (const specifier in modules) { |
| 941 | const module = parsed.get(specifier)! |
| 942 | const declarations = module.program.body.filter( |
| 943 | statement => |
| 944 | statement.type === "VariableDeclaration" && |
| 945 | kept.statements.has(statement) |
| 946 | ) |
| 947 | if (declarations.length && isUnitModule(module)) |
| 948 | units.set(specifier, { specifier, module, declarations }) |
| 949 | } |
| 950 | // a module of values, e.g. a template, gains nothing in the function unless |
| 951 | // a unit there reads it |
| 952 | const read = new Set( |
| 953 | [...units.values()] |
| 954 | .filter(unit => unit.declarations.some(declaresUnit)) |
| 955 | .map(unit => unit.specifier) |
| 956 | ) |
| 957 | for (const specifier of read) { |
| 958 | for (const source of importsOf(units.get(specifier)!.module)) |
| 959 | if (units.has(source)) read.add(source) |
| 960 | } |
| 961 | for (const specifier of units.keys()) |
| 962 | if (!read.has(specifier)) units.delete(specifier) |
| 963 | // a unit reading a module other than a unit's can't read it in the function |
| 964 | for (let dropped = true; dropped; ) { |
| 965 | dropped = false |
| 966 | for (const unit of units.values()) { |
| 967 | if ( |
| 968 | importsOf(unit.module).some( |
| 969 | source => |
| 970 | source !== runtimeSource && |
| 971 | !source.startsWith(cellPrefix) && |
| 972 | !units.has(source) |
| 973 | ) |
| 974 | ) { |
| 975 | units.delete(unit.specifier) |
| 976 | dropped = true |
| 977 | } |
| 978 | } |
| 979 | } |
| 980 | const ordered: UnitModule[] = [] |
| 981 | const state = new Map<string, "visiting" | "done">() |
| 982 | const visit = (unit: UnitModule): boolean => { |
| 983 | if (state.get(unit.specifier) === "done") return true |
| 984 | if (state.get(unit.specifier) === "visiting") return false |
| 985 | state.set(unit.specifier, "visiting") |
| 986 | for (const source of importsOf(unit.module)) { |
| 987 | const read = units.get(source) |
| 988 | if (read && !visit(read)) return false |
| 989 | } |
| 990 | state.set(unit.specifier, "done") |
| 991 | ordered.push(unit) |