Enum erg_parser::ast::TypeSpec

source ·
pub enum TypeSpec {
Show 14 variants Infer(Token), PreDeclTy(PreDeclTypeSpec), Array(ArrayTypeSpec), SetWithLen(SetWithLenTypeSpec), Tuple(TupleTypeSpec), Dict(Vec<(TypeSpec, TypeSpec)>), Record(Vec<(Identifier, TypeSpec)>), And(Box<TypeSpec>, Box<TypeSpec>), Not(Box<TypeSpec>, Box<TypeSpec>), Or(Box<TypeSpec>, Box<TypeSpec>), Enum(ConstArgs), Interval { op: Token, lhs: ConstExpr, rhs: ConstExpr, }, Subr(SubrTypeSpec), TypeApp { spec: Box<TypeSpec>, args: TypeAppArgs, },
}
Expand description
  • Array: [Int; 3], [Int, Ratio, Complex], etc.
  • Dict: [Str: Str], etc.
  • And (Intersection type): Add and Sub and Mul (== Num), etc.
  • Not (Diff type): Pos == Nat not {0}, etc.
  • Or (Union type): Int or None (== Option Int), etc.
  • Enum: {0, 1} (== Binary), etc.
  • Range: 1..12, 0.0<..1.0, etc.
  • Record: {.into_s: Self.() -> Str }, etc.
  • Subr: Int -> Int, Int => None, T.(X) -> Int, etc.
  • TypeApp: F|…|

Variants§

Implementations§

Examples found in repository?
parse.rs (line 3362)
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
    pub fn expr_to_type_spec(rhs: Expr) -> Result<TypeSpec, ParseError> {
        match rhs {
            Expr::Accessor(acc) => Self::accessor_to_type_spec(acc),
            Expr::Call(call) => {
                let predecl = Self::call_to_predecl_type_spec(call)?;
                Ok(TypeSpec::PreDeclTy(predecl))
            }
            Expr::Lambda(lambda) => {
                let lambda = Self::lambda_to_subr_type_spec(lambda)?;
                Ok(TypeSpec::Subr(lambda))
            }
            Expr::Array(array) => {
                let array = Self::array_to_array_type_spec(array)?;
                Ok(TypeSpec::Array(array))
            }
            Expr::Set(set) => {
                let set = Self::set_to_set_type_spec(set)?;
                Ok(set)
            }
            Expr::Dict(dict) => {
                let dict = Self::dict_to_dict_type_spec(dict)?;
                Ok(TypeSpec::Dict(dict))
            }
            Expr::Record(rec) => {
                let rec = Self::record_to_record_type_spec(rec)?;
                Ok(TypeSpec::Record(rec))
            }
            Expr::Tuple(tup) => {
                let tup = Self::tuple_to_tuple_type_spec(tup)?;
                Ok(TypeSpec::Tuple(tup))
            }
            Expr::BinOp(bin) => {
                if bin.op.kind.is_range_op() {
                    let op = bin.op;
                    let mut args = bin.args.into_iter();
                    let lhs = Self::validate_const_expr(*args.next().unwrap())?;
                    let rhs = Self::validate_const_expr(*args.next().unwrap())?;
                    Ok(TypeSpec::Interval { op, lhs, rhs })
                } else if bin.op.kind == TokenKind::AndOp {
                    let mut args = bin.args.into_iter();
                    let lhs = Self::expr_to_type_spec(*args.next().unwrap())?;
                    let rhs = Self::expr_to_type_spec(*args.next().unwrap())?;
                    Ok(TypeSpec::and(lhs, rhs))
                } else if bin.op.kind == TokenKind::OrOp {
                    let mut args = bin.args.into_iter();
                    let lhs = Self::expr_to_type_spec(*args.next().unwrap())?;
                    let rhs = Self::expr_to_type_spec(*args.next().unwrap())?;
                    Ok(TypeSpec::or(lhs, rhs))
                } else {
                    let err = ParseError::simple_syntax_error(line!() as usize, bin.loc());
                    Err(err)
                }
            }
            Expr::Lit(lit) => {
                let mut err = ParseError::simple_syntax_error(line!() as usize, lit.loc());
                if lit.is(TokenKind::NoneLit) {
                    err.set_hint("you mean: `NoneType`?");
                }
                Err(err)
            }
            other => {
                let err = ParseError::simple_syntax_error(line!() as usize, other.loc());
                Err(err)
            }
        }
    }
