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