@@ -956,6 +956,29 @@ pub fn type_name(module: &ModuleDef, ty: &AlgebraicTypeUse) -> String {
956
956
s
957
957
}
958
958
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
+
959
982
pub fn write_type < W : Write > (
960
983
module : & ModuleDef ,
961
984
out : & mut W ,
@@ -999,7 +1022,15 @@ pub fn write_type<W: Write>(
999
1022
if matches ! ( & * * elem_ty, AlgebraicTypeUse :: Primitive ( PrimitiveType :: U8 ) ) {
1000
1023
return write ! ( out, "Uint8Array" ) ;
1001
1024
}
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
+ }
1002
1030
write_type ( module, out, elem_ty, ref_prefix) ?;
1031
+ if needs_parens {
1032
+ write ! ( out, ")" ) ?;
1033
+ }
1003
1034
write ! ( out, "[]" ) ?;
1004
1035
}
1005
1036
AlgebraicTypeUse :: Ref ( r) => {
0 commit comments