From c6bb4a979187e945a9d5d970f846b42743f2c9d8 Mon Sep 17 00:00:00 2001 From: civilian Date: Sat, 28 Nov 2026 02:29:48 +0900 Subject: [PATCH] Re-export used units (uses export) and project-wide uses (--project-uses) uses export (unleashed mode): a unit passes units of its interface uses clause on to the units that use it, so one name brings a whole set (C# global using, Rust pub use, TS export *). unit Lumi; interface uses export UI.Forms, UI.StdCtrls, Data.Window; - "export" right after "uses" covers the clause; before a later unit, that unit only. In the implementation uses clause it is error 03448. - A user sees the passed-on units as if they stood right before the re-exporting unit: its own names win, later units of the user win over both, and every passed-on unit stays reachable by its qualified name. Transitive. Naming a passed-on unit again is no duplicate. - The user records the passed-on units as used units (their crc goes into its ppu), so a change of their interface recompiles it. - No "unit not used" hint for a unit used only for what it passes on, nor for the passed-on units inside the re-exporting unit. - PPU: interface entry ibreexportunits (counted in the interface crc); PPU long version 49. --project-uses=A,B: every unit and program of the run uses A and B, as if they stood first in its uses clause (-Fa covers programs only). A unit that is one of them does not get itself; the units such a unit is built from do not get it either (they are loaded while its interface is not compiled yet; giving it to them would be a circular reference with -B). Naming them again is no duplicate. Wildcards (uses UI.*) were considered and left out: the hiding order would not be in the source, and adding a unit to a folder would change what an unchanged program means. qualification/compiler-uses-export: re-export, per-unit export, the implementation error, no unused hint, recompilation, project uses with and without -B. Documentation: unleashed/docs/uses-export.md. Co-Authored-By: Claude Opus 5.5 --- compiler/entfile.pas | 2 + compiler/fmodule.pas | 36 +++- compiler/fppu.pas | 52 +++++ compiler/globals.pas | 4 + compiler/msg/errore.msg | 4 + compiler/options.pas | 14 ++ compiler/pmodules.pas | 184 ++++++++++++++++-- compiler/ppu.pas | 5 +- qualification/compiler-uses-export/README.md | 18 ++ qualification/compiler-uses-export/ReexpA.pas | 28 +++ qualification/compiler-uses-export/ReexpB.pas | 19 ++ .../compiler-uses-export/ReexpBundle.pas | 20 ++ .../compiler-uses-export/ReexpImplBad.pas | 11 ++ .../compiler-uses-export/ReexpPartial.pas | 12 ++ .../compiler-uses-export/ReexpProj.pas | 20 ++ .../compiler-uses-export/ReexpUser.pas | 20 ++ .../compiler-uses-export/projuses_main.pas | 12 ++ .../compiler-uses-export/reexp_impl_bad.pas | 9 + .../compiler-uses-export/reexp_main.pas | 17 ++ .../compiler-uses-export/reexp_partial.pas | 14 ++ .../reexp_partial_bad.pas | 12 ++ .../compiler-uses-export/reexp_user_main.pas | 10 + .../compiler-uses-export/run_gate.py | 129 ++++++++++++ unleashed/docs/README.md | 4 + unleashed/docs/uses-export.md | 90 +++++++++ 25 files changed, 726 insertions(+), 20 deletions(-) create mode 100644 qualification/compiler-uses-export/README.md create mode 100644 qualification/compiler-uses-export/ReexpA.pas create mode 100644 qualification/compiler-uses-export/ReexpB.pas create mode 100644 qualification/compiler-uses-export/ReexpBundle.pas create mode 100644 qualification/compiler-uses-export/ReexpImplBad.pas create mode 100644 qualification/compiler-uses-export/ReexpPartial.pas create mode 100644 qualification/compiler-uses-export/ReexpProj.pas create mode 100644 qualification/compiler-uses-export/ReexpUser.pas create mode 100644 qualification/compiler-uses-export/projuses_main.pas create mode 100644 qualification/compiler-uses-export/reexp_impl_bad.pas create mode 100644 qualification/compiler-uses-export/reexp_main.pas create mode 100644 qualification/compiler-uses-export/reexp_partial.pas create mode 100644 qualification/compiler-uses-export/reexp_partial_bad.pas create mode 100644 qualification/compiler-uses-export/reexp_user_main.pas create mode 100644 qualification/compiler-uses-export/run_gate.py create mode 100644 unleashed/docs/uses-export.md diff --git a/compiler/entfile.pas b/compiler/entfile.pas index fb7e65a50..a7a8a95ce 100644 --- a/compiler/entfile.pas +++ b/compiler/entfile.pas @@ -127,6 +127,7 @@ interface ibmoduleoptions = 85; ibunitimportsyms = 86; iborderedsymbols = 87; + ibreexportunits = 88; ibmainname = 90; ibsymtableoptions = 91; @@ -524,6 +525,7 @@ function entry_name(nr : byte) : string; ibmoduleoptions: entry_name:='ibmoduleoptions'; ibunitimportsyms: entry_name:='ibunitimportsyms'; iborderedsymbols: entry_name:='iborderedsymbols'; + ibreexportunits: entry_name:='ibreexportunits'; ibmainname: entry_name:='ibmainname'; ibsymtableoptions: entry_name:='ibsymtableoptions'; diff --git a/compiler/fmodule.pas b/compiler/fmodule.pas index 7159b0b27..45e61d739 100644 --- a/compiler/fmodule.pas +++ b/compiler/fmodule.pas @@ -130,6 +130,15 @@ tused_unit = class(tlinkedlistitem) unitsym : tunitsym; aliases : TCmdStrList; { additional spellings of this dependency } dependent_added : boolean; + { `uses export X` in the interface: the units using this one see X's + interface too (connect_loaded_units) } + reexport : boolean; + { added by connect_loaded_units because a used unit re-exports it; + naming it in a uses clause as well is no duplicate } + via_reexport : boolean; + { added by --project-uses: naming it in the uses clause too is no + duplicate, and it is not the first explicit unit } + via_project : boolean; constructor create(_u : tmodule;intface,inuses:boolean;usym:tunitsym); destructor destroy; override; procedure check_hints; @@ -1705,6 +1714,28 @@ implementation procedure tmodule.allunitsused; var pu : tused_unit; + + { A unit that passes others on ("uses export") is used when a name of + one of them is: "uses Lumi" for TForm is no unused unit. } + function reexportused(m: tmodule; depth: longint): boolean; + var + rp : tused_unit; + begin + result:=false; + if depth>32 then + exit; + rp:=tused_unit(m.used_units.first); + while assigned(rp) do + begin + if rp.in_interface and rp.reexport and + (rp.u.moduleid0) or reexportused(rp.u,depth+1)) then + exit(true); + rp:=tused_unit(rp.next); + end; + end; + begin pu:=tused_unit(used_units.first); while assigned(pu) do @@ -1717,7 +1748,10 @@ implementation this is for units with an initialization/finalization } if (unitmap[pu.u.moduleid].refs=0) and pu.in_uses and - ((pu.u.moduleflags * [mf_init,mf_finalize])=[]) then + ((pu.u.moduleflags * [mf_init,mf_finalize])=[]) and + { passed on: used by the users of this unit } + not pu.reexport and + not reexportused(pu.u,0) then CGMessagePos2(pu.unitsym.fileinfo,sym_n_unit_not_used,pu.u.realmodulename^,realmodulename^); end; pu:=tused_unit(pu.next); diff --git a/compiler/fppu.pas b/compiler/fppu.pas index 4b690bcdb..c1a126fa2 100644 --- a/compiler/fppu.pas +++ b/compiler/fppu.pas @@ -121,6 +121,8 @@ tppumodule = class(tmodule) procedure freederefunitimportsyms; procedure writesourcefiles; procedure writeusedunit(intf:boolean); + procedure writereexportunits; + procedure readreexportunits; procedure writelinkcontainer(var p:tlinkcontainer;id:byte;strippath:boolean); procedure writederefmap; procedure writederefdata; @@ -1015,6 +1017,52 @@ implementation end; + { The interface units this unit passes on ("uses export"): their names, in + uses order. Part of the interface: it changes what the users of this + unit see, so it counts in the crc. Written only when there is one. } + procedure tppumodule.writereexportunits; + var + hp : tused_unit; + any : boolean; + begin + any:=false; + hp:=tused_unit(used_units.first); + while assigned(hp) do + begin + if hp.in_interface and hp.reexport then + begin + ppufile.putstring(hp.u.realmodulename^); + any:=true; + end; + hp:=tused_unit(hp.next); + end; + if any then + ppufile.writeentry(ibreexportunits); + end; + + + procedure tppumodule.readreexportunits; + var + hs : string; + hp : tused_unit; + begin + while not ppufile.endofentry do + begin + hs:=upper(ppufile.getstring); + hp:=tused_unit(used_units.first); + while assigned(hp) do + begin + if hp.u.modulename^=hs then + begin + hp.reexport:=true; + break; + end; + hp:=tused_unit(hp.next); + end; + end; + end; + + procedure tppumodule.writelinkcontainer(var p:tlinkcontainer;id:byte;strippath:boolean); var hcontainer : tlinkcontainer; @@ -1658,6 +1706,8 @@ implementation {$ENDIF} ibloadunit : readloadunit; + ibreexportunits : + readreexportunits; iblinkunitofiles : readlinkcontainer(LinkUnitOFiles); iblinkunitstaticlibs : @@ -1808,6 +1858,7 @@ implementation { write interface uses } writeusedunit(true); + writereexportunits; { write the objectfiles and libraries that come for this unit, preserve the containers because they are still needed to load @@ -1988,6 +2039,7 @@ implementation { the interface units affect the crc } writeusedunit(true); + writereexportunits; { deref data of interface that affect the crc } derefdata.reset; diff --git a/compiler/globals.pas b/compiler/globals.pas index 0b77bd44f..8b49f5ae7 100644 --- a/compiler/globals.pas +++ b/compiler/globals.pas @@ -400,6 +400,9 @@ tpendingstate = record { ordered explicit program/library unit prefix required by --required-first-unit } requiredfirstunit : TIDString; + { --project-uses=A,B: units every unit and program uses, as the first + of its uses clause (a project-wide uses) } + projectuses : ansistring; // lowercased glob patterns from `--rttiexpose=` CLI flags; // per-unit patterns from `{$rttiexpose}` directive live on tmodule cli_rtti_expose_patterns : TCmdStrList; @@ -1870,6 +1873,7 @@ tinitdoneentry=record namespacelist:=TCmdStrList.Create; pinnedunitfiles:=TLinkStrMap.Create; requiredfirstunit:=''; + projectuses:=''; cli_rtti_expose_patterns:=TCmdStrList.Create; premodule_namespacelist:=TCmdStrList.Create; current_namespacelist:=Nil; diff --git a/compiler/msg/errore.msg b/compiler/msg/errore.msg index 5a58a0b6a..c20f1f019 100644 --- a/compiler/msg/errore.msg +++ b/compiler/msg/errore.msg @@ -1844,6 +1844,10 @@ parser_e_align_bitalign_exclusive=03406_E_"align" and "bitalign" are mutually ex parser_e_weak_threadlocal_property=03447_E_A weak field inside a class threadvar requires a property accessor method for RTTI % The address of the field must be obtained for the calling thread. +parser_e_reexport_uses_in_implementation=03448_E_A used unit can be re-exported ("export $1") only in the interface uses clause +% "uses export" passes the used units on to the units that use this one, which see +% only its interface. In the implementation uses clause there is nothing to pass on. + parser_e_unsupported_weak_declaration=03446_E_[Weak] requires an instance field of a class or a COM interface type % Weak storage is available for instance fields. Class references keep desktop non-ARC semantics. diff --git a/compiler/options.pas b/compiler/options.pas index 40ba64f14..4c3a6416b 100644 --- a/compiler/options.pas +++ b/compiler/options.pas @@ -1675,6 +1675,20 @@ procedure TOption.interpret_option(const opt:TCmdStr;ispara:boolean); end; exit; end; + if opt.StartsWith('--project-uses=') then begin + { units every unit and program of the project uses (lumi.json "uses") } + more:=Copy(opt,Length('--project-uses=')+1); + if (more='') or (more[1]=',') or (more[Length(more)]=',') or (Pos(',,',more)>0) then + IllegalPara(opt); + { the options are read more than once: add each unit once } + if Pos(','+Upper(more)+',',','+Upper(projectuses)+',')=0 then + begin + if projectuses<>'' then + projectuses:=projectuses+','; + projectuses:=projectuses+more; + end; + exit; + end; if opt.StartsWith('--required-first-unit=') then begin more:=Upper(Copy(opt,Length('--required-first-unit=')+1)); if (more='') or (more[1]=',') or (more[Length(more)]=',') or diff --git a/compiler/pmodules.pas b/compiler/pmodules.pas index 1c4bb1cc7..789424180 100644 --- a/compiler/pmodules.pas +++ b/compiler/pmodules.pas @@ -723,17 +723,48 @@ current_module.rtti_directive.options:=class_tobject.rtti.options; filepos : tfileposinfo; isnew, aliasuse, - implicitproductunit : boolean; + implicitproductunit, + exportall, + firstitem, + reexportitem, + viareexport : boolean; aliasitem: TCmdStrListItem; begin consume(_USES); + { "uses export A, B;": every unit of the clause is passed on; + "uses A, export B;": that one only (unleashed). "export" is no + reserved word: followed by an identifier it is the marker, else + it is a unit of that name. } + exportall:=false; + firstitem:=true; repeat s:=current_scanner.pattern; sorg:=current_scanner.orgpattern; filepos:=current_tokenpos; - consume(_ID); + reexportitem:=exportall; + if (m_unleashed in current_settings.modeswitches) and + (current_scanner.token=_ID) and (current_scanner.idtoken=_EXPORT) then + begin + consume(_ID); + if current_scanner.token=_ID then + begin + reexportitem:=true; + { right after USES: the whole clause } + if firstitem then + exportall:=true; + if not curr.in_interface then + Message1(parser_e_reexport_uses_in_implementation,current_scanner.orgpattern); + s:=current_scanner.pattern; + sorg:=current_scanner.orgpattern; + filepos:=current_tokenpos; + consume(_ID); + end; + end + else + consume(_ID); + firstitem:=false; while current_scanner.token=_POINT do begin consume(_POINT); @@ -827,9 +858,11 @@ current_module.rtti_directive.options:=class_tobject.rtti.options; insert_unit_alias(curr,hp2,sorg); end; end; - if assigned(pu) and not (implicitproductunit or aliasuse) then + { already visible: a unit used before re-exports it } + viareexport:=assigned(pu) and (pu.via_reexport or pu.via_project); + if assigned(pu) and not (implicitproductunit or aliasuse or viareexport) then Message1(sym_e_duplicate_id,s); - if not (implicitproductunit or aliasuse) then + if not (implicitproductunit or aliasuse or viareexport) then begin { Create unitsym, we need to use the name as specified, we can not use the modulename because that can be different @@ -837,7 +870,8 @@ current_module.rtti_directive.options:=class_tobject.rtti.options; current_tokenpos:=filepos; unitsym:=cunitsym.create(sorg,nil); { the current module uses the unit hp2 } - curr.addusedunit(hp2,true,unitsym); + pu:=curr.addusedunit(hp2,true,unitsym); + pu.reexport:=reexportitem and curr.in_interface; end; end else @@ -852,6 +886,48 @@ current_module.rtti_directive.options:=class_tobject.rtti.options; until false; end; + { --project-uses=Lumi,...: the units every unit and program of the + project uses, registered before its own uses clause is read, as if they + stood first in it (its own units win). A unit that is one of them does + not get itself. True if any was added. } + function addprojectuses(curr: tmodule): boolean; + var + hs,s : ansistring; + hp : tmodule; + pu : tused_unit; + isnew : boolean; + begin + result:=false; + hs:=projectuses; + repeat + s:=GetToken(hs,','); + if s='' then + break; + if Upper(s)=curr.modulename^ then + continue; + { A project unit whose interface is not compiled yet is what is + loading curr: curr is one of its dependencies, and giving it the + project unit would be a circular reference (with -B, the units + the project unit uses are compiled in the same run). Looked up + before registerunit, which would report the cycle. } + hp:=tmodule(loaded_units.first); + while assigned(hp) and (hp.modulename^<>Upper(s)) do + hp:=tmodule(hp.next); + if assigned(hp) and + (hp.state in [ms_registered,ms_load,ms_compile,ms_compiling_wait,ms_compiling_waitintf]) then + continue; + hp:=registerunit(curr,s,'',isnew); + if isnew then + usedunits.concat(tused_unit.create(hp,curr.in_interface,true,nil)); + if assigned(curr.findusedunit(hp)) then + continue; + pu:=curr.addusedunit(hp,true,cunitsym.create(s,nil)); + pu.via_project:=true; + result:=true; + until false; + end; + + procedure checkrequiredfirstunit(curr: tmodule); var pu : tused_unit; @@ -870,7 +946,7 @@ current_module.rtti_directive.options:=class_tobject.rtti.options; if expected='' then break; inc(index); - while assigned(pu) and not pu.in_uses do + while assigned(pu) and (not pu.in_uses or pu.via_project) do pu:=tused_unit(pu.next); if assigned(pu) then actual:=pu.u.modulename^ @@ -978,6 +1054,48 @@ current_module.rtti_directive.options:=class_tobject.rtti.options; aliasitem: TCmdStrListItem; unitsymtable: tabstractunitsymtable; + procedure pushsymtable(m: tmodule); + begin + if assigned(preservest) then + symtablestack.pushafter(m.globalsymtable,preservest) + else + symtablestack.push(m.globalsymtable); + if (m_mac in current_settings.modeswitches) and + assigned(m.globalmacrosymtable) then + macrosymtablestack.push(m.globalmacrosymtable); + end; + + { The units m passes on ("uses export"), and the ones they pass on, + become visible here as if they stood in the uses clause right + before m: m's own names win. They are used units of _module, so its + ppu records their crc and a change of their interface recompiles it; + a unit symbol makes the qualified names (UI.Forms.TForm) work. } + procedure connectreexports(m: tmodule); + var + rp,np : tused_unit; + begin + rp:=tused_unit(m.used_units.first); + while assigned(rp) do + begin + if rp.in_interface and rp.reexport and + (rp.u<>_module) and + assigned(rp.u.globalsymtable) and + not assigned(_module.findusedunit(rp.u)) then + begin + connectreexports(rp.u); + np:=_module.addusedunit(rp.u,false,nil); + np.via_reexport:=true; + np.checksum:=rp.u.crc; + np.interface_checksum:=rp.u.interface_crc; + np.indirect_checksum:=rp.u.indirect_crc; + rp.u.adddependency(_module,_module.in_interface); + insert_unit_alias(_module,rp.u,rp.u.realmodulename^); + pushsymtable(rp.u); + end; + rp:=tused_unit(rp.next); + end; + end; + begin // writeln(_module.get_modulename,': Connecting units'); pu:=tused_unit(_module.used_units.first); @@ -1057,15 +1175,11 @@ current_module.rtti_directive.options:=class_tobject.rtti.options; aliasitem:=TCmdStrListItem(aliasitem.next); end; end; + { what it re-exports first, so that its own names win } + connectreexports(pu.u); { add to symtable stack } // Writeln('Adding used unit symtable ',pu.u.globalsymtable.name^,' (',pu.u.globalsymtable.DefList.Count, ' defs) to stack'); - if assigned(preservest) then - symtablestack.pushafter(pu.u.globalsymtable,preservest) - else - symtablestack.push(pu.u.globalsymtable); - if (m_mac in current_settings.modeswitches) and - assigned(pu.u.globalmacrosymtable) then - macrosymtablestack.push(pu.u.globalmacrosymtable); + pushsymtable(pu.u); end; pu:=tused_unit(pu.next); @@ -1742,7 +1856,8 @@ tfinishstate=record unitname : ansistring; unitname8 : string[8]; feature : tfeature; - load_ok : boolean; + load_ok, + projectused : boolean; begin result:=true; @@ -1855,6 +1970,18 @@ tfinishstate=record if not(cs_compilesystem in current_settings.moduleswitches) then load_ok:=loaddefaultunits(curr) and load_ok; + { the project's own uses come first } + projectused:=false; + if not(cs_compilesystem in current_settings.moduleswitches) and + (projectuses<>'') then + begin + if Assigned(curr) then + curr.Loadlocalnamespacelist + else + current_namespacelist:=Nil; + projectused:=addprojectuses(curr); + end; + { insert qualifier for the system unit (allows system.writeln) } if not(cs_compilesystem in current_settings.moduleswitches) and (current_scanner.token=_USES) then @@ -1876,7 +2003,18 @@ tfinishstate=record curr.consume_semicolon_after_uses:=true; end else - curr.consume_semicolon_after_uses:=false; + begin + curr.consume_semicolon_after_uses:=false; + if projectused then + begin + load_ok:=loadunits(curr,true) and load_ok and not tmodule.ctask_fast_backtrack; + if curr.state in [ms_compiled,ms_processed] then + begin + Message1(parser_u_already_compiled,curr.realmodulename^); + exit; + end; + end; + end; { move the global symtable from the temporary local to global } current_module.globalsymtable:=current_module.localsymtable; @@ -3338,7 +3476,8 @@ TProgramParam = record sc : TProgramParamArray; i : Longint; feature : tfeature; - load_ok : boolean; + load_ok, + projectused : boolean; begin result:=true; @@ -3454,6 +3593,17 @@ TProgramParam = record end; end; + { the project's own uses come first } + projectused:=false; + if projectuses<>'' then + begin + if Assigned(curr) then + curr.Loadlocalnamespacelist + else + current_namespacelist:=Nil; + projectused:=addprojectuses(curr); + end; + { Load the units used by the program we compile. } if current_scanner.token=_USES then begin @@ -3470,7 +3620,7 @@ TProgramParam = record else begin curr.consume_semicolon_after_uses:=false; checkrequiredfirstunit(curr); - if productruntimeprefixenabled then + if productruntimeprefixenabled or projectused then load_ok:=loadunits(curr,false) and load_ok; if tmodule.ctask_fast_backtrack then load_ok:=false; { some used units are not fully compiled } diff --git a/compiler/ppu.pas b/compiler/ppu.pas index 53bca8516..e707e0de7 100644 --- a/compiler/ppu.pas +++ b/compiler/ppu.pas @@ -51,8 +51,9 @@ interface { 44: tai_align_abstract serializes fixedfill and padbytes; 45: tai_align_abstract additionally serializes its placement purpose; 47: unit symbols retain their physical module binding; - 48: generic runtime types use shared semantic linker identities. } - CurrentPPULongVersion = 48; + 48: generic runtime types use shared semantic linker identities; + 49: ibreexportunits, the interface units passed on by "uses export". } + CurrentPPULongVersion = 49; { unit flags } uf_big_endian = $000004; diff --git a/qualification/compiler-uses-export/README.md b/qualification/compiler-uses-export/README.md new file mode 100644 index 000000000..c7a1f8e63 --- /dev/null +++ b/qualification/compiler-uses-export/README.md @@ -0,0 +1,18 @@ +# `uses export` and `--project-uses` + +```text +python qualification/compiler-uses-export/run_gate.py \ + --compiler --config --output +``` + +See `unleashed/docs/uses-export.md`. + +| Case | What it checks | +|---|---| +| `uses-export` | `uses export ReexpA, ReexpB;` in a unit's interface: a program using that unit sees ReexpA and ReexpB, the unit's own names win (`Who`), a passed-on unit is reachable by its qualified name (`ReexpA.Who`) | +| `uses-export-item`, `uses-export-item-only` | `uses ReexpA, export ReexpB;`: only the marked unit is passed on; a type of the other one is unknown to the users | +| `uses-export-implementation` | `export` in the implementation uses clause is an error (03448) | +| `uses-export-no-unused-hint` | A unit used only for the names it passes on gets no "unit not used" hint (`-vh`) | +| `uses-export-recompile` | A unit that names only the bundle is compiled again when the interface of a passed-on unit changes | +| `project-uses` | `--project-uses=ReexpBundle`: a unit without a uses clause and the program get the unit; the program naming it again is no duplicate | +| `project-uses-build-all` | The same with `-B`: the units the bundle is built from are compiled in the same run and do not get the bundle (no circular reference) | \ No newline at end of file diff --git a/qualification/compiler-uses-export/ReexpA.pas b/qualification/compiler-uses-export/ReexpA.pas new file mode 100644 index 000000000..8b3897d66 --- /dev/null +++ b/qualification/compiler-uses-export/ReexpA.pas @@ -0,0 +1,28 @@ +unit ReexpA; + +{ re-exported by ReexpBundle } +{$mode unleashed} + +interface + +type + TReexpA = record + X: Integer; + end; + +function Who: string; +function OnlyA: string; + +implementation + +function Who: string; +begin + Result := 'A'; +end; + +function OnlyA: string; +begin + Result := 'onlyA'; +end; + +end. \ No newline at end of file diff --git a/qualification/compiler-uses-export/ReexpB.pas b/qualification/compiler-uses-export/ReexpB.pas new file mode 100644 index 000000000..a27774fd2 --- /dev/null +++ b/qualification/compiler-uses-export/ReexpB.pas @@ -0,0 +1,19 @@ +unit ReexpB; + +{$mode unleashed} + +interface + +type + TReexpB = class + function Name: string; + end; + +implementation + +function TReexpB.Name: string; +begin + Result := 'B'; +end; + +end. \ No newline at end of file diff --git a/qualification/compiler-uses-export/ReexpBundle.pas b/qualification/compiler-uses-export/ReexpBundle.pas new file mode 100644 index 000000000..2eedad50f --- /dev/null +++ b/qualification/compiler-uses-export/ReexpBundle.pas @@ -0,0 +1,20 @@ +unit ReexpBundle; + +{ "uses export": the units using this one see ReexpA and ReexpB as well. + Its own Who wins over ReexpA.Who. } +{$mode unleashed} + +interface + +uses export ReexpA, ReexpB; + +function Who: string; + +implementation + +function Who: string; +begin + Result := 'bundle'; +end; + +end. \ No newline at end of file diff --git a/qualification/compiler-uses-export/ReexpImplBad.pas b/qualification/compiler-uses-export/ReexpImplBad.pas new file mode 100644 index 000000000..392f656be --- /dev/null +++ b/qualification/compiler-uses-export/ReexpImplBad.pas @@ -0,0 +1,11 @@ +unit ReexpImplBad; + +{$mode unleashed} + +interface + +implementation + +uses export ReexpA; + +end. \ No newline at end of file diff --git a/qualification/compiler-uses-export/ReexpPartial.pas b/qualification/compiler-uses-export/ReexpPartial.pas new file mode 100644 index 000000000..d14965f13 --- /dev/null +++ b/qualification/compiler-uses-export/ReexpPartial.pas @@ -0,0 +1,12 @@ +unit ReexpPartial; + +{ only the unit marked "export" is passed on } +{$mode unleashed} + +interface + +uses ReexpA, export ReexpB; + +implementation + +end. \ No newline at end of file diff --git a/qualification/compiler-uses-export/ReexpProj.pas b/qualification/compiler-uses-export/ReexpProj.pas new file mode 100644 index 000000000..0ce1ef550 --- /dev/null +++ b/qualification/compiler-uses-export/ReexpProj.pas @@ -0,0 +1,20 @@ +unit ReexpProj; + +{ no uses clause: --project-uses=ReexpBundle gives it the bundle } +{$mode unleashed} + +interface + +function Q: string; + +implementation + +function Q: string; +var + A: TReexpA; +begin + A.X := 1; + Result := Who + OnlyA + Chr(Ord('0') + A.X); +end; + +end. \ No newline at end of file diff --git a/qualification/compiler-uses-export/ReexpUser.pas b/qualification/compiler-uses-export/ReexpUser.pas new file mode 100644 index 000000000..afc15845c --- /dev/null +++ b/qualification/compiler-uses-export/ReexpUser.pas @@ -0,0 +1,20 @@ +unit ReexpUser; + +{ uses the bundle only; its interface depends on ReexpA through it } +{$mode unleashed} + +interface + +uses + ReexpBundle; + +function Make: TReexpA; + +implementation + +function Make: TReexpA; +begin + Result.X := 3; +end; + +end. diff --git a/qualification/compiler-uses-export/projuses_main.pas b/qualification/compiler-uses-export/projuses_main.pas new file mode 100644 index 000000000..580127d8a --- /dev/null +++ b/qualification/compiler-uses-export/projuses_main.pas @@ -0,0 +1,12 @@ +program projuses_main; + +{ --project-uses=ReexpBundle: every unit and the program use it; naming it + here as well is no duplicate } +{$mode unleashed} + +uses + ReexpBundle, ReexpProj; + +begin + WriteLn(Q, ' ', Who); +end. \ No newline at end of file diff --git a/qualification/compiler-uses-export/reexp_impl_bad.pas b/qualification/compiler-uses-export/reexp_impl_bad.pas new file mode 100644 index 000000000..1aeb1e824 --- /dev/null +++ b/qualification/compiler-uses-export/reexp_impl_bad.pas @@ -0,0 +1,9 @@ +program reexp_impl_bad; + +{$mode unleashed} + +uses + ReexpImplBad; + +begin +end. \ No newline at end of file diff --git a/qualification/compiler-uses-export/reexp_main.pas b/qualification/compiler-uses-export/reexp_main.pas new file mode 100644 index 000000000..80e4b7338 --- /dev/null +++ b/qualification/compiler-uses-export/reexp_main.pas @@ -0,0 +1,17 @@ +program reexp_main; + +{$mode unleashed} + +uses + ReexpBundle; + +var + A: TReexpA; + B: TReexpB; +begin + A.X := 7; + B := TReexpB.Create; + { the bundle's own Who wins; the re-exported unit is there by its qualified name } + WriteLn(Who, ' ', ReexpA.Who, ' ', OnlyA, ' ', A.X, ' ', B.Name); + B.Free; +end. \ No newline at end of file diff --git a/qualification/compiler-uses-export/reexp_partial.pas b/qualification/compiler-uses-export/reexp_partial.pas new file mode 100644 index 000000000..d0f12f762 --- /dev/null +++ b/qualification/compiler-uses-export/reexp_partial.pas @@ -0,0 +1,14 @@ +program reexp_partial; + +{$mode unleashed} + +uses + ReexpPartial; + +var + B: TReexpB; +begin + B := TReexpB.Create; + WriteLn(B.Name); + B.Free; +end. \ No newline at end of file diff --git a/qualification/compiler-uses-export/reexp_partial_bad.pas b/qualification/compiler-uses-export/reexp_partial_bad.pas new file mode 100644 index 000000000..085dc12d9 --- /dev/null +++ b/qualification/compiler-uses-export/reexp_partial_bad.pas @@ -0,0 +1,12 @@ +program reexp_partial_bad; + +{ ReexpPartial uses ReexpA without passing it on } +{$mode unleashed} + +uses + ReexpPartial; + +var + A: TReexpA; +begin +end. \ No newline at end of file diff --git a/qualification/compiler-uses-export/reexp_user_main.pas b/qualification/compiler-uses-export/reexp_user_main.pas new file mode 100644 index 000000000..b97737cfc --- /dev/null +++ b/qualification/compiler-uses-export/reexp_user_main.pas @@ -0,0 +1,10 @@ +program reexp_user_main; + +{$mode unleashed} + +uses + ReexpUser; + +begin + WriteLn(Make.X); +end. diff --git a/qualification/compiler-uses-export/run_gate.py b/qualification/compiler-uses-export/run_gate.py new file mode 100644 index 000000000..a75d39562 --- /dev/null +++ b/qualification/compiler-uses-export/run_gate.py @@ -0,0 +1,129 @@ +"""Check "uses export" (re-exported units) and --project-uses (project-wide +uses): what the users of a unit see, which name wins, the errors, and the +recompilation of a user when a passed-on unit changes.""" + +import argparse +import os +import re +from pathlib import Path +import shutil +import subprocess +import time + +HERE = Path(__file__).resolve().parent +FLAGS = 0x08000000 if os.name == 'nt' else 0 + +# id, program source, extra compiler options, expected output lines - or, as +# a string 'error: ', a compile error whose message contains +CASES = [ + # A unit passes the units of its interface uses clause on. + ('uses-export', 'reexp_main.pas', [], + ['bundle A onlyA 7 B']), + # "export" before a later unit passes on that unit only. + ('uses-export-item', 'reexp_partial.pas', [], + ['B']), + ('uses-export-item-only', 'reexp_partial_bad.pas', [], + 'error: Identifier not found "TReexpA"'), + # Nothing to pass on from the implementation uses clause. + ('uses-export-implementation', 'reexp_impl_bad.pas', [], + 'error: A used unit can be re-exported ("export ReexpA") only in the interface uses clause'), + # A unit used only for names it passes on (ReexpPartial declares none) + # is no unused unit, and neither is a unit passed on (ReexpB in + # ReexpPartial). ReexpA, used there and not passed on, is. + ('uses-export-no-unused-hint', 'reexp_partial.pas', ['-vh'], + ['B']), + # --project-uses: a uses clause for every unit and program. + ('project-uses', 'projuses_main.pas', ['--project-uses=ReexpBundle'], + ['bundleonlyA1 bundle']), + # With -B the units the project unit is built from are compiled in the + # same run; they do not get it (that would be a circular reference). + ('project-uses-build-all', 'projuses_main.pas', ['-B', '--project-uses=ReexpBundle'], + ['bundleonlyA1 bundle']), +] + + +def compile_case(compiler, config, work, options, source): + command = [str(compiler), '-n', '@' + str(config), '-Munleashed', *options, + '-FU' + str(work), '-FE' + str(work), '-Fu' + str(work), str(work / source)] + compiled = subprocess.run(command, cwd=work, capture_output=True, timeout=120, creationflags=FLAGS) + log = (compiled.stdout + compiled.stderr).decode(errors='replace') + return compiled.returncode, log + + +def run_exe(work, source): + exe = (work / Path(source).stem).with_suffix('.exe' if os.name == 'nt' else '') + ran = subprocess.run([str(exe)], cwd=work, capture_output=True, timeout=60, creationflags=FLAGS) + return ran.returncode, [l.strip() for l in ran.stdout.decode(errors='replace').splitlines() if l.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--compiler', type=Path, required=True) + parser.add_argument('--config', type=Path, required=True) + parser.add_argument('--output', type=Path, required=True) + args = parser.parse_args() + output = args.output.resolve() + output.mkdir(parents=True, exist_ok=False) + compiler, config = args.compiler.resolve(), args.config.resolve() + failures = [] + + for case_id, source, options, expected in CASES: + work = output / case_id + work.mkdir() + for unit in HERE.glob('*.pas'): + shutil.copy2(unit, work / unit.name) + code, log = compile_case(compiler, config, work, options, source) + (work / 'compile.log').write_text(log, encoding='utf-8') + if isinstance(expected, str): + wanted = expected[len('error: '):] + if code == 0: + failures.append(f'{case_id}: compiles, expected the error {wanted!r}') + elif wanted not in log: + failures.append(f'{case_id}: fails, but not with {wanted!r} (see {work / "compile.log"})') + else: + print(f'PASS {case_id}') + continue + if code != 0: + failures.append(f'{case_id}: does not compile (see {work / "compile.log"})') + continue + if '-vh' in options and re.search(r'Unit "(ReexpPartial|ReexpB)" not used', log): + failures.append(f'{case_id}: an unused-unit hint for a unit used through what it passes on') + continue + exit_code, got = run_exe(work, source) + if exit_code != 0 or got != expected: + failures.append(f'{case_id}: exit {exit_code}, output {got}, expected {expected}') + else: + print(f'PASS {case_id}') + + # A user of the bundle records the passed-on units: when the interface of + # one changes, the user is compiled again although it names the bundle only. + case_id = 'uses-export-recompile' + work = output / case_id + work.mkdir() + for unit in HERE.glob('*.pas'): + shutil.copy2(unit, work / unit.name) + code, log = compile_case(compiler, config, work, [], 'reexp_user_main.pas') + user_ppu = work / 'reexpuser.ppu' + if code != 0 or not user_ppu.exists(): + failures.append(f'{case_id}: does not compile ({log[-500:]})') + else: + before = user_ppu.stat().st_mtime_ns + time.sleep(1.1) + text = (work / 'ReexpA.pas').read_text(encoding='utf-8') + (work / 'ReexpA.pas').write_text(text.replace('X: Integer;', 'X: Integer;\n Y: Integer;'), encoding='utf-8') + code, log = compile_case(compiler, config, work, [], 'reexp_user_main.pas') + if code != 0: + failures.append(f'{case_id}: does not compile after the change ({log[-500:]})') + elif user_ppu.stat().st_mtime_ns == before: + failures.append(f'{case_id}: the user of the bundle was not compiled again') + else: + print(f'PASS {case_id}') + + print(f'USES_EXPORT_GATE {"OK" if not failures else "FAIL"} cases={len(CASES) + 1} failures={len(failures)}') + for failure in failures: + print('FAIL', failure) + raise SystemExit(1 if failures else 0) + + +if __name__ == '__main__': + main() diff --git a/unleashed/docs/README.md b/unleashed/docs/README.md index 82bc7bf0e..5ed62cbdd 100644 --- a/unleashed/docs/README.md +++ b/unleashed/docs/README.md @@ -108,6 +108,10 @@ Declare variables at the point of first use, with type inference (`var x := expr `f(var x)` at an `out`-argument position declares a fresh variable typed from the parameter and scoped to the enclosing block; `f(_)` discards the output. No more pre-declaring a throwaway local for every `Try*` routine. Accepted only at an `out` parameter, resolved after overload selection, and a declared identifier `_` always wins over the discard meaning, so existing code is unaffected. Modeswitch `outvar`. +### [Re-exporting Units](uses-export.md) + +`uses export A, B;` in a unit's interface passes A and B on to the units that use it: one name in a uses clause brings a whole set, the unit's own names win, the passed-on units stay reachable by their qualified names, and a change in their interface recompiles the users. `export` before a later unit passes on that one only. `--project-uses=A,B` gives every unit and program of a project the same uses. + ### [Statement Expressions](statement-expressions.md) `if`, `case`, and `try` as expressions that yield a value, computed where it is consumed. Only the taken branch is evaluated, numeric branches widen to a common type, and `try X except 'fallback'` turns an exception into a value. Each branch is a single expression - value-less statements (`raise`, `exit`) are rejected. Modeswitch `statementexpressions`. diff --git a/unleashed/docs/uses-export.md b/unleashed/docs/uses-export.md new file mode 100644 index 000000000..fc30a772e --- /dev/null +++ b/unleashed/docs/uses-export.md @@ -0,0 +1,90 @@ +# Re-exporting Units - `uses export`, `--project-uses` + +A unit can pass the units it uses on to the units that use it, so one name in +a uses clause brings a whole set (C# `global using`, Rust `pub use`, +TypeScript `export * from`). And a project can give every one of its units +the same uses without writing it in each file. + +Available in `{$mode unleashed}` (`-Munleashed`); elsewhere `export` before a +unit name stays a syntax error. + +## `uses export` + +```pascal +unit Lumi; + +interface + +uses export UI.Forms, UI.StdCtrls, UI.Grids, Data.Window; + +end. +``` + +```pascal +program Orders; + +uses + Lumi; { TForm, TButton, TGrid, TDataWindow are all visible } +``` + +- `export` right after `uses` passes on every unit of the clause. +- `export` before a later unit passes on that unit only: + `uses SysUtils, export UI.Forms;` keeps SysUtils private. +- Only the interface uses clause can re-export; `export` in the + implementation uses clause is an error (`03448`): its units are invisible to + the users of the unit anyway. +- Re-export is transitive: a unit passed on that itself re-exports passes its + units on as well. + +### Which name wins + +The passed-on units are visible as if they stood in the user's uses clause +right before the re-exporting unit. So: + +- the re-exporting unit's own declarations win over the units it passes on + (`Lumi.Who` hides `UI.Forms.Who`); +- units the user names after it win over both, as with any uses clause; +- every passed-on unit is also there by its qualified name + (`UI.Forms.TForm`), even when a closer name hides the short one. + +Naming a passed-on unit again in a later uses clause (for instance the +implementation uses clause of the user) is no duplicate. + +### Recompilation + +A user of the re-exporting unit records the passed-on units as its own +dependencies (their checksums go into its `.ppu`): when the interface of a +passed-on unit changes, the user is compiled again, even though it names +only the re-exporting unit. + +### Why not wildcards + +`uses UI.*` was considered and left out: which of the matching units hides +which is not defined by the source, and adding a unit to the folder changes +what an unchanged program means. `uses export` names every unit once, in one +place, and the order is the order written. + +## `--project-uses` + +```text +ppcx64 --project-uses=Lumi,AppCommon ... +``` + +Every unit and program compiled in the run uses the listed units, as if they +stood first in its uses clause (its own units win). `-Fa` does the same for +programs only. + +- A unit that is one of them does not get itself. +- The units a project unit is built from do not get it either: a unit is + skipped while the project unit that loads it has no compiled interface yet + (with `-B`, the project unit's dependencies are compiled in the same run; + giving them the project unit would be a circular reference). +- Naming a project unit in a uses clause as well is no duplicate. + +The Lumi build tool passes the `"uses"` list of `lumi.json` here. + +## PPU format + +The interface part of a `.ppu` gets an `ibreexportunits` entry (the names of +the passed-on units) when the unit re-exports anything; it counts in the +interface checksum. PPU long version 49.