-
Notifications
You must be signed in to change notification settings - Fork 0
/
types.rs
1657 lines (1511 loc) · 58.4 KB
/
types.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! A basic type system for BigQuery-compatible SQL.
//!
//! We support most basic BigQuery types, including arrays and structs. We also
//! have representations for table types and function types. Function types may
//! have type variables, which we use to represent things like `Fn<T>(ARRAY<T>,
//! INT64) -> T`.
//!
//! Function types may be overloaded, to support things like addition:
//! `Fn(INT64, INT64) -> INT64 | Fn(FLOAT64, FLOAT64) -> FLOAT64`.
//!
//! We try to get some of the fiddly details right, like the fact that BigQuery
//! does not support `ARRAY<ARRAY<T>>`, only `ARRAY<STRUCT<ARRAY<T>>>`, and that
//! `STRUCT` fields have optional names.
use std::{collections::HashSet, fmt};
use peg::{error::ParseError, str::LineCol};
use crate::{
ast::{self, Name},
drivers::bigquery::BigQueryName,
errors::{format_err, Error, Result},
known_files::{FileId, KnownFiles},
scope::{ColumnSet, ColumnSetColumn, ColumnSetColumnName},
tokenizer::{Ident, Keyword, PseudoKeyword, Punct, Span, Spanned},
unification::{UnificationTable, Unify},
util::is_c_ident,
};
/// Sometimes we want concrete types, and sometimes we want types with type
/// variables. This trait convers both those cases.
pub trait TypeVarSupport: Clone + fmt::Display + PartialEq + Sized {
/// Convert a [`TypeVar`] into a [`SimpleType`], if possible.
fn simple_type_from_type_var(tv: TypeVar) -> Result<SimpleType<Self>, &'static str>;
}
/// This type can never be instantiated. We use this to represent a type variable with
/// all type variables resolved.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ResolvedTypeVarsOnly {}
impl TypeVarSupport for ResolvedTypeVarsOnly {
fn simple_type_from_type_var(_tv: TypeVar) -> Result<SimpleType<Self>, &'static str> {
// This will be a parser error with `"expected "` prepended. So it's
// hard to word well.
Err("something other than a type variable")
}
}
impl fmt::Display for ResolvedTypeVarsOnly {
fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
unreachable!()
}
}
/// A type variable.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct TypeVar {
name: String,
}
impl TypeVar {
/// Create a new type variable.
pub fn new(name: impl Into<String>) -> Result<Self> {
Self::new_helper(name.into())
}
/// Helper for `new` that has no type parameter, and therefore only gets
/// compiled once.
fn new_helper(name: String) -> Result<Self> {
if !is_c_ident(&name) {
return Err(format_err!("invalid type variable name: {}", name));
}
if !name.chars().next().unwrap().is_ascii_uppercase() {
return Err(format_err!(
"type variable name must start with an uppercase letter: {}",
name
));
}
Ok(Self { name })
}
}
impl TypeVarSupport for TypeVar {
fn simple_type_from_type_var(tv: TypeVar) -> Result<SimpleType<Self>, &'static str> {
Ok(SimpleType::Parameter(tv))
}
}
impl fmt::Display for TypeVar {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "?{}", self.name)?;
Ok(())
}
}
/// Basic types.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Type<TV: TypeVarSupport = ResolvedTypeVarsOnly> {
/// A value which may appear as a function argument.
Argument(ArgumentType<TV>),
/// The type of a table, as seen in `CREATE TABLE` statements, or
/// as returned from a sub-`SELECT`, or as passed to `UNNEST`.
Table(TableType),
/// A function type.
Function(FunctionType),
}
impl<TV: TypeVarSupport> Type<TV> {
/// Convert this type into an [`ArgumentType`], if possible.
pub fn try_as_argument_type(&self, spanned: &dyn Spanned) -> Result<&ArgumentType<TV>> {
match self {
Type::Argument(t) => Ok(t),
_ => Err(Error::annotated(
format!("expected argument type, found {}", self),
spanned.span(),
"type mismatch",
)),
}
}
/// Convert this type into a [`TableType`], if possible.
pub fn try_as_table_type<'ty>(&'ty self, spanned: &dyn Spanned) -> Result<&'ty TableType> {
match self {
Type::Table(t) => Ok(t),
_ => Err(Error::annotated(
format!("expected table type, found {}", self),
spanned.span(),
"type mismatch",
)),
}
}
/// Convert this type into a [`FunctionType`], if possible.
pub fn try_as_function_type(&self, spanned: &dyn Spanned) -> Result<&FunctionType> {
match self {
Type::Function(t) => Ok(t),
_ => Err(Error::annotated(
format!("expected function type, found {}", self),
spanned.span(),
"type mismatch",
)),
}
}
}
impl<TV: TypeVarSupport> fmt::Display for Type<TV> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Type::Argument(v) => write!(f, "{}", v),
Type::Table(t) => write!(f, "{}", t),
Type::Function(func) => write!(f, "{}", func),
}
}
}
/// An argument type.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ArgumentType<TV: TypeVarSupport = ResolvedTypeVarsOnly> {
/// A value type.
Value(ValueType<TV>),
/// An aggregating value type. Note that we can nest aggregating types.
Aggregating(Box<ArgumentType<TV>>),
}
impl<TV: TypeVarSupport> ArgumentType<TV> {
/// Create a NULL type.
pub fn null() -> Self {
ArgumentType::Value(ValueType::Simple(SimpleType::Null))
}
/// Create a BOOL type.
pub fn bool() -> Self {
ArgumentType::Value(ValueType::Simple(SimpleType::Bool))
}
/// Create an INT64 type.
pub fn int64() -> Self {
ArgumentType::Value(ValueType::Simple(SimpleType::Int64))
}
/// Expect a [`ValueType`].
pub fn expect_value_type(&self, spanned: &dyn Spanned) -> Result<&ValueType<TV>> {
match self {
ArgumentType::Value(t) => Ok(t),
ArgumentType::Aggregating(_) => Err(Error::annotated(
format!("expected value type, found aggregate type {}", self),
spanned.span(),
"type mismatch",
)),
}
}
/// Expect a [`SimpleType`].
pub fn expect_simple_type(&self, spanned: &dyn Spanned) -> Result<&SimpleType<TV>> {
match self {
ArgumentType::Value(ValueType::Simple(t)) => Ok(t),
_ => Err(Error::annotated(
format!("expected simple type, found {}", self),
spanned.span(),
"type mismatch",
)),
}
}
/// Expect a [`StructType`].
pub fn expect_struct_type(&self, spanned: &dyn Spanned) -> Result<&StructType<TV>> {
match self {
ArgumentType::Value(ValueType::Simple(SimpleType::Struct(t))) => Ok(t),
_ => Err(Error::annotated(
format!("expected struct type, found {}", self),
spanned.span(),
"type mismatch",
)),
}
}
/// Expect an [`ArrayType`].
pub fn expect_array_type(&self, spanned: &dyn Spanned) -> Result<&ValueType<TV>> {
match self {
ArgumentType::Value(t @ ValueType::Array(_)) => Ok(t),
_ => Err(Error::annotated(
format!("expected array type, found {}", self),
spanned.span(),
"type mismatch",
)),
}
}
/// Expect an [`ArrayType`] and return the element type.
pub fn expect_array_type_returning_elem_type(
&self,
spanned: &dyn Spanned,
) -> Result<&SimpleType<TV>> {
match self {
ArgumentType::Value(ValueType::Array(t)) => Ok(t),
_ => Err(Error::annotated(
format!("expected array type, found {}", self),
spanned.span(),
"type mismatch",
)),
}
}
/// Is this a subtype of `other`?
pub fn is_subtype_of(&self, other: &ArgumentType<TV>) -> bool {
// Value types can't be subtypes of aggregating types or vice versa,
// at least until we discover otherwise.
match (self, other) {
(ArgumentType::Value(a), ArgumentType::Value(b)) => a.is_subtype_of(b),
(ArgumentType::Aggregating(a), ArgumentType::Aggregating(b)) => a.is_subtype_of(b),
_ => false,
}
}
/// Return an error if we are not a subtype of `other`.
pub fn expect_subtype_of(&self, other: &ArgumentType<TV>, spanned: &dyn Spanned) -> Result<()> {
if !self.is_subtype_of(other) {
return Err(Error::annotated(
format!("expected {}, found {}", other, self),
spanned.span(),
"type mismatch",
));
}
Ok(())
}
/// Find a common supertype of two types. Returns `None` if the only common
/// super type would be top (⊤), which isn't part of our type system.
pub fn common_supertype<'a>(&'a self, other: &'a ArgumentType<TV>) -> Option<ArgumentType<TV>> {
match (self, other) {
// Recurse if structure matches.
(ArgumentType::Value(a), ArgumentType::Value(b)) => {
Some(ArgumentType::Value(a.common_supertype(b)?))
}
(ArgumentType::Aggregating(a), ArgumentType::Aggregating(b)) => {
Some(ArgumentType::Aggregating(Box::new(a.common_supertype(b)?)))
}
_ => None,
}
}
}
impl Unify for ArgumentType<TypeVar> {
type Resolved = ArgumentType<ResolvedTypeVarsOnly>;
fn unify(
&self,
other: &Self::Resolved,
table: &mut UnificationTable,
spanned: &dyn Spanned,
) -> Result<Self::Resolved> {
match (self, other) {
(ArgumentType::Value(a), ArgumentType::Value(b)) => {
Ok(ArgumentType::Value(a.unify(b, table, spanned)?))
}
(ArgumentType::Aggregating(a), ArgumentType::Aggregating(b)) => Ok(
ArgumentType::Aggregating(Box::new(a.unify(b, table, spanned)?)),
),
_ => Err(Error::annotated(
format!("cannot unify {} and {}", self, other),
spanned.span(),
"type mismatch",
)),
}
}
fn resolve(&self, table: &UnificationTable, spanned: &dyn Spanned) -> Result<Self::Resolved> {
match self {
ArgumentType::Value(t) => Ok(ArgumentType::Value(t.resolve(table, spanned)?)),
ArgumentType::Aggregating(t) => Ok(ArgumentType::Aggregating(Box::new(
t.resolve(table, spanned)?,
))),
}
}
}
impl<TV: TypeVarSupport> fmt::Display for ArgumentType<TV> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ArgumentType::Value(v) => write!(f, "{}", v),
ArgumentType::Aggregating(v) => write!(f, "Agg<{}>", v),
}
}
}
/// An unnested [`ValueType`].
#[derive(Clone, Debug)]
pub enum Unnested {
/// This type unnests to a single anonymous column.
AnonymousColumn(TableType),
/// This type unnests to a table with named columns.
NamedColumns(TableType),
}
impl From<Unnested> for TableType {
fn from(unnested: Unnested) -> Self {
match unnested {
Unnested::AnonymousColumn(t) => t,
Unnested::NamedColumns(t) => t,
}
}
}
/// A value type.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ValueType<TV: TypeVarSupport = ResolvedTypeVarsOnly> {
/// Any value type which may appear in an array.
Simple(SimpleType<TV>),
/// An array of values. BigQuery does not support nesting arrays, although
/// you can have `ARRAY<STRUCT<ARRAY<T>>>` if you wish.
Array(SimpleType<TV>),
}
impl<TV: TypeVarSupport> ValueType<TV> {
/// Is this a subtype of `other`?
pub fn is_subtype_of(&self, other: &ValueType<TV>) -> bool {
match (self, other) {
// Every type is a subtype of itself.
(a, b) if a == b => true,
// Bottom is a subtype of every type, but no other type is a
// subtype of bottom.
(ValueType::Simple(SimpleType::Bottom), _) => true,
(_, ValueType::Simple(SimpleType::Bottom)) => false,
// Null is a subtype of every type except bottom.
(ValueType::Simple(SimpleType::Null), _) => true,
// Integers are a subtype of floats.
(ValueType::Simple(SimpleType::Int64), ValueType::Simple(SimpleType::Float64)) => true,
// An ARRAY<⊥> is a subset of any other array type. However,
// an ARRAY<INT64> is not a subtype of ARRAY<FLOAT64>, as
(ValueType::Array(SimpleType::Bottom), ValueType::Array(_)) => true,
// Structs may be subtypes of other structs.
(
ValueType::Simple(SimpleType::Struct(a)),
ValueType::Simple(SimpleType::Struct(b)),
) => a.is_subtype_of(b),
// Otherwise, assume it isn't a subtype.
_ => false,
}
}
/// Return an error if we are not a subtype of `other`.
#[allow(dead_code)]
pub fn expect_subtype_of(&self, other: &ValueType<TV>, spanned: &dyn Spanned) -> Result<()> {
if !self.is_subtype_of(other) {
return Err(Error::annotated(
format!("expected {}, found {}", other, self),
spanned.span(),
"type mismatch",
));
}
Ok(())
}
/// Compute the least common supertype of two types. Returns `None` if the
/// only common super type would be top (⊤), which isn't part of our type
/// system.
///
/// For some nice theoretical terminology, see [this
/// page](https://orc.csres.utexas.edu/documentation/html/refmanual/ref.types.subtyping.html).
pub fn common_supertype<'a>(&'a self, other: &'a ValueType<TV>) -> Option<ValueType<TV>> {
if self.is_subtype_of(other) {
Some(other.clone())
} else if other.is_subtype_of(self) {
Some(self.clone())
} else {
None
}
}
/// Expect this type to be inhabited by at least one value.
pub fn expect_inhabited(&self, spanned: &dyn Spanned) -> Result<()> {
match self {
ValueType::Simple(SimpleType::Bottom) => Err(Error::annotated(
"cannot construct a value of this type",
spanned.span(),
"no valid values",
)),
_ => Ok(()),
}
}
/// Expect this value type to be a struct type.
pub fn expect_struct_type(&self, spanned: &dyn Spanned) -> Result<&StructType<TV>> {
match self {
ValueType::Simple(SimpleType::Struct(s)) => Ok(s),
_ => Err(Error::annotated(
format!("expected struct type, found {}", self),
spanned.span(),
"type mismatch",
)),
}
}
}
impl ValueType<ResolvedTypeVarsOnly> {
/// Unnest an array type into a table type, according to [Google's rules][unnest].
///
/// [unnest]: https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#unnest_operator
pub fn unnest(&self, spanned: &dyn Spanned) -> Result<Unnested> {
match self {
// Structs unnest to tables with the same columns.
//
// TODO: JSON, too, if we ever support it.
ValueType::Array(SimpleType::Struct(s)) => {
Ok(Unnested::NamedColumns(s.to_table_type()))
}
// Other types unnest to tables with a single anonymous column.
ValueType::Array(elem_ty) => Ok(Unnested::AnonymousColumn(TableType {
columns: vec![ColumnType {
name: None,
ty: ArgumentType::Value(ValueType::Simple(elem_ty.clone())),
not_null: false,
}],
})),
_ => Err(Error::annotated(
"cannot unnest a non-array",
spanned.span(),
"type mismatch",
)),
}
}
}
impl Unify for ValueType<TypeVar> {
type Resolved = ValueType<ResolvedTypeVarsOnly>;
fn unify(
&self,
other: &Self::Resolved,
table: &mut UnificationTable,
spanned: &dyn Spanned,
) -> Result<Self::Resolved> {
match (self, other) {
// Unify an array with with a TypeVar.
(ValueType::Simple(SimpleType::Parameter(var)), array_ty @ ValueType::Array(_)) => {
table
.update(var.clone(), ArgumentType::Value(array_ty.clone()), spanned)?
.expect_value_type(spanned)
.cloned()
}
(ValueType::Simple(a), ValueType::Simple(b)) => {
Ok(ValueType::Simple(a.unify(b, table, spanned)?))
}
(ValueType::Array(a), ValueType::Array(b)) => {
Ok(ValueType::Array(a.unify(b, table, spanned)?))
}
_ => {
// To handle things like passing a `NULL` value to a function
// expecting an `ARRAY<INT64>`, we need to check subtyping.
if let Ok(rself) = self.resolve(table, spanned) {
if other.is_subtype_of(&rself) {
return Ok(rself);
}
}
Err(Error::annotated(
format!("cannot unify {} and {}", self, other),
spanned.span(),
"type mismatch",
))
}
}
}
fn resolve(&self, table: &UnificationTable, spanned: &dyn Spanned) -> Result<Self::Resolved> {
match self {
// TODO: This is duplicated from SimpleType, because we may have
// bound a type variable to an array type.
ValueType::Simple(SimpleType::Parameter(var)) => table
.get(var.clone())
.ok_or_else(|| {
Error::annotated(
format!("cannot resolve type variable: {}", var),
spanned.span(),
"unbound type variable",
)
})?
.expect_value_type(spanned)
.cloned(),
ValueType::Simple(t) => Ok(ValueType::Simple(t.resolve(table, spanned)?)),
ValueType::Array(t) => Ok(ValueType::Array(t.resolve(table, spanned)?)),
}
}
}
impl TryFrom<ValueType> for ast::DataType {
type Error = Error;
fn try_from(value: ValueType) -> Result<Self> {
match value {
ValueType::Simple(t) => t.try_into(),
ValueType::Array(t) => Ok(ast::DataType::Array {
array_token: Keyword::new("ARRAY", Span::Unknown),
lt: Punct::new("<", Span::Unknown),
data_type: Box::new(t.try_into()?),
gt: Punct::new(">", Span::Unknown),
}),
}
}
}
impl<TV: TypeVarSupport> fmt::Display for ValueType<TV> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ValueType::Simple(s) => write!(f, "{}", s),
ValueType::Array(t) => write!(f, "ARRAY<{}>", t),
}
}
}
/// A simple type, which can appear in an array.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SimpleType<TV: TypeVarSupport = ResolvedTypeVarsOnly> {
Bool,
/// The "bottom" type "⊥", which contains no values, and is a subtype of
/// all other types. The expression `ARRAY[]` has the type `ARRAY<⊥>`,
/// because it can be used as an array of any type.
Bottom,
Bytes,
Date,
/// This type can be used a function argument, but does not exist as an
/// actual value, as far as I can tell. It's part of the grammar for
/// `DATE_TRUNC`, `DATE_DIFF`, etc. It takes "values" like `DAY` and `YEAR`.
Datepart,
Datetime,
Float64,
Geography,
Int64,
Interval,
/// The NULL type. This is somewhat similar to `Bottom`. It's a subtype of
/// almost every type. It contains a single value, `NULL`.
Null,
Numeric,
String,
Time,
Timestamp,
Struct(StructType<TV>),
Parameter(TV),
}
impl Unify for SimpleType<TypeVar> {
type Resolved = SimpleType<ResolvedTypeVarsOnly>;
fn unify(
&self,
other: &Self::Resolved,
table: &mut UnificationTable,
spanned: &dyn Spanned,
) -> Result<Self::Resolved> {
match (self, other) {
(SimpleType::Parameter(var), matched) => table
.update(
var.clone(),
ArgumentType::Value(ValueType::Simple(matched.clone())),
spanned,
)?
.expect_simple_type(spanned)
.cloned(),
(SimpleType::Bool, SimpleType::Bool) => Ok(SimpleType::Bool),
(SimpleType::Bottom, SimpleType::Bottom) => Ok(SimpleType::Bottom),
(SimpleType::Bytes, SimpleType::Bytes) => Ok(SimpleType::Bytes),
(SimpleType::Date, SimpleType::Date) => Ok(SimpleType::Date),
(SimpleType::Datepart, SimpleType::Datepart) => Ok(SimpleType::Datepart),
(SimpleType::Datetime, SimpleType::Datetime) => Ok(SimpleType::Datetime),
(SimpleType::Float64, SimpleType::Float64) => Ok(SimpleType::Float64),
(SimpleType::Geography, SimpleType::Geography) => Ok(SimpleType::Geography),
(SimpleType::Int64, SimpleType::Int64) => Ok(SimpleType::Int64),
(SimpleType::Interval, SimpleType::Interval) => Ok(SimpleType::Interval),
(SimpleType::Numeric, SimpleType::Numeric) => Ok(SimpleType::Numeric),
(SimpleType::Null, SimpleType::Null) => Ok(SimpleType::Null),
(SimpleType::String, SimpleType::String) => Ok(SimpleType::String),
(SimpleType::Time, SimpleType::Time) => Ok(SimpleType::Time),
(SimpleType::Timestamp, SimpleType::Timestamp) => Ok(SimpleType::Timestamp),
(SimpleType::Struct(a), SimpleType::Struct(b)) => {
Ok(SimpleType::Struct(a.unify(b, table, spanned)?))
}
_ => {
// To handle things like passing a `INT64` value to a function
// expecting an `FLOAT64`, we need to check subtyping.
if let Ok(rself) = self.resolve(table, spanned) {
// TODO: We shouldn't need to use wrappers here.
if ValueType::Simple(other.clone())
.is_subtype_of(&ValueType::Simple(rself.clone()))
{
return Ok(rself);
}
}
Err(Error::annotated(
format!("cannot unify {} and {}", self, other),
spanned.span(),
"type mismatch",
))
}
}
}
fn resolve(&self, table: &UnificationTable, spanned: &dyn Spanned) -> Result<Self::Resolved> {
match self {
SimpleType::Bool => Ok(SimpleType::Bool),
SimpleType::Bottom => Ok(SimpleType::Bottom),
SimpleType::Bytes => Ok(SimpleType::Bytes),
SimpleType::Date => Ok(SimpleType::Date),
SimpleType::Datepart => Ok(SimpleType::Datepart),
SimpleType::Datetime => Ok(SimpleType::Datetime),
SimpleType::Float64 => Ok(SimpleType::Float64),
SimpleType::Geography => Ok(SimpleType::Geography),
SimpleType::Int64 => Ok(SimpleType::Int64),
SimpleType::Interval => Ok(SimpleType::Interval),
SimpleType::Numeric => Ok(SimpleType::Numeric),
SimpleType::Null => Ok(SimpleType::Null),
SimpleType::String => Ok(SimpleType::String),
SimpleType::Time => Ok(SimpleType::Time),
SimpleType::Timestamp => Ok(SimpleType::Timestamp),
SimpleType::Struct(s) => Ok(SimpleType::Struct(s.resolve(table, spanned)?)),
SimpleType::Parameter(var) => table
.get(var.clone())
.ok_or_else(|| {
Error::annotated(
format!("cannot resolve type variable: {}", var),
spanned.span(),
"unbound type variable",
)
})?
.expect_simple_type(spanned)
.cloned(),
}
}
}
impl<TV: TypeVarSupport> fmt::Display for SimpleType<TV> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SimpleType::Bool => write!(f, "BOOL"),
SimpleType::Bottom => write!(f, "⊥"),
SimpleType::Bytes => write!(f, "BYTES"),
SimpleType::Date => write!(f, "DATE"),
SimpleType::Datepart => write!(f, "DATEPART"),
SimpleType::Datetime => write!(f, "DATETIME"),
SimpleType::Float64 => write!(f, "FLOAT64"),
SimpleType::Geography => write!(f, "GEOGRAPHY"),
SimpleType::Int64 => write!(f, "INT64"),
SimpleType::Interval => write!(f, "INTERVAL"),
SimpleType::Numeric => write!(f, "NUMERIC"),
SimpleType::Null => write!(f, "NULL"),
SimpleType::String => write!(f, "STRING"),
SimpleType::Time => write!(f, "TIME"),
SimpleType::Timestamp => write!(f, "TIMESTAMP"),
SimpleType::Struct(s) => write!(f, "{}", s),
SimpleType::Parameter(t) => write!(f, "{}", t),
}
}
}
impl TryFrom<SimpleType> for ast::DataType {
type Error = Error;
fn try_from(value: SimpleType) -> Result<Self> {
let pk = |s| PseudoKeyword::new(s, Span::Unknown);
match value {
SimpleType::Bool => Ok(ast::DataType::Bool(pk("BOOL"))),
SimpleType::Bottom => Err(format_err!(
"cannot convert unknown type to a printable type"
)),
SimpleType::Bytes => Ok(ast::DataType::Bytes(pk("BYTES"))),
SimpleType::Date => Ok(ast::DataType::Date(pk("DATE"))),
SimpleType::Datepart => Err(format_err!(
"cannot convert datepart type to a printable type"
)),
SimpleType::Datetime => Ok(ast::DataType::Datetime(pk("DATETIME"))),
SimpleType::Float64 => Ok(ast::DataType::Float64(pk("FLOAT64"))),
SimpleType::Geography => Ok(ast::DataType::Geography(pk("GEOGRAPHY"))),
SimpleType::Int64 => Ok(ast::DataType::Int64(pk("INT64"))),
SimpleType::Interval => Err(format_err!(
"cannot convert interval type to a printable type"
)),
SimpleType::Null => Err(format_err!(
"cannot convert unknown type to a printable type"
)),
SimpleType::Numeric => Ok(ast::DataType::Numeric(pk("NUMERIC"))),
SimpleType::String => Ok(ast::DataType::String(pk("STRING"))),
SimpleType::Time => Ok(ast::DataType::Time(pk("TIME"))),
SimpleType::Timestamp => Ok(ast::DataType::Timestamp(pk("TIMESTAMP"))),
SimpleType::Struct(s) => s.try_into(),
SimpleType::Parameter(_) => {
unreachable!("SimpleType::Parameter should contain no values")
}
}
}
}
/// A struct type.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StructType<TV: TypeVarSupport = ResolvedTypeVarsOnly> {
pub fields: Vec<StructElementType<TV>>,
}
impl<TV: TypeVarSupport> StructType<TV> {
/// Get the type of a field, or raise an error if the field does not exist.
pub fn expect_field(&self, name: &Name) -> Result<&ValueType<TV>> {
for field in &self.fields {
if let Some(field_name) = &field.name {
if Name::from(field_name.clone()) == *name {
return Ok(&field.ty);
}
}
}
Err(Error::annotated(
format!("no such field {} in {}", name.unescaped_bigquery(), self),
name.span(),
"no such field",
))
}
/// Is this a subtype of `other`?
pub fn is_subtype_of(&self, other: &StructType<TV>) -> bool {
// We are a subtype of `other` if we have the same fields, and each of
// our fields is a subtype of the corresponding field in `other`.
if self.fields.len() != other.fields.len() {
return false;
}
for (a, b) in self.fields.iter().zip(&other.fields) {
if !a.is_subtype_of(b) {
return false;
}
}
true
}
/// Return an error if we are not a subtype of `other`.
pub fn expect_subtype_of(&self, other: &StructType<TV>, spanned: &dyn Spanned) -> Result<()> {
if !self.is_subtype_of(other) {
return Err(Error::annotated(
format!("expected {}, found {}", other, self),
spanned.span(),
"type mismatch",
));
}
Ok(())
}
}
impl StructType<ResolvedTypeVarsOnly> {
/// Convert to a `TableType`.
pub fn to_table_type(&self) -> TableType {
TableType {
columns: self
.fields
.iter()
.map(|field| ColumnType {
name: field.name.clone(),
ty: ArgumentType::Value(field.ty.clone()),
not_null: false,
})
.collect(),
}
}
}
impl Unify for StructType<TypeVar> {
type Resolved = StructType<ResolvedTypeVarsOnly>;
fn unify(
&self,
other: &Self::Resolved,
_table: &mut UnificationTable,
spanned: &dyn Spanned,
) -> Result<Self::Resolved> {
// This isn't particularly complicated, but until we have an actual use
// case for it, it's better not to risk getting it _almost_ right.
Err(Error::annotated(
format!("cannot unify {} and {}", self, other),
spanned.span(),
"not yet implemented",
))
}
fn resolve(&self, table: &UnificationTable, spanned: &dyn Spanned) -> Result<Self::Resolved> {
let mut fields = Vec::new();
for field in &self.fields {
let ty = field.ty.resolve(table, spanned)?;
fields.push(StructElementType {
name: field.name.clone(),
ty,
});
}
Ok(StructType { fields })
}
}
impl TryFrom<StructType> for ast::DataType {
type Error = Error;
fn try_from(value: StructType) -> Result<Self> {
let mut fields = ast::NodeVec::new(",");
for field in value.fields {
fields.push(field.try_into()?);
}
Ok(ast::DataType::Struct {
struct_token: Keyword::new("STRUCT", Span::Unknown),
lt: Punct::new("<", Span::Unknown),
fields,
gt: Punct::new(">", Span::Unknown),
})
}
}
impl<TV: TypeVarSupport> fmt::Display for StructType<TV> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "STRUCT<")?;
for (i, field) in self.fields.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{}", field)?;
}
write!(f, ">")?;
Ok(())
}
}
/// A struct element type.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StructElementType<TV: TypeVarSupport = ResolvedTypeVarsOnly> {
pub name: Option<Ident>,
pub ty: ValueType<TV>,
}
impl<TV: TypeVarSupport> StructElementType<TV> {
/// Is this a subtype of `other`?
pub fn is_subtype_of(&self, other: &StructElementType<TV>) -> bool {
// We are a subtype of `other` if we have the same name, or if we have
// no name and `other` has a name.
//
// TODO: We may need to refine this carefully to match the expected
// behavior. Some of these combinations can't occur in the `STRUCT(..)`
// syntax, because it doesn't allow `STRUCT<..>(..) to use `AS`.
self.ty.is_subtype_of(&other.ty)
&& match (&self.name, &other.name) {
(Some(a), Some(b)) => a == b,
(None, Some(_)) => true,
(None, None) => true,
(Some(_), None) => false,
}
}
}
impl TryFrom<StructElementType> for ast::StructField {
type Error = Error;
fn try_from(value: StructElementType) -> Result<Self> {
Ok(ast::StructField {
name: value.name,
data_type: value.ty.try_into()?,
})
}
}
impl<TV: TypeVarSupport> fmt::Display for StructElementType<TV> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(name) = &self.name {
write!(f, "{} ", BigQueryName(&name.name))?;
}
write!(f, "{}", self.ty)?;
Ok(())
}
}
/// A table type.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TableType {
pub columns: Vec<ColumnType>,
}
impl TableType {
/// Expect a table to have a single column, and return that column.
pub fn expect_one_column(&self, spanned: &dyn Spanned) -> Result<&ColumnType> {
if self.columns.len() != 1 {
return Err(Error::annotated(
format!("expected a table with one column, found {}", self),
spanned.span(),
"type mismatch",
));
}
Ok(&self.columns[0])
}
/// Is this table a subtype of `other`, ignoring nullability?
pub fn is_subtype_ignoring_nullability_of(&self, other: &TableType) -> bool {
if self.columns.len() != other.columns.len() {
return false;
}
for (a, b) in self.columns.iter().zip(&other.columns) {
if !a.is_subtype_ignoring_nullability_of(b) {
return false;
}
}
true
}
/// Return an error if this table is not a subtype of `other`.
pub fn expect_subtype_ignoring_nullability_of(
&self,
other: &TableType,
spanned: &dyn Spanned,
) -> Result<()> {
if !self.is_subtype_ignoring_nullability_of(other) {
return Err(Error::annotated(
format!("expected {}, found {}", other, self),
spanned.span(),
"type mismatch",
));
}
Ok(())
}
/// Compute the least common supertype of two types. Returns `None` if the
/// only common super type would be top (⊤), which isn't part of our type
/// system.
///
/// For some nice theoretical terminology, see [this
/// page](https://orc.csres.utexas.edu/documentation/html/refmanual/ref.types.subtyping.html).
pub fn common_supertype<'a>(&'a self, other: &'a Self) -> Option<Self> {
// Make sure we have the same number of columns.
if self.columns.len() != other.columns.len() {
return None;
}
// For each column, see if we can merge the column definitions.
let mut columns = Vec::new();
for (a, b) in self.columns.iter().zip(&other.columns) {
if let Some(column) = a.common_supertype(b) {
columns.push(column);
} else {
return None;
}
}
Some(TableType { columns })
}
/// Expect this table to be creatable.
///
/// It must:
///
/// - Contain at least one column.
/// - Contain no duplicate column names.
/// - Contain no aggregate columns.
/// - Contain no uninhabited types.
pub fn expect_creatable(&self, spanned: &dyn Spanned) -> Result<()> {
if self.columns.is_empty() {
return Err(Error::annotated(
"Cannot create a table with no columns",
spanned.span(),