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