cratestack_parser/lib.rs
1mod diagnostics;
2mod line_helpers;
3mod parse;
4mod relation_actions;
5mod relation_helpers;
6mod validate;
7
8#[cfg(test)]
9mod tests_attribute_spacing;
10#[cfg(test)]
11mod tests_basic;
12mod tests_builder_add_setter_collisions;
13#[cfg(test)]
14mod tests_builder_collisions;
15mod tests_builder_collisions_derived;
16#[cfg(test)]
17mod tests_client_method_collisions;
18#[cfg(test)]
19mod tests_computed;
20#[cfg(test)]
21mod tests_computed_params;
22#[cfg(test)]
23mod tests_docs;
24#[cfg(test)]
25mod tests_enums;
26#[cfg(test)]
27mod tests_extensions;
28#[cfg(test)]
29mod tests_field_attrs;
30#[cfg(test)]
31mod tests_list_arity;
32#[cfg(test)]
33mod tests_mixins;
34#[cfg(test)]
35mod tests_model_attrs;
36#[cfg(test)]
37mod tests_model_index;
38#[cfg(test)]
39mod tests_model_internal;
40#[cfg(test)]
41mod tests_model_unique;
42#[cfg(test)]
43mod tests_multi_error;
44mod tests_patch_touch_flag_collisions;
45#[cfg(test)]
46mod tests_procedure_handler_collisions;
47#[cfg(test)]
48mod tests_procedures;
49#[cfg(test)]
50mod tests_relation_actions;
51#[cfg(test)]
52mod tests_relations;
53#[cfg(test)]
54mod tests_relations_policy;
55#[cfg(test)]
56mod tests_reserved_keywords;
57#[cfg(test)]
58mod tests_snake_case_collisions;
59#[cfg(test)]
60mod tests_stream_attribute;
61#[cfg(test)]
62mod tests_transport;
63#[cfg(test)]
64mod tests_type_declaration_collisions;
65#[cfg(test)]
66mod tests_types;
67#[cfg(test)]
68mod tests_validators;
69#[cfg(test)]
70mod tests_vector;
71#[cfg(test)]
72mod tests_version;
73#[cfg(test)]
74mod tests_views;
75
76use std::path::Path;
77
78pub use diagnostics::SchemaError;
79
80/// Canonical scalar type names built into the `.cstack` language (e.g.
81/// `String`, `Int`, `Decimal`, ...), including `Page` (which is valid only
82/// as a procedure return type — see `validate::type_names::validate_type_ref`
83/// — not as a plain field type).
84///
85/// This is the same list `cratestack-lsp`'s autocompletion and the
86/// `cratestack-pg`/`cratestack-sqlite` emitter/decoder round-trip tests
87/// assert against, so a new builtin scalar only has to be added here once —
88/// see cratestack#232 for why that matters (this list had already silently
89/// drifted from the LSP's hand-copied one before this accessor existed).
90pub fn builtin_type_names() -> &'static [&'static str] {
91 validate::builtin_type_names()
92}
93
94#[cfg(test)]
95use relation_helpers::parse_relation_attribute;
96
97pub fn parse_schema(source: &str) -> Result<cratestack_core::Schema, SchemaError> {
98 parse_schema_named("<schema>", source)
99}
100
101pub fn parse_schema_named(
102 path: &str,
103 source: &str,
104) -> Result<cratestack_core::Schema, SchemaError> {
105 let schema = parse::parse_schema_only(source)?;
106 validate::validate_schema(path, source, &schema)?;
107 Ok(schema)
108}
109
110/// Parse and validate, reporting **every** independent problem rather than
111/// only the first.
112///
113/// [`parse_schema_named`] stops at the first error, which is right for a
114/// compiler or a CLI: the build is failing either way, and one clear message
115/// beats a cascade. It is wrong for an editor, where stopping early means the
116/// author fixes one error, saves, and is handed the next — one round trip per
117/// mistake.
118///
119/// Semantics worth knowing:
120///
121/// * A **syntax** error still yields exactly one diagnostic. Parsing has no
122/// recovery, so there is no second error to report — everything after the
123/// failure is unparsed, not valid.
124/// * **Validation** errors are collected in stages, and a stage runs only when
125/// every earlier stage was clean. Several validators document that they
126/// assume an earlier one passed, and running them over already-rejected input
127/// produces cascades pointing at the wrong places. Within a stage, every
128/// declaration reports independently — three models each naming a type that
129/// does not exist produce three diagnostics, not three round trips.
130/// * The schema is returned only when there are no errors at all, matching
131/// [`parse_schema_named`].
132///
133/// The first element of the returned `Vec` is always the same error
134/// [`parse_schema_named`] would have returned; both go through one set of
135/// checks in one order, so they cannot drift apart.
136pub fn parse_schema_diagnostics(
137 path: &str,
138 source: &str,
139) -> (Option<cratestack_core::Schema>, Vec<SchemaError>) {
140 let schema = match parse::parse_schema_only(source) {
141 Ok(schema) => schema,
142 Err(error) => return (None, vec![error]),
143 };
144 let errors = validate::validate_schema_collecting(path, source, &schema);
145 if errors.is_empty() {
146 (Some(schema), Vec::new())
147 } else {
148 (None, errors)
149 }
150}
151
152/// Parse a `.cstack` source into a [`cratestack_core::Schema`] WITHOUT
153/// running [`validate::validate_schema`].
154///
155/// Prefer [`parse_schema`] for any new source — this exists for two
156/// legitimate cases where the validated pipeline understates what a
157/// `Schema` value can actually be:
158///
159/// 1. A committed `migrations/*/schema.snapshot.json` can predate a
160/// validation rule added later. `cratestack-cli`'s `migrate diff`
161/// deserializes that "previous" snapshot directly and never re-runs
162/// `validate_schema` on it (only the *new* side, parsed fresh from the
163/// `.cstack` source, goes through [`parse_schema_file`]) — so an emitter
164/// can still legitimately be handed a shape the current validator would
165/// reject at the source level.
166/// 2. Tests that deliberately exercise an emitter's rendering logic for
167/// such an already-invalid shape, to prove the emitter itself still
168/// behaves sanely if that shape arrives via (1) — see
169/// `cratestack-migrate`'s `emit::postgres::tests::enums` for an example
170/// (a list-valued enum column, rejected by cratestack#229/#236 at parse
171/// time, but still real input to the Postgres emitter via a pre-#236
172/// snapshot).
173pub fn parse_schema_unvalidated(source: &str) -> Result<cratestack_core::Schema, SchemaError> {
174 parse::parse_schema_only(source)
175}
176
177pub fn parse_schema_file(path: impl AsRef<Path>) -> Result<cratestack_core::Schema, SchemaError> {
178 let path = path.as_ref();
179 let source = std::fs::read_to_string(path).map_err(|error| {
180 SchemaError::new(
181 format!("failed to read schema file {}: {error}", path.display()),
182 0..0,
183 1,
184 )
185 })?;
186 parse_schema_named(&path.display().to_string(), &source)
187}