Package Declaration

In Cangjie, a package declaration starts with the keyword package, followed by package names from the root package to the current subpackage separated by dots .. Package and subpackage names must be valid common identifiers (that is, they cannot contain raw identifiers). For example:

package pkg1      // root package pkg1
package pkg1.sub1 // Subpackage sub1 of the root package pkg1

The package declaration must be in the first non-empty, non-commented line of the source file, and the package declarations of different source files in the same package must be consistent.

// file 1
// Comments are accepted
package test
// declarations...

// file 2
let a = 1 // Error, package declaration must appear first in a file
package test
// declarations...

The Cangjie package name should match the path of the current source file relative to the source code root directory src of the project, with dots . replacing the path separators. For example, if the source code of a package is in the src/directory_0/directory_1 directory and the root package name is pkg, the package declaration in the source code should be package pkg.directory_0.directory_1.

Note:

  • The name of the directory where the package source files are located must be the same as the package name.
  • The default name of the source code root directory is src.
  • Source files located in the source root directory are permitted to have no package declaration. In such cases, the compiler will automatically assign the name default to the package.

Assume that the source code directory structure is as follows:

// The directory structure is as follows:
src
`-- directory_0
    |-- directory_1
    |    |-- a.cj
    |    `-- b.cj
    `-- c.cj
`-- main.cj

The package declarations in the a.cj, b.cj, c.cj, and main.cj files can be the following:

// a.cj
// in file a.cj, the declared package name must correspond to relative path directory_0/directory_1.

package default.directory_0.directory_1
// b.cj
// in file b.cj, the declared package name must correspond to relative path directory_0/directory_1.

package default.directory_0.directory_1
// c.cj
// in file c.cj, the declared package name must correspond to relative path directory_0.

package default.directory_0
// main.cj
// file main.cj is in the module root directory and may omit package declaration.

main() {
    return 0
}

In addition, a package declaration must avoid name conflicts. That is, a subpackage cannot have the same name as a top-level declaration in the current package.

The following are some incorrect examples:

// a.cj
package a
public class B { // Error, 'B' is conflicted with subpackage 'a.B'
    public static func f() {}
}

// b.cj
package a.B
public func f {}

// main.cj
import a.B // ambiguous use of 'a.B'

main() {
    a.B.f()
    return 0
}