@@ -956,6 +956,29 @@ pub fn type_name(module: &ModuleDef, ty: &AlgebraicTypeUse) -> String {
956956 s
957957}
958958
959+ // This should return true if we should wrap the type in parentheses when it is the element type of
960+ // an array. This is needed if the type has a `|` in it, e.g. `Option<T>` or `Foo | Bar`, since
961+ // without parens, `Foo | Bar[]` would be parsed as `Foo | (Bar[])`.
962+ fn needs_parens_within_array ( ty : & AlgebraicTypeUse ) -> bool {
963+ match ty {
964+ AlgebraicTypeUse :: Unit
965+ | AlgebraicTypeUse :: Never
966+ | AlgebraicTypeUse :: Identity
967+ | AlgebraicTypeUse :: ConnectionId
968+ | AlgebraicTypeUse :: Timestamp
969+ | AlgebraicTypeUse :: TimeDuration
970+ | AlgebraicTypeUse :: Primitive ( _)
971+ | AlgebraicTypeUse :: Array ( _)
972+ | AlgebraicTypeUse :: Ref ( _) // We use the type name for these.
973+ | AlgebraicTypeUse :: String => {
974+ false
975+ }
976+ AlgebraicTypeUse :: ScheduleAt | AlgebraicTypeUse :: Option ( _) => {
977+ true
978+ }
979+ }
980+ }
981+
959982pub fn write_type < W : Write > (
960983 module : & ModuleDef ,
961984 out : & mut W ,
@@ -999,7 +1022,15 @@ pub fn write_type<W: Write>(
9991022 if matches ! ( & * * elem_ty, AlgebraicTypeUse :: Primitive ( PrimitiveType :: U8 ) ) {
10001023 return write ! ( out, "Uint8Array" ) ;
10011024 }
1025+ let needs_parens = needs_parens_within_array ( elem_ty) ;
1026+ // We wrap the inner type in parentheses to avoid ambiguity with the [] binding.
1027+ if needs_parens {
1028+ write ! ( out, "(" ) ?;
1029+ }
10021030 write_type ( module, out, elem_ty, ref_prefix) ?;
1031+ if needs_parens {
1032+ write ! ( out, ")" ) ?;
1033+ }
10031034 write ! ( out, "[]" ) ?;
10041035 }
10051036 AlgebraicTypeUse :: Ref ( r) => {
0 commit comments