Examples found in repository?
parse.rs (line 3367)
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
    pub fn expr_to_type_spec(rhs: Expr) -> Result<TypeSpec, ParseError> {
        match rhs {
            Expr::Accessor(acc) => Self::accessor_to_type_spec(acc),
            Expr::Call(call) => {
                let predecl = Self::call_to_predecl_type_spec(call)?;
                Ok(TypeSpec::PreDeclTy(predecl))
            }
            Expr::Lambda(lambda) => {
                let lambda = Self::lambda_to_subr_type_spec(lambda)?;
                Ok(TypeSpec::Subr(lambda))
            }
            Expr::Array(array) => {
                let array = Self::array_to_array_type_spec(array)?;
                Ok(TypeSpec::Array(array))
            }
            Expr::Set(set) => {
                let set = Self::set_to_set_type_spec(set)?;
                Ok(set)
            }
            Expr::Dict(dict) => {
                let dict = Self::dict_to_dict_type_spec(dict)?;
                Ok(TypeSpec::Dict(dict))
            }
            Expr::Record(rec) => {
                let rec = Self::record_to_record_type_spec(rec)?;
                Ok(TypeSpec::Record(rec))
            }
            Expr::Tuple(tup) => {
                let tup = Self::tuple_to_tuple_type_spec(tup)?;
                Ok(TypeSpec::Tuple(tup))
            }
            Expr::BinOp(bin) => {
                if bin.op.kind.is_range_op() {
                    let op = bin.op;
                    let mut args = bin.args.into_iter();
                    let lhs = Self::validate_const_expr(*args.next().unwrap())?;
                    let rhs = Self::validate_const_expr(*args.next().unwrap())?;
                    Ok(TypeSpec::Interval { op, lhs, rhs })
                } else if bin.op.kind == TokenKind::AndOp {
                    let mut args = bin.args.into_iter();
                    let lhs = Self::expr_to_type_spec(*args.next().unwrap())?;
                    let rhs = Self::expr_to_type_spec(*args.next().unwrap())?;
                    Ok(TypeSpec::and(lhs, rhs))
                } else if bin.op.kind == TokenKind::OrOp {
                    let mut args = bin.args.into_iter();
                    let lhs = Self::expr_to_type_spec(*args.next().unwrap())?;
                    let rhs = Self::expr_to_type_spec(*args.next().unwrap())?;
                    Ok(TypeSpec::or(lhs, rhs))
                } else {
                    let err = ParseError::simple_syntax_error(line!() as usize, bin.loc());
                    Err(err)
                }
            }
            Expr::Lit(lit) => {
                let mut err = ParseError::simple_syntax_error(line!() as usize, lit.loc());
                if lit.is(TokenKind::NoneLit) {
                    err.set_hint("you mean: `NoneType`?");
                }
                Err(err)
            }
            other => {
                let err = ParseError::simple_syntax_error(line!() as usize, other.loc());
                Err(err)
            }
        }
    }
Examples found in repository?
parse.rs (line 3116)
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
    fn accessor_to_type_spec(accessor: Accessor) -> Result<TypeSpec, ParseError> {
        let t_spec = match accessor {
            Accessor::Ident(ident) => {
                let predecl = PreDeclTypeSpec::Simple(Self::ident_to_type_spec(ident));
                TypeSpec::PreDeclTy(predecl)
            }
            Accessor::TypeApp(tapp) => {
                let spec = Self::expr_to_type_spec(*tapp.obj)?;
                TypeSpec::type_app(spec, tapp.type_args)
            }
            Accessor::Attr(attr) => {
                let namespace = attr.obj;
                let t = Self::ident_to_type_spec(attr.ident);
                let predecl = PreDeclTypeSpec::Attr { namespace, t };
                TypeSpec::PreDeclTy(predecl)
            }
            other => {
                let err = ParseError::simple_syntax_error(line!() as usize, other.loc());
                return Err(err);
            }
        };
        Ok(t_spec)
    }
