Skip to content
This repository was archived by the owner on Feb 6, 2025. It is now read-only.

Commit 0a6e0d6

Browse files
committed
Add failible ExternalDeclaration::new_struct. #49
1 parent a31b701 commit 0a6e0d6

File tree

1 file changed

+44
-25
lines changed

1 file changed

+44
-25
lines changed

src/syntax.rs

+44-25
Original file line numberDiff line numberDiff line change
@@ -584,33 +584,43 @@ impl ExternalDeclaration {
584584
}
585585

586586
/// Create a new structure.
587-
pub fn new_struct<N, F>(name: N, fields: F) -> Self
587+
///
588+
/// # Errors
589+
///
590+
/// - `None` if no fields are provided. GLSL forbids having empty structs.
591+
pub fn new_struct<N, F>(name: N, fields: F) -> Option<Self>
588592
where N: Into<String>,
589593
F: IntoIterator<Item = StructFieldSpecifier> {
590-
ExternalDeclaration::Declaration(
591-
Declaration::InitDeclaratorList(
592-
InitDeclaratorList {
593-
head: SingleDeclaration {
594-
ty: FullySpecifiedType {
595-
qualifier: None,
596-
ty: TypeSpecifier {
597-
ty: TypeSpecifierNonArray::Struct(
598-
StructSpecifier {
599-
name: Some(name.into()),
600-
fields: fields.into_iter().collect()
601-
}
602-
),
603-
array_specifier: None
604-
}
594+
let fields: Vec<_> = fields.into_iter().collect();
595+
596+
if fields.is_empty() {
597+
None
598+
} else {
599+
Some(ExternalDeclaration::Declaration(
600+
Declaration::InitDeclaratorList(
601+
InitDeclaratorList {
602+
head: SingleDeclaration {
603+
ty: FullySpecifiedType {
604+
qualifier: None,
605+
ty: TypeSpecifier {
606+
ty: TypeSpecifierNonArray::Struct(
607+
StructSpecifier {
608+
name: Some(name.into()),
609+
fields: fields.into_iter().collect()
610+
}
611+
),
612+
array_specifier: None
613+
}
614+
},
615+
name: None,
616+
array_specifier: None,
617+
initializer: None
605618
},
606-
name: None,
607-
array_specifier: None,
608-
initializer: None
609-
},
610-
tail: vec![]
611-
}
612-
)
613-
)
619+
tail: vec![]
620+
}
621+
)
622+
))
623+
}
614624
}
615625
}
616626

@@ -883,12 +893,21 @@ mod tests {
883893
// };
884894
#[test]
885895
fn declare_struct() {
886-
let _ =
896+
let point =
887897
ExternalDeclaration::new_struct("Point2D",
888898
vec![
889899
StructFieldSpecifier::new("x", TypeSpecifierNonArray::Double),
890900
StructFieldSpecifier::new("y", TypeSpecifierNonArray::Double)
891901
]
892902
);
903+
904+
assert!(point.is_some());
905+
}
906+
907+
// struct Point2D {};
908+
#[test]
909+
fn declare_bad_struct() {
910+
let point = ExternalDeclaration::new_struct("Point2D", vec![]);
911+
assert!(point.is_none());
893912
}
894913
}

0 commit comments

Comments
 (0)