diff --git a/next/language/fundamentals.md b/next/language/fundamentals.md index 5bc10301..d9741bfe 100644 --- a/next/language/fundamentals.md +++ b/next/language/fundamentals.md @@ -1096,6 +1096,23 @@ you can leave a type alias `typealias T = @pkgB.T` in `@pkgA`, and **incremental The type alias can be removed after all uses of `@pkgA.T` is migrated to `@pkgB.T`. ``` +### Local types + +Moonbit supports declaring structs/enums/newtypes at the top of a toplevel +function, which are only visible within the current toplevel function. These +local types can use the generic parameters of the toplevel function but cannot +introduce additional generic parameters themselves. Local types can derive +methods using derive, but no additional methods can be defined manually. For +example: + +```{literalinclude} /sources/language/src/data/top.mbt +:language: moonbit +:start-after: start local-type 1 +:end-before: end local-type 1 +``` + +Currently, local types do not support being declared as error types. + ## Pattern Matching Pattern matching allows us to match on specific pattern and bind data from data structures. diff --git a/next/sources/language/src/data/top.mbt b/next/sources/language/src/data/top.mbt index ffdcfa55..4c35096d 100644 --- a/next/sources/language/src/data/top.mbt +++ b/next/sources/language/src/data/top.mbt @@ -303,3 +303,17 @@ pub typealias Index = Int // type alias are private by default typealias MapString[X] = Map[String, X] // end typealias 1 + +// start local-type 1 +fn toplevel[T: Show](x: T) -> Unit { + enum LocalEnum { + A(T) + B(Int) + } derive(Show) + struct LocalStruct { + a: (String, T) + } derive(Show) + type LocalNewtype T derive(Show) + ... +} +// end local-type 1 \ No newline at end of file