@@ -39,6 +39,8 @@ final class CodegenFile {
3939 private ?Map < string , Vector < string >> $rekey = null ;
4040 private bool $createOnly = false ;
4141 private ?ICodegenFormatter $formatter ;
42+ private ?string $fileNamespace ;
43+ private Map < string , ?string > $useNamespaces = Map {};
4244
4345 public function __construct (
4446 private IHackCodegenConfig $config ,
@@ -270,6 +272,15 @@ public function setDoClobber(bool $do_force): this {
270272
271273 private function getContent (): string {
272274 $builder = hack_builder ();
275+ $builder -> addLineIf(
276+ $this -> fileNamespace !== null ,
277+ ' namespace %s;' ,
278+ $this -> fileNamespace ,
279+ );
280+ foreach ($this -> useNamespaces as $ns => $as ) {
281+ $builder -> addLine($as === null ? " use $ns ;" : " use $ns as $as ;" );
282+ }
283+
273284 foreach ($this -> beforeTypes as $type ) {
274285 $builder -> ensureNewLine()-> newLine();
275286 $builder -> add($type -> render());
@@ -330,6 +341,33 @@ public function setGeneratedFrom(
330341 return $this ;
331342 }
332343
344+ public function setNamespace (string $file_namespace ): this {
345+ invariant ($this -> fileNamespace === null , ' namespace has already been set' );
346+ $this -> fileNamespace = $file_namespace ;
347+ return $this ;
348+ }
349+
350+ public function useNamespace (string $ns , ?string $as = null ): this {
351+ invariant (
352+ ! $this -> useNamespaces -> contains($ns ),
353+ $ns . ' is already being used' ,
354+ );
355+ $this -> useNamespaces [$ns ] = $as ;
356+ return $this ;
357+ }
358+
359+ public function useClass (string $ns , ?string $as = null ): this {
360+ return $this -> useNamespace($ns , $as );
361+ }
362+
363+ public function useFunction (string $ns , ?string $as = null ): this {
364+ return $this -> useNamespace(' function ' . $ns , $as );
365+ }
366+
367+ public function useConst (string $ns , ?string $as = null ): this {
368+ return $this -> useNamespace(' const ' . $ns , $as );
369+ }
370+
333371 /**
334372 * If called, save() will only write the file if it doesn't exist
335373 */
0 commit comments