1use proc_macro::{Delimiter, TokenStream, TokenTree};
32
33#[proc_macro_derive(Model, attributes(model, obs))]
42pub fn model(input: TokenStream) -> TokenStream {
43 finish(expand_model(input))
44}
45
46fn finish(result: Result<String, String>) -> TokenStream {
47 match result {
48 Ok(out) => out
49 .parse()
50 .unwrap_or_else(|e| panic!("generated code did not parse: {e}")),
51 Err(msg) => format!("compile_error!({msg:?});")
52 .parse()
53 .expect("compile_error! literal always parses"),
54 }
55}
56
57#[derive(Default)]
58struct FieldDef {
59 name: String,
60 ty: String,
61 key: bool,
62 skip: bool,
63 column: Option<String>,
65 unique: bool,
66 indexed: bool,
67 transient: bool,
68 with: Option<String>,
69 json: bool,
70 lazy: bool,
73 relation: Option<RelationAttr>,
76 link: Option<LinkAttr>,
80}
81
82struct LinkAttr {
84 target: String,
85 local: String,
86 remote: String,
87}
88
89struct RelationAttr {
91 target: String,
92 inverse: Option<String>,
93 delete: String,
94 ordered: Option<String>,
95 join: Option<String>,
96}
97
98impl FieldDef {
99 fn column_name(&self) -> &str {
100 self.column.as_deref().unwrap_or(&self.name)
101 }
102 fn persisted(&self) -> bool {
103 !self.skip && !self.transient && self.relation.is_none() && self.link.is_none()
104 }
105 fn nullable(&self) -> bool {
106 self.ty == "Option" || self.ty.starts_with("Option <")
107 }
108}
109
110struct StructDef {
111 name: String,
112 table: Option<String>,
113 external: Option<String>,
116 composites: Vec<Vec<String>>,
117 uniques: Vec<Vec<String>>,
119 fts: Vec<String>,
120 fts_tokenize: Option<String>,
121 spatial: Option<(String, String)>,
122 fields: Vec<FieldDef>,
123}
124
125fn expand_model(input: TokenStream) -> Result<String, String> {
126 let def = parse_struct(input)?;
127 let keys: Vec<&FieldDef> = def.fields.iter().filter(|f| f.key).collect();
128 let key = match keys.as_slice() {
129 [k] => *k,
130 [] => {
131 return Err(format!(
132 "Model: `{}` needs exactly one field marked #[model(id)]",
133 def.name
134 ));
135 }
136 _ => {
137 return Err(format!(
138 "Model: `{}` marks more than one field as the id",
139 def.name
140 ));
141 }
142 };
143 if key.transient || key.skip {
144 return Err(format!(
145 "Model: `{}`'s id field cannot be transient or skipped",
146 def.name
147 ));
148 }
149 if key.with.is_some() || key.json {
150 return Err(format!(
153 "Model: `{}`'s id field takes no codec — integer, Uuid and String keys store \
154 in their canonical forms",
155 def.name
156 ));
157 }
158
159 let mut out = observable_impls(&def);
160 out.push_str(&emit_model(&def, key)?);
161 Ok(out)
162}
163
164fn observable_impls(def: &StructDef) -> String {
173 let mut out = format!(
174 "day_persistence::__observable_impls! {{\n struct {} {{\n",
175 def.name
176 );
177 for f in def
178 .fields
179 .iter()
180 .filter(|f| !f.skip && f.relation.is_none() && f.link.is_none())
181 {
182 let key = if f.key { "#[obs(key)] " } else { "" };
183 out.push_str(&format!(" {key}{}: {},\n", f.name, f.ty));
184 }
185 out.push_str(" }\n}\n");
186 out
187}
188
189fn emit_model(def: &StructDef, key: &FieldDef) -> Result<String, String> {
193 let name = &def.name;
194 let bare_table = def.table.clone().unwrap_or_else(|| snake_case(name));
195 let table = match &def.external {
199 Some(alias) => format!("{alias}.{bare_table}"),
200 None => bare_table.clone(),
201 };
202 for f in def.fields.iter().filter(|f| f.lazy) {
203 if f.key {
204 return Err(format!(
205 "Model: `{name}`'s id field `{}` cannot be a Blob",
206 f.name
207 ));
208 }
209 if f.with.is_some() || f.json {
210 return Err(format!(
211 "Model: Blob field `{}` of `{name}` takes no codec; it is stored as it is",
212 f.name
213 ));
214 }
215 if !f.persisted() {
216 return Err(format!(
217 "Model: Blob field `{}` of `{name}` cannot be transient or a relation marker",
218 f.name
219 ));
220 }
221 }
222 if let Some(f) = def.fields.iter().find(|f| {
223 f.nullable() && is_blob_type(f.ty.trim_start_matches("Option <").trim_end_matches('>'))
224 }) {
225 return Err(format!(
226 "Model: field `{}` of `{name}` is `Option<Blob>`; a Blob column is nullable by \
227 itself (a NULL reads as empty), so declare it as `Blob`",
228 f.name
229 ));
230 }
231 let persisted: Vec<&FieldDef> = def
235 .fields
236 .iter()
237 .filter(|f| f.persisted() && !f.lazy)
238 .chain(def.fields.iter().filter(|f| f.persisted() && f.lazy))
239 .collect();
240 for f in def.fields.iter().filter(|f| f.link.is_some()) {
241 let l = f.link.as_ref().expect("filtered");
242 if !persisted.iter().any(|p| p.column_name() == l.local) {
243 return Err(format!(
244 "Model: link(…) on `{}` names local = {:?}, which is not a persisted column of `{name}`",
245 f.name, l.local
246 ));
247 }
248 }
249
250 check_name("table", &bare_table)?;
253 for f in &persisted {
254 check_name(&format!("column of field `{}`", f.name), f.column_name())?;
255 }
256 for (i, f) in persisted.iter().enumerate() {
257 let twin = persisted[..i]
258 .iter()
259 .find(|p| p.column_name().eq_ignore_ascii_case(f.column_name()));
260 if let Some(twin) = twin {
261 return Err(format!(
262 "Model: fields `{}` and `{}` of `{name}` both store in column {:?} (SQLite \
263 compares column names without case)",
264 twin.name,
265 f.name,
266 f.column_name()
267 ));
268 }
269 }
270
271 let mut columns = String::new();
272 for f in &persisted {
273 let sql = sql_type_expr(f);
274 columns.push_str(&format!(
275 " day_persistence::ColumnDef {{ name: {:?}, field: \"{}\", sql: {sql}, \
276 not_null: {}, unique: {}, indexed: {}, lazy: {} }},\n",
277 f.column_name(),
278 f.name,
279 !f.nullable() && !f.lazy,
280 f.unique,
281 f.indexed,
282 f.lazy,
283 ));
284 }
285
286 let column_names: Vec<&str> = persisted.iter().map(|f| f.column_name()).collect();
288 for c in &def.fts {
289 if !column_names.contains(&c.as_str()) {
290 return Err(format!(
291 "Model: fts(…) names `{c}`, which is not a persisted column of `{name}`"
292 ));
293 }
294 }
295 for (what, lists) in [("index", &def.composites), ("unique", &def.uniques)] {
296 for cols in lists {
297 for c in cols {
298 if !column_names.contains(&c.as_str()) {
299 return Err(format!(
300 "Model: {what}(…) names `{c}`, which is not a persisted column of `{name}`"
301 ));
302 }
303 }
304 }
305 }
306 if let Some((lat, lon)) = &def.spatial {
307 for c in [lat, lon] {
308 if !column_names.contains(&c.as_str()) {
309 return Err(format!(
310 "Model: spatial(…) names `{c}`, which is not a persisted column of `{name}`"
311 ));
312 }
313 }
314 }
315
316 let uniques = def
317 .uniques
318 .iter()
319 .map(|cols| {
320 format!(
321 "&[{}]",
322 cols.iter()
323 .map(|c| format!("{c:?}"))
324 .collect::<Vec<_>>()
325 .join(", ")
326 )
327 })
328 .collect::<Vec<_>>()
329 .join(", ");
330 let composites = def
331 .composites
332 .iter()
333 .map(|cols| {
334 format!(
335 "&[{}]",
336 cols.iter()
337 .map(|c| format!("{c:?}"))
338 .collect::<Vec<_>>()
339 .join(", ")
340 )
341 })
342 .collect::<Vec<_>>()
343 .join(", ");
344
345 let mut to_row = String::new();
346 for f in &persisted {
347 to_row.push_str(&format!(" {},\n", encode_expr(f)));
348 }
349
350 let mut from_row = String::new();
351 for f in &def.fields {
352 if let Some(i) = persisted.iter().position(|p| p.name == f.name) {
353 from_row.push_str(&format!(" {}: {},\n", f.name, decode_expr(f, i)));
354 } else {
355 from_row.push_str(&format!(
356 " {}: ::core::default::Default::default(),\n",
357 f.name
358 ));
359 }
360 }
361
362 let mut cols = String::new();
366 for f in &persisted {
367 let encode = match codec(f) {
368 Some(codec) => format!(
369 "<{codec} as day_persistence::ValueCodec<{}>>::to_sqlite_value",
370 f.ty
371 ),
372 None => format!("day_persistence::encode_column::<{}>", f.ty),
373 };
374 cols.push_str(&format!(
375 " pub fn {}() -> day_persistence::Col<{}> {{\n\
376 \x20 day_persistence::Col::new({:?}, \"{}\", {table:?}, {encode})\n\
377 \x20 }}\n",
378 f.name,
379 f.ty,
380 f.column_name(),
381 f.name,
382 ));
383 }
384 for f in def.fields.iter().filter(|f| f.relation.is_some()) {
388 let r = f.relation.as_ref().expect("filtered");
389 cols.push_str(&format!(
390 " pub fn {}() -> day_persistence::RelationCol<{name}, {}> {{\n\
391 \x20 day_persistence::RelationCol::new(\"{}\", {table:?}, \
392 <{} as day_persistence::Model>::TABLE)\n\
393 \x20 }}\n",
394 f.name, r.target, f.name, r.target,
395 ));
396 }
397 for f in def.fields.iter().filter(|f| f.link.is_some()) {
401 let l = f.link.as_ref().expect("filtered");
402 cols.push_str(&format!(
403 " pub fn {}() -> day_persistence::RelationCol<{name}, {}> {{\n\
404 \x20 day_persistence::RelationCol::new(\"{}\", {table:?}, \
405 <{} as day_persistence::Model>::TABLE)\n\
406 \x20 }}\n",
407 f.name, l.target, f.name, l.target,
408 ));
409 }
410 if !def.fts.is_empty() {
411 cols.push_str(&format!(
412 " pub fn fts() -> day_persistence::FtsRef {{\n\
413 \x20 day_persistence::FtsRef {{ columns: <{name} as day_persistence::Model>::FTS_COLUMNS }}\n\
414 \x20 }}\n"
415 ));
416 }
417 if let Some((lat, lon)) = &def.spatial {
418 cols.push_str(&format!(
419 " pub fn geo() -> day_persistence::GeoRef {{\n\
420 \x20 day_persistence::GeoRef {{ lat: {lat:?}, lon: {lon:?} }}\n\
421 \x20 }}\n"
422 ));
423 }
424 let col_impl = format!("#[allow(dead_code)]\nimpl {name} {{\n{cols}}}\n");
425
426 let rels: Vec<(&FieldDef, &RelationAttr)> = def
428 .fields
429 .iter()
430 .filter_map(|f| f.relation.as_ref().map(|r| (f, r)))
431 .collect();
432 let delete_expr = |d: &str| match d {
433 "cascade" => "day_persistence::DeleteRule::Cascade",
434 "deny" => "day_persistence::DeleteRule::Deny",
435 _ => "day_persistence::DeleteRule::Nullify",
436 };
437 let opt_str = |o: &Option<String>| match o {
438 Some(s) => format!("Some({s:?})"),
439 None => "None".into(),
440 };
441 let relations_const = if rels.is_empty() {
442 String::new()
443 } else {
444 format!(
445 " const RELATIONS: &'static [day_persistence::RelationDef] = &[\n{} ];\n",
446 rels.iter()
447 .map(|(f, r)| format!(
448 " day_persistence::RelationDef {{ field: \"{}\", target_table: \
449 <{} as day_persistence::Model>::TABLE, inverse: {:?}, delete: {}, \
450 ordered: {}, join: {} }},\n",
451 f.name,
452 r.target,
453 r.inverse.as_deref().unwrap_or(""),
454 delete_expr(&r.delete),
455 opt_str(&r.ordered),
456 opt_str(&r.join),
457 ))
458 .collect::<String>()
459 )
460 };
461 let wire_fn = if rels.is_empty() {
462 String::new()
463 } else {
464 format!(
465 " fn wire(reg: &mut day_persistence::Registrar<'_>) {{\n{} }}\n",
466 rels.iter()
467 .map(|(f, r)| match (&r.join, &r.inverse) {
468 (Some(join), _) => format!(
469 " day_persistence::wire_join::<Self, {}>(reg, \"{}\", \
470 {join:?}, {}, {});\n",
471 r.target,
472 f.name,
473 opt_str(&r.ordered),
474 delete_expr(&r.delete),
475 ),
476 (None, Some(inverse)) => format!(
477 " day_persistence::wire_to_many::<Self, {}>(reg, \"{}\", \
478 {inverse:?}, {}, {});\n",
479 r.target,
480 f.name,
481 delete_expr(&r.delete),
482 opt_str(&r.ordered),
483 ),
484 (None, None) => String::new(), })
486 .collect::<String>()
487 )
488 };
489 let rel_trait = if rels.is_empty() {
490 String::new()
491 } else {
492 format!(
493 "#[allow(non_camel_case_types)]\n\
494 pub trait {name}Relations: day_model::Source<{name}> + Sized {{\n{}}}\n\
495 impl<S: day_model::Source<{name}>> {name}Relations for S {{}}\n",
496 rels.iter()
497 .map(|(f, r)| format!(
498 " fn {}(self) -> day_persistence::RelationRef<Self, {name}, {}> {{\n\
499 \x20 day_persistence::RelationRef::new(day_model::project(\
500 self, \"{}\", |s| &s.{}, |s| &mut s.{}))\n\
501 \x20 }}\n",
502 f.name, r.target, f.name, f.name, f.name
503 ))
504 .collect::<String>()
505 )
506 };
507
508 let fts_const = if def.fts.is_empty() {
509 String::new()
510 } else {
511 let tokenize = match &def.fts_tokenize {
512 Some(t) => format!(" const FTS_TOKENIZE: Option<&'static str> = Some({t:?});\n"),
513 None => String::new(),
514 };
515 format!(
516 " const FTS_COLUMNS: &'static [&'static str] = &[{}];\n{tokenize}",
517 def.fts
518 .iter()
519 .map(|c| format!("{c:?}"))
520 .collect::<Vec<_>>()
521 .join(", ")
522 )
523 };
524 let links: Vec<(&FieldDef, &LinkAttr)> = def
525 .fields
526 .iter()
527 .filter_map(|f| f.link.as_ref().map(|l| (f, l)))
528 .collect();
529 let links_const = if links.is_empty() {
530 String::new()
531 } else {
532 format!(
533 " const LINKS: &'static [day_persistence::LinkDef] = &[\n{} ];\n",
534 links
535 .iter()
536 .map(|(f, l)| format!(
537 " day_persistence::LinkDef {{ field: \"{}\", local: {:?}, \
538 target_table: <{} as day_persistence::Model>::TABLE, remote: {:?} }},\n",
539 f.name, l.local, l.target, l.remote
540 ))
541 .collect::<String>()
542 )
543 };
544 let external_const = match &def.external {
545 Some(alias) => format!(
546 " const EXTERNAL: bool = true;\n const SCHEMA: Option<&'static str> = Some({alias:?});\n"
547 ),
548 None => String::new(),
549 };
550 let spatial_const = match &def.spatial {
551 None => String::new(),
552 Some((lat, lon)) => format!(
553 " const SPATIAL: Option<day_persistence::SpatialCols> = \
554 Some(day_persistence::SpatialCols {{ lat: {lat:?}, lon: {lon:?} }});\n"
555 ),
556 };
557
558 let lazy_fields: Vec<&FieldDef> = persisted.iter().copied().filter(|f| f.lazy).collect();
559 let lazy_const = if lazy_fields.is_empty() {
560 String::new()
561 } else {
562 format!(
563 " const LAZY_FIELDS: &'static [&'static str] = &[{}];\n\
564 \x20 fn settle_lazy(&mut self) -> Vec<(&'static str, ::std::sync::Arc<Vec<u8>>)> {{\n\
565 \x20 let mut out = Vec::new();\n{}\
566 \x20 out\n\
567 \x20 }}\n",
568 lazy_fields
569 .iter()
570 .map(|f| format!("\"{}\"", f.name))
571 .collect::<Vec<_>>()
572 .join(", "),
573 lazy_fields
574 .iter()
575 .map(|f| format!(
576 " if let Some(b) = self.{}.take_pending() {{ out.push((\"{}\", b)); }}\n",
577 f.name, f.name
578 ))
579 .collect::<String>(),
580 )
581 };
582
583 let key_sql = sql_type_expr(key);
584 Ok(col_impl
585 + &rel_trait
586 + &format!(
587 "impl day_persistence::Model for {name} {{\n\
588 \x20 const TABLE: &'static str = {table:?};\n\
589 \x20 const KEY: &'static str = {key_col:?};\n\
590 \x20 const KEY_SQL: day_persistence::SqlType = {key_sql};\n\
591 \x20 const COLUMNS: &'static [day_persistence::ColumnDef] = &[\n{columns} ];\n\
592 \x20 const COMPOSITE_INDEXES: &'static [&'static [&'static str]] = &[{composites}];\n\
593 \x20 const UNIQUE_INDEXES: &'static [&'static [&'static str]] = &[{uniques}];\n\
594 {fts_const}{spatial_const}{relations_const}{links_const}{external_const}{lazy_const}\
595 \x20 fn to_row(&self) -> Vec<day_persistence::Value> {{\n\
596 \x20 vec![\n{to_row} ]\n\
597 \x20 }}\n\
598 \x20 fn from_row(row: &dyn day_persistence::Row) -> \
599 Result<Self, day_persistence::DbError> {{\n\
600 \x20 Ok(Self {{\n{from_row} }})\n\
601 \x20 }}\n\
602 \x20 fn default_row() -> Vec<day_persistence::Value> {{\n\
603 \x20 day_persistence::Model::to_row(&<Self as ::core::default::Default>::default())\n\
604 \x20 }}\n\
605 {wire_fn}\
606 }}\n",
607 key_col = key.column_name(),
608 ))
609}
610
611fn sql_type_expr(f: &FieldDef) -> String {
612 match codec(f) {
613 Some(codec) => format!(
614 "<{codec} as day_persistence::ValueCodec<{}>>::SQL_TYPE",
615 f.ty
616 ),
617 None => format!("<{} as day_persistence::ColumnValue>::SQL_TYPE", f.ty),
618 }
619}
620
621fn encode_expr(f: &FieldDef) -> String {
622 match codec(f) {
623 Some(codec) => format!(
624 "<{codec} as day_persistence::ValueCodec<{}>>::to_sqlite_value(&self.{})",
625 f.ty, f.name
626 ),
627 None => format!(
628 "day_persistence::ColumnValue::to_sqlite_value(&self.{})",
629 f.name
630 ),
631 }
632}
633
634fn decode_expr(f: &FieldDef, i: usize) -> String {
637 let read = format!("day_persistence::Row::get(row, {i}usize)");
638 match codec(f) {
639 Some(codec) => format!(
640 "match {read} {{\n\
641 \x20 day_persistence::Value::Null => ::core::default::Default::default(),\n\
642 \x20 v => <{codec} as day_persistence::ValueCodec<{}>>::from_sqlite_value(v)?,\n\
643 \x20 }}",
644 f.ty
645 ),
646 None => format!(
647 "match {read} {{\n\
648 \x20 day_persistence::Value::Null => ::core::default::Default::default(),\n\
649 \x20 v => <{} as day_persistence::ColumnValue>::from_sqlite_value(v)?,\n\
650 \x20 }}",
651 f.ty
652 ),
653 }
654}
655
656fn codec(f: &FieldDef) -> Option<String> {
657 if let Some(with) = &f.with {
658 Some(with.clone())
659 } else if f.json {
660 Some("day_persistence::Json".into())
661 } else {
662 None
663 }
664}
665
666fn snake_case(name: &str) -> String {
667 let mut out = String::with_capacity(name.len() + 4);
668 for (i, ch) in name.chars().enumerate() {
669 if ch.is_uppercase() {
670 if i > 0 {
671 out.push('_');
672 }
673 out.extend(ch.to_lowercase());
674 } else {
675 out.push(ch);
676 }
677 }
678 out
679}
680
681fn parse_struct(input: TokenStream) -> Result<StructDef, String> {
687 let tokens: Vec<TokenTree> = input.into_iter().collect();
688
689 let mut opts = StructOptions::default();
690 let mut i = 0;
691 while i < tokens.len() {
692 match &tokens[i] {
693 TokenTree::Ident(id) if id.to_string() == "struct" => break,
694 TokenTree::Punct(p) if p.as_char() == '#' => {
695 if let Some(TokenTree::Group(g)) = tokens.get(i + 1) {
696 if let Some(items) = attr_items(g, "model") {
697 parse_struct_options(items, &mut opts)?;
698 }
699 i += 2;
700 continue;
701 }
702 return Err("malformed attribute on the struct".into());
703 }
704 _ => i += 1,
705 }
706 }
707 if i >= tokens.len() {
708 return Err("the derive expects a struct".into());
709 }
710 let name = match tokens.get(i + 1) {
711 Some(TokenTree::Ident(id)) => id.to_string(),
712 _ => return Err("the derive expects a named struct".into()),
713 };
714 let body = match tokens.get(i + 2) {
715 Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Brace => g.stream(),
716 Some(TokenTree::Punct(p)) if p.as_char() == '<' => {
717 return Err("the derive does not support generic structs yet".into());
718 }
719 _ => return Err("the derive expects a struct with named fields".into()),
720 };
721
722 let StructOptions {
723 table,
724 external,
725 composites,
726 uniques,
727 fts,
728 fts_tokenize,
729 spatial,
730 } = opts;
731 Ok(StructDef {
732 name,
733 table,
734 external,
735 composites,
736 uniques,
737 fts,
738 fts_tokenize,
739 spatial,
740 fields: parse_fields(body)?,
741 })
742}
743
744fn attr_items(bracket: &proc_macro::Group, name: &str) -> Option<Vec<Vec<TokenTree>>> {
746 let inner: Vec<TokenTree> = bracket.stream().into_iter().collect();
747 match (inner.first(), inner.get(1)) {
748 (Some(TokenTree::Ident(id)), Some(TokenTree::Group(g)))
749 if id.to_string() == name && g.delimiter() == Delimiter::Parenthesis =>
750 {
751 let mut items = vec![Vec::new()];
752 for tt in g.stream() {
753 match &tt {
754 TokenTree::Punct(p) if p.as_char() == ',' => items.push(Vec::new()),
755 _ => items.last_mut().expect("never empty").push(tt),
756 }
757 }
758 items.retain(|item| !item.is_empty());
759 Some(items)
760 }
761 _ => None,
762 }
763}
764
765#[derive(Default)]
767struct StructOptions {
768 table: Option<String>,
769 external: Option<String>,
770 composites: Vec<Vec<String>>,
771 uniques: Vec<Vec<String>>,
772 fts: Vec<String>,
773 fts_tokenize: Option<String>,
774 spatial: Option<(String, String)>,
775}
776
777fn parse_struct_options(
778 items: Vec<Vec<TokenTree>>,
779 opts: &mut StructOptions,
780) -> Result<(), String> {
781 let StructOptions {
782 table,
783 external,
784 composites,
785 uniques,
786 fts,
787 fts_tokenize,
788 spatial,
789 } = opts;
790 for item in items {
791 match item.as_slice() {
792 [TokenTree::Ident(id), TokenTree::Group(g)]
793 if id.to_string() == "fts" && g.delimiter() == Delimiter::Parenthesis =>
794 {
795 let mut fts_items = vec![Vec::new()];
798 for tt in g.stream() {
799 match &tt {
800 TokenTree::Punct(p) if p.as_char() == ',' => fts_items.push(Vec::new()),
801 _ => fts_items.last_mut().expect("never empty").push(tt.clone()),
802 }
803 }
804 for item in fts_items.into_iter().filter(|i| !i.is_empty()) {
805 match item.as_slice() {
806 [TokenTree::Literal(lit)] => fts.push(string_literal(lit)?),
807 [
808 TokenTree::Ident(k),
809 TokenTree::Punct(eq),
810 TokenTree::Literal(lit),
811 ] if k.to_string() == "tokenize" && eq.as_char() == '=' => {
812 *fts_tokenize = Some(string_literal(lit)?);
813 }
814 other => {
815 return Err(format!(
816 "fts(…) expects column string literals and an optional \
817 tokenize = \"…\", found `{}`",
818 tokens_text(other)
819 ));
820 }
821 }
822 }
823 }
824 [TokenTree::Ident(id), TokenTree::Group(g)]
825 if id.to_string() == "spatial" && g.delimiter() == Delimiter::Parenthesis =>
826 {
827 let mut lat = None;
828 let mut lon = None;
829 let inner: Vec<TokenTree> = g.stream().into_iter().collect();
830 let mut j = 0;
831 while j + 2 < inner.len() + 1 {
832 match (&inner.get(j), &inner.get(j + 1), &inner.get(j + 2)) {
833 (
834 Some(TokenTree::Ident(k)),
835 Some(TokenTree::Punct(eq)),
836 Some(TokenTree::Literal(lit)),
837 ) if eq.as_char() == '=' => {
838 match k.to_string().as_str() {
839 "lat" => lat = Some(string_literal(lit)?),
840 "lon" => lon = Some(string_literal(lit)?),
841 other => {
842 return Err(format!(
843 "spatial(…) takes lat = \"…\" and lon = \"…\", found `{other}`"
844 ));
845 }
846 }
847 j += 3;
848 if matches!(inner.get(j), Some(TokenTree::Punct(p)) if p.as_char() == ',')
849 {
850 j += 1;
851 }
852 }
853 _ => return Err("spatial(…) takes lat = \"…\" and lon = \"…\"".into()),
854 }
855 }
856 match (lat, lon) {
857 (Some(lat), Some(lon)) => *spatial = Some((lat, lon)),
858 _ => return Err("spatial(…) needs BOTH lat = \"…\" and lon = \"…\"".into()),
859 }
860 }
861 [
862 TokenTree::Ident(id),
863 TokenTree::Punct(eq),
864 TokenTree::Literal(lit),
865 ] if id.to_string() == "table" && eq.as_char() == '=' => {
866 *table = Some(string_literal(lit)?);
867 }
868 [
869 TokenTree::Ident(id),
870 TokenTree::Punct(eq),
871 TokenTree::Literal(lit),
872 ] if id.to_string() == "external" && eq.as_char() == '=' => {
873 let alias = string_literal(lit)?;
874 if alias.is_empty() || !alias.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
875 {
876 return Err(format!(
877 "external = {alias:?} must be a plain SQL schema name (letters, digits, `_`)"
878 ));
879 }
880 *external = Some(alias);
881 }
882 [TokenTree::Ident(id), TokenTree::Group(g)]
883 if id.to_string() == "index" && g.delimiter() == Delimiter::Parenthesis =>
884 {
885 let mut cols = Vec::new();
886 for tt in g.stream() {
887 match &tt {
888 TokenTree::Literal(lit) => cols.push(string_literal(lit)?),
889 TokenTree::Punct(p) if p.as_char() == ',' => {}
890 other => {
891 return Err(format!(
892 "index(…) expects string literals, found `{other}`"
893 ));
894 }
895 }
896 }
897 composites.push(cols);
898 }
899 [TokenTree::Ident(id), TokenTree::Group(g)]
900 if id.to_string() == "unique" && g.delimiter() == Delimiter::Parenthesis =>
901 {
902 let mut cols = Vec::new();
903 for tt in g.stream() {
904 match &tt {
905 TokenTree::Literal(lit) => cols.push(string_literal(lit)?),
906 TokenTree::Punct(p) if p.as_char() == ',' => {}
907 other => {
908 return Err(format!(
909 "unique(…) expects string literals, found `{other}`"
910 ));
911 }
912 }
913 }
914 if cols.is_empty() {
915 return Err("unique(…) names at least one column".into());
916 }
917 uniques.push(cols);
918 }
919 other => {
920 return Err(format!(
921 "unknown #[model] option on the struct: `{}` (supported: table = \"…\", external = \"alias\", index(\"a\", \"b\"), unique(\"a\", \"b\"), fts(\"a\", \"b\"), spatial(lat = \"…\", lon = \"…\"))",
922 tokens_text(other)
923 ));
924 }
925 }
926 }
927 Ok(())
928}
929
930fn parse_field_options(items: Vec<Vec<TokenTree>>, f: &mut FieldDef) -> Result<(), String> {
931 for item in items {
932 match item.as_slice() {
933 [TokenTree::Ident(id)] => match id.to_string().as_str() {
934 "id" => f.key = true,
935 "unique" => f.unique = true,
936 "index" => f.indexed = true,
937 "transient" => f.transient = true,
938 "json" => f.json = true,
939 other => {
940 return Err(format!(
941 "unknown #[model] option on field `{}`: `{other}` (supported: id, unique, index, transient, json, column = \"…\", with = Codec)",
942 f.name
943 ));
944 }
945 },
946 [
947 TokenTree::Ident(id),
948 TokenTree::Punct(eq),
949 TokenTree::Literal(lit),
950 ] if id.to_string() == "column" && eq.as_char() == '=' => {
951 f.column = Some(string_literal(lit)?);
952 }
953 [TokenTree::Ident(id), TokenTree::Punct(eq), rest @ ..]
954 if id.to_string() == "with" && eq.as_char() == '=' && !rest.is_empty() =>
955 {
956 f.with = Some(tokens_text(rest));
957 }
958 [TokenTree::Ident(id), TokenTree::Group(g)]
959 if id.to_string() == "relation" && g.delimiter() == Delimiter::Parenthesis =>
960 {
961 f.relation = Some(parse_relation(g, &f.name)?);
962 }
963 [TokenTree::Ident(id), TokenTree::Group(g)]
964 if id.to_string() == "link" && g.delimiter() == Delimiter::Parenthesis =>
965 {
966 f.link = Some(parse_link(g, &f.name)?);
967 }
968 other => {
969 return Err(format!(
970 "unknown #[model] option on field `{}`: `{}`",
971 f.name,
972 tokens_text(other)
973 ));
974 }
975 }
976 }
977 Ok(())
978}
979
980fn parse_relation(g: &proc_macro::Group, field: &str) -> Result<RelationAttr, String> {
982 let mut items = vec![Vec::new()];
983 for tt in g.stream() {
984 match &tt {
985 TokenTree::Punct(p) if p.as_char() == ',' => items.push(Vec::new()),
986 _ => items.last_mut().expect("never empty").push(tt),
987 }
988 }
989 items.retain(|i| !i.is_empty());
990
991 let (mut target, mut inverse, mut delete, mut ordered, mut join) =
992 (None, None, None, None, None);
993 for item in items {
994 match item.as_slice() {
995 [TokenTree::Ident(k), TokenTree::Punct(eq), rest @ ..]
996 if eq.as_char() == '=' && !rest.is_empty() =>
997 {
998 match k.to_string().as_str() {
999 "target" => target = Some(tokens_text(rest)),
1000 "inverse" => inverse = Some(literal_str(rest, field)?),
1001 "delete" => delete = Some(literal_str(rest, field)?),
1002 "ordered" => ordered = Some(literal_str(rest, field)?),
1003 "join" => join = Some(literal_str(rest, field)?),
1004 other => {
1005 return Err(format!(
1006 "relation(…) on `{field}`: unknown option `{other}` (supported: \
1007 target = Type, inverse = \"field\", delete = \"…\", \
1008 ordered = \"field\", join = \"table\")"
1009 ));
1010 }
1011 }
1012 }
1013 [TokenTree::Ident(k)] if k.to_string() == "ordered" => {
1017 ordered = Some("position".into());
1018 }
1019 other => {
1020 return Err(format!(
1021 "relation(…) on `{field}`: expected `name = …`, found `{}`",
1022 tokens_text(other)
1023 ));
1024 }
1025 }
1026 }
1027 let Some(target) = target else {
1028 return Err(format!("relation(…) on `{field}` needs target = Type"));
1029 };
1030 let delete = delete.unwrap_or_else(|| "nullify".into());
1031 if !["nullify", "cascade", "deny"].contains(&delete.as_str()) {
1032 return Err(format!(
1033 "relation(…) on `{field}`: delete = {delete:?} — nullify, cascade, or deny"
1034 ));
1035 }
1036 if inverse.is_none() && join.is_none() {
1037 return Err(format!(
1038 "relation(…) on `{field}` needs inverse = \"field\" (the target's One<…> field) \
1039 — or join = \"table\" for a many-to-many"
1040 ));
1041 }
1042 Ok(RelationAttr {
1043 target,
1044 inverse,
1045 delete,
1046 ordered,
1047 join,
1048 })
1049}
1050
1051fn parse_link(g: &proc_macro::Group, field: &str) -> Result<LinkAttr, String> {
1055 let mut items = vec![Vec::new()];
1056 for tt in g.stream() {
1057 match &tt {
1058 TokenTree::Punct(p) if p.as_char() == ',' => items.push(Vec::new()),
1059 _ => items.last_mut().expect("never empty").push(tt),
1060 }
1061 }
1062 items.retain(|i| !i.is_empty());
1063 let (mut target, mut local, mut remote) = (None, None, None);
1064 for item in items {
1065 match item.as_slice() {
1066 [TokenTree::Ident(k), TokenTree::Punct(eq), rest @ ..]
1067 if eq.as_char() == '=' && !rest.is_empty() =>
1068 {
1069 match k.to_string().as_str() {
1070 "target" => target = Some(tokens_text(rest)),
1071 "local" => local = Some(literal_str(rest, field)?),
1072 "remote" => remote = Some(literal_str(rest, field)?),
1073 other => {
1074 return Err(format!(
1075 "link(…) on `{field}`: unknown option `{other}` (supported: \
1076 target = Type, local = \"column\", remote = \"column\")"
1077 ));
1078 }
1079 }
1080 }
1081 other => {
1082 return Err(format!(
1083 "link(…) on `{field}`: expected `name = …`, found `{}`",
1084 tokens_text(other)
1085 ));
1086 }
1087 }
1088 }
1089 match (target, local, remote) {
1090 (Some(target), Some(local), Some(remote)) => Ok(LinkAttr {
1091 target,
1092 local,
1093 remote,
1094 }),
1095 _ => Err(format!(
1096 "link(…) on `{field}` needs target = Type, local = \"column\", and remote = \"column\""
1097 )),
1098 }
1099}
1100
1101fn literal_str(rest: &[TokenTree], field: &str) -> Result<String, String> {
1102 match rest {
1103 [TokenTree::Literal(l)] => string_literal(l),
1104 other => Err(format!(
1105 "relation(…) on `{field}`: expected a string literal, found `{}`",
1106 tokens_text(other)
1107 )),
1108 }
1109}
1110
1111fn string_literal(lit: &proc_macro::Literal) -> Result<String, String> {
1115 let s = lit.to_string();
1116 if let Some(raw) = s.strip_prefix('r') {
1117 let hashes = raw.len() - raw.trim_start_matches('#').len();
1118 let body = &raw[hashes..raw.len() - hashes];
1119 if hashes * 2 + 2 <= raw.len() && body.starts_with('"') && body.ends_with('"') {
1120 return Ok(body[1..body.len() - 1].to_string());
1121 }
1122 return Err(format!("expected a string literal, found `{s}`"));
1123 }
1124 if s.len() < 2 || !s.starts_with('"') || !s.ends_with('"') {
1125 return Err(format!("expected a string literal, found `{s}`"));
1126 }
1127 let mut out = String::with_capacity(s.len());
1128 let mut chars = s[1..s.len() - 1].chars();
1129 while let Some(ch) = chars.next() {
1130 if ch != '\\' {
1131 out.push(ch);
1132 continue;
1133 }
1134 match chars.next() {
1135 Some('"') => out.push('"'),
1136 Some('\\') => out.push('\\'),
1137 Some('\'') => out.push('\''),
1138 Some('n') => out.push('\n'),
1139 Some('r') => out.push('\r'),
1140 Some('t') => out.push('\t'),
1141 Some('0') => out.push('\0'),
1142 Some('x') => {
1143 let hex: String = chars.by_ref().take(2).collect();
1144 let code = u8::from_str_radix(&hex, 16)
1145 .map_err(|_| format!("bad escape `\\x{hex}` in {s}"))?;
1146 out.push(code as char);
1147 }
1148 Some('u') => {
1149 if chars.next() != Some('{') {
1150 return Err(format!("bad escape `\\u` in {s}"));
1151 }
1152 let hex: String = chars.by_ref().take_while(|c| *c != '}').collect();
1153 let code = u32::from_str_radix(&hex, 16)
1154 .ok()
1155 .and_then(char::from_u32)
1156 .ok_or_else(|| format!("bad escape `\\u{{{hex}}}` in {s}"))?;
1157 out.push(code);
1158 }
1159 Some('\n') => {
1161 let rest = chars.as_str();
1162 let trimmed = rest.trim_start();
1163 chars = trimmed.chars();
1164 let _ = rest;
1165 }
1166 other => {
1167 return Err(format!(
1168 "unsupported escape `\\{}` in {s}",
1169 other.map(String::from).unwrap_or_default()
1170 ));
1171 }
1172 }
1173 }
1174 Ok(out)
1175}
1176
1177fn check_name(what: &str, name: &str) -> Result<(), String> {
1180 if name.is_empty() {
1181 return Err(format!("Model: the {what} name is empty"));
1182 }
1183 if name.contains('\0') {
1184 return Err(format!(
1185 "Model: the {what} name {name:?} contains a NUL, which SQL cannot carry"
1186 ));
1187 }
1188 Ok(())
1189}
1190
1191fn tokens_text(tokens: &[TokenTree]) -> String {
1192 tokens.iter().cloned().collect::<TokenStream>().to_string()
1193}
1194
1195fn parse_fields(body: TokenStream) -> Result<Vec<FieldDef>, String> {
1199 let mut fields = Vec::new();
1200 let mut chunk: Vec<TokenTree> = Vec::new();
1201 let mut angle_depth = 0i32;
1202 let mut prev_dash = false;
1203
1204 for tt in body {
1205 match &tt {
1206 TokenTree::Punct(p) if p.as_char() == '<' => {
1207 angle_depth += 1;
1208 chunk.push(tt);
1209 }
1210 TokenTree::Punct(p) if p.as_char() == '>' && !prev_dash => {
1212 angle_depth = (angle_depth - 1).max(0);
1213 chunk.push(tt);
1214 }
1215 TokenTree::Punct(p) if p.as_char() == ',' && angle_depth == 0 => {
1216 if !chunk.is_empty() {
1217 fields.push(parse_one(&chunk)?);
1218 chunk.clear();
1219 }
1220 }
1221 _ => chunk.push(tt),
1222 }
1223 prev_dash = matches!(
1224 chunk.last(),
1225 Some(TokenTree::Punct(p)) if p.as_char() == '-'
1226 );
1227 }
1228 if !chunk.is_empty() {
1229 fields.push(parse_one(&chunk)?);
1230 }
1231 Ok(fields)
1232}
1233
1234fn is_blob_type(ty: &str) -> bool {
1236 let last = ty.rsplit("::").next().unwrap_or(ty).trim();
1237 last == "Blob"
1238}
1239
1240fn parse_one(chunk: &[TokenTree]) -> Result<FieldDef, String> {
1241 let mut i = 0;
1242 let mut f = FieldDef::default();
1243 let mut deferred: Vec<Vec<Vec<TokenTree>>> = Vec::new();
1244
1245 while i < chunk.len() {
1248 match &chunk[i] {
1249 TokenTree::Punct(p) if p.as_char() == '#' => {
1250 if let Some(TokenTree::Group(g)) = chunk.get(i + 1) {
1251 if let Some(items) = attr_items(g, "obs") {
1252 for item in items {
1253 match item.as_slice() {
1254 [TokenTree::Ident(id)] if id.to_string() == "key" => f.key = true,
1255 [TokenTree::Ident(id)] if id.to_string() == "skip" => {
1256 f.skip = true;
1257 }
1258 other => {
1259 return Err(format!(
1260 "unknown #[obs] option: `{}` (supported: key, skip)",
1261 tokens_text(other)
1262 ));
1263 }
1264 }
1265 }
1266 } else if let Some(items) = attr_items(g, "model") {
1267 deferred.push(items);
1268 }
1269 i += 2;
1270 continue;
1271 }
1272 return Err("malformed attribute on a field".into());
1273 }
1274 _ => break,
1275 }
1276 }
1277
1278 if let Some(TokenTree::Ident(id)) = chunk.get(i)
1280 && id.to_string() == "pub"
1281 {
1282 i += 1;
1283 if let Some(TokenTree::Group(g)) = chunk.get(i)
1284 && g.delimiter() == Delimiter::Parenthesis
1285 {
1286 i += 1;
1287 }
1288 }
1289
1290 f.name = match chunk.get(i) {
1291 Some(TokenTree::Ident(id)) => id.to_string(),
1292 _ => return Err("expected a field name".into()),
1293 };
1294 i += 1;
1295 match chunk.get(i) {
1296 Some(TokenTree::Punct(p)) if p.as_char() == ':' => i += 1,
1297 _ => return Err(format!("expected `:` after field `{}`", f.name)),
1298 }
1299
1300 f.ty = tokens_text(&chunk[i..]);
1303 if f.ty.is_empty() {
1304 return Err(format!("field `{}` has no type", f.name));
1305 }
1306 f.lazy = is_blob_type(&f.ty);
1307
1308 for items in deferred {
1309 parse_field_options(items, &mut f)?;
1310 }
1311 Ok(f)
1312}