--- title: Type name alias with use syntax tags: RBS --- # Type name alias with `use` syntax The `use` syntax allows using type names with shorter alias names. Instead of specifying type names with qualified names, the `use` syntax defines aliases of existing type names. It works with per-file basis. The `use` directives written in a file works only for the file. The directive works only for RBS. There is no corresponding Ruby code. ## `use` with single type name clause The simplest form of the directive is for single type name, without new name. ```rbs= use RBS::Namespace ``` With the directive, the relative type name/namespace `Namespace` is resolved to `::RBS::Namespace`. ## `use` with single type name with new name clause One *single type name* use clause can have optional `as` keyword to give a new name to the type. ```rbs= use RBS::Resolver::context as resolver_context ``` The `resolver_context` is resolved to `::RBS::Resolver::context`. ## `use` with wildcard clause The *wildcard* use clause allows defining same-name aliases of all types under the namespace. ```rbs= use RBS::AST::* ``` The `RBS::AST::` namespace contains modules including `::RBS::AST::Declarations` and `::RBS::AST::Members`, and it all of the names can be accessed with the base name, as `Declarations` and `Members`. ## `use` with multiple clauses ```rbs use RBS::Namespace, RBS::TypeName as TN, RBS::AST::* ``` ## Syntax The `use` directive has a syntax rule as follows: ``` use-directive ::= `use` *use-clause* `,` ... `,` *use-clause* use-clause ::= *type-name* | *type-name* `as` *simple-type-name* | *namespace* `::` `*` ``` The `*type-name*` and `*namespace*` can be either relative or absolute. Relative type names and namespaces are simply converted to absolute type name, just by adding `::` at the head of them. ## Discussion ### Using alias names to define new types The `use` name resolution works with right-hand-side types. It cannot be used to define new types. ```rbs= use RBS::TypeName # Defines a class, ::TypeName, not ::RBS::TypeName class TypeName end ``` ### Alias names resolution The alias names works for relative type names. Fully qualified type names are not subject for `use` name resolution. ```rbs= use RBS::TypeName Foo: TypeName # ::RBS::TypeName Bar: ::TypeName # ::TypeName ``` Note that the `use` name resolution has higher precedence than usual type name resolution. ```rbs= use RBS::TypeName class TypeName # Defines ::TypeName Foo: TypeName # ::RBS::TypeName, not ::TypeName end ``` When alias names conflict, the names from later clauses wins. ```rbs= use RBS::TypeName as Declarations use RBS::AST::Declarations ``` Both the `use` directives at line 1 and 2 defines alias of `Declarations`, and the `::RBS::AST::Declarations` wins.