Examples found in repository?
desugar.rs (line 756)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
    fn desugar_nd_param(&mut self, param: &mut NonDefaultParamSignature, body: &mut Block) {
        let mut insertion_idx = 0;
        let line = param.ln_begin().unwrap();
        match &mut param.pat {
            ParamPattern::VarName(_v) => {}
            ParamPattern::Lit(l) => {
                let lit = l.clone();
                param.pat = ParamPattern::Discard(Token::new(
                    TokenKind::UBar,
                    "_",
                    l.ln_begin().unwrap(),
                    l.col_begin().unwrap(),
                ));
                param.t_spec = Some(TypeSpecWithOp::new(COLON, TypeSpec::enum_t_spec(vec![lit])));
            }
            ParamPattern::Tuple(tup) => {
                let (buf_name, buf_param) = self.gen_buf_nd_param(line);
                let mut tys = vec![];
                for (n, elem) in tup.elems.non_defaults.iter_mut().enumerate() {
                    insertion_idx = self.desugar_nested_param_pattern(
                        body,
                        elem,
                        &buf_name,
                        BufIndex::Tuple(n),
                        insertion_idx,
                    );
                    let infer = Token::new(TokenKind::Try, "?", line, 0);
                    tys.push(
                        elem.t_spec
                            .as_ref()
                            .map(|ts| ts.t_spec.clone())
                            .unwrap_or(TypeSpec::Infer(infer))
                            .clone(),
                    );
                }
                if param.t_spec.is_none() {
                    let t_spec = TypeSpec::Tuple(TupleTypeSpec::new(tup.elems.parens.clone(), tys));
                    param.t_spec = Some(TypeSpecWithOp::new(COLON, t_spec));
                }
                param.pat = buf_param;
            }
            ParamPattern::Array(arr) => {
                let (buf_name, buf_param) = self.gen_buf_nd_param(line);
                for (n, elem) in arr.elems.non_defaults.iter_mut().enumerate() {
                    insertion_idx = self.desugar_nested_param_pattern(
                        body,
                        elem,
                        &buf_name,
                        BufIndex::Array(n),
                        insertion_idx,
                    );
                }
                if param.t_spec.is_none() {
                    let len = arr.elems.non_defaults.len();
                    let len = Literal::new(Token::new(TokenKind::NatLit, len.to_string(), line, 0));
                    let infer = Token::new(TokenKind::Try, "?", line, 0);
                    let t_spec = ArrayTypeSpec::new(TypeSpec::Infer(infer), ConstExpr::Lit(len));
                    param.t_spec = Some(TypeSpecWithOp::new(
                        Token::dummy(TokenKind::Colon, ":"),
                        TypeSpec::Array(t_spec),
                    ));
                }
                param.pat = buf_param;
            }
            ParamPattern::Record(rec) => {
                let (buf_name, buf_param) = self.gen_buf_nd_param(line);
                for ParamRecordAttr { lhs, rhs } in rec.elems.iter_mut() {
                    insertion_idx = self.desugar_nested_param_pattern(
                        body,
                        rhs,
                        &buf_name,
                        BufIndex::Record(lhs),
                        insertion_idx,
                    );
                }
                if param.t_spec.is_none() {
                    let mut tys = vec![];
                    for ParamRecordAttr { lhs, rhs } in rec.elems.iter() {
                        let infer = Token::new(TokenKind::Try, "?", line, 0);
                        tys.push((
                            lhs.clone(),
                            rhs.t_spec
                                .as_ref()
                                .map(|ts| ts.t_spec.clone())
                                .unwrap_or(TypeSpec::Infer(infer))
                                .clone(),
                        ));
                    }
                    param.t_spec = Some(TypeSpecWithOp::new(COLON, TypeSpec::Record(tys)));
                }
                param.pat = buf_param;
            }
            /*ParamPattern::DataPack(pack) => {
                let (buf_name, buf_sig) = self.gen_buf_name_and_sig(
                    v.ln_begin().unwrap(),
                    Some(pack.class.clone()), // TODO: これだとvの型指定の意味がなくなる
                );
                let buf_def = Def::new(buf_sig, body);
                new.push(Expr::Def(buf_def));
                for VarRecordAttr { lhs, rhs } in pack.args.attrs.iter() {
                    self.desugar_nested_var_pattern(
                        &mut new,
                        rhs,
                        &buf_name,
                        BufIndex::Record(lhs),
                    );
                }
            }*/
            _ => {}
        }
    }

    fn desugar_nested_param_pattern(
        &mut self,
        new_body: &mut Block,
        sig: &mut NonDefaultParamSignature,
        buf_name: &str,
        buf_index: BufIndex,
        mut insertion_idx: usize,
    ) -> usize {
        let obj = Expr::local(buf_name, sig.ln_begin().unwrap(), sig.col_begin().unwrap());
        let acc = match buf_index {
            BufIndex::Tuple(n) => obj.tuple_attr(Literal::nat(n, sig.ln_begin().unwrap())),
            BufIndex::Array(n) => {
                let r_brace = Token::new(
                    TokenKind::RBrace,
                    "]",
                    sig.ln_begin().unwrap(),
                    sig.col_begin().unwrap(),
                );
                obj.subscr(Expr::Lit(Literal::nat(n, sig.ln_begin().unwrap())), r_brace)
            }
            BufIndex::Record(attr) => obj.attr(attr.clone()),
        };
        let id = DefId(get_hash(&(&acc, buf_name)));
        let block = Block::new(vec![Expr::Accessor(acc)]);
        let op = Token::from_str(TokenKind::Equal, "=");
        let body = DefBody::new(op, block, id);
        let line = sig.ln_begin().unwrap();
        match &mut sig.pat {
            ParamPattern::Tuple(tup) => {
                let (buf_name, buf_sig) = self.gen_buf_nd_param(line);
                let ident = Identifier::private(Str::from(&buf_name));
                new_body.insert(
                    insertion_idx,
                    Expr::Def(Def::new(
                        Signature::Var(VarSignature::new(
                            VarPattern::Ident(ident),
                            sig.t_spec.as_ref().map(|ts| ts.t_spec.clone()),
                        )),
                        body,
                    )),
                );
                insertion_idx += 1;
                let mut tys = vec![];
                for (n, elem) in tup.elems.non_defaults.iter_mut().enumerate() {
                    insertion_idx = self.desugar_nested_param_pattern(
                        new_body,
                        elem,
                        &buf_name,
                        BufIndex::Tuple(n),
                        insertion_idx,
                    );
                    let infer = Token::new(TokenKind::Try, "?", line, 0);
                    tys.push(
                        elem.t_spec
                            .as_ref()
                            .map(|ts| ts.t_spec.clone())
                            .unwrap_or(TypeSpec::Infer(infer))
                            .clone(),
                    );
                }
                if sig.t_spec.is_none() {
                    let t_spec = TypeSpec::Tuple(TupleTypeSpec::new(tup.elems.parens.clone(), tys));
                    sig.t_spec = Some(TypeSpecWithOp::new(COLON, t_spec));
                }
                sig.pat = buf_sig;
                insertion_idx
            }
            ParamPattern::Array(arr) => {
                let (buf_name, buf_sig) = self.gen_buf_nd_param(line);
                new_body.insert(
                    insertion_idx,
                    Expr::Def(Def::new(
                        Signature::Var(VarSignature::new(
                            VarPattern::Ident(Identifier::private(Str::from(&buf_name))),
                            sig.t_spec.as_ref().map(|ts| ts.t_spec.clone()),
                        )),
                        body,
                    )),
                );
                insertion_idx += 1;
                for (n, elem) in arr.elems.non_defaults.iter_mut().enumerate() {
                    insertion_idx = self.desugar_nested_param_pattern(
                        new_body,
                        elem,
                        &buf_name,
                        BufIndex::Array(n),
                        insertion_idx,
                    );
                }
                if sig.t_spec.is_none() {
                    let len = arr.elems.non_defaults.len();
                    let len = Literal::new(Token::new(TokenKind::NatLit, len.to_string(), line, 0));
                    let infer = Token::new(TokenKind::Try, "?", line, 0);
                    let t_spec = ArrayTypeSpec::new(TypeSpec::Infer(infer), ConstExpr::Lit(len));
                    sig.t_spec = Some(TypeSpecWithOp::new(COLON, TypeSpec::Array(t_spec)));
                }
                sig.pat = buf_sig;
                insertion_idx
            }
            ParamPattern::Record(rec) => {
                let (buf_name, buf_sig) = self.gen_buf_nd_param(line);
                new_body.insert(
                    insertion_idx,
                    Expr::Def(Def::new(
                        Signature::Var(VarSignature::new(
                            VarPattern::Ident(Identifier::private(Str::from(&buf_name))),
                            sig.t_spec.as_ref().map(|ts| ts.t_spec.clone()),
                        )),
                        body,
                    )),
                );
                insertion_idx += 1;
                let mut tys = vec![];
                for ParamRecordAttr { lhs, rhs } in rec.elems.iter_mut() {
                    insertion_idx = self.desugar_nested_param_pattern(
                        new_body,
                        rhs,
                        &buf_name,
                        BufIndex::Record(lhs),
                        insertion_idx,
                    );
                    let infer = Token::new(TokenKind::Try, "?", line, 0);
                    tys.push((
                        lhs.clone(),
                        rhs.t_spec
                            .as_ref()
                            .map(|ts| ts.t_spec.clone())
                            .unwrap_or(TypeSpec::Infer(infer))
                            .clone(),
                    ));
                }
                if sig.t_spec.is_none() {
                    sig.t_spec = Some(TypeSpecWithOp::new(COLON, TypeSpec::Record(tys)));
                }
                sig.pat = buf_sig;
                insertion_idx
            }
            /*
            VarPattern::DataPack(pack) => {
                let (buf_name, buf_sig) =
                    self.gen_buf_name_and_sig(sig.ln_begin().unwrap(), Some(pack.class.clone()));
                let buf_def = Def::new(buf_sig, body);
                new_module.push(Expr::Def(buf_def));
                for VarRecordAttr { lhs, rhs } in pack.args.attrs.iter() {
                    self.desugar_nested_var_pattern(
                        new_module,
                        rhs,
                        &buf_name,
                        BufIndex::Record(lhs),
                    );
                }
            }
            */
            ParamPattern::VarName(name) => {
                let ident = Identifier::new(None, name.clone());
                let v = VarSignature::new(
                    VarPattern::Ident(ident),
                    sig.t_spec.as_ref().map(|ts| ts.t_spec.clone()),
                );
                let def = Def::new(Signature::Var(v), body);
                new_body.insert(insertion_idx, Expr::Def(def));
                insertion_idx += 1;
                insertion_idx
            }
            ParamPattern::Lit(l) => {
                let lit = l.clone();
                sig.pat = ParamPattern::Discard(Token::new(
                    TokenKind::UBar,
                    "_",
                    l.ln_begin().unwrap(),
                    l.col_begin().unwrap(),
                ));
                sig.t_spec = Some(TypeSpecWithOp::new(COLON, TypeSpec::enum_t_spec(vec![lit])));
                insertion_idx
            }
            _ => insertion_idx,
        }
    }

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Formats the value using the given formatter. Read more
Feeds this value into the given Hasher. Read more
Feeds a slice of this type into the given Hasher. Read more
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
Converts the given value to a String. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.