From b669d2df1eb065e05e20be9d596bfa0e77763f0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Rowicki?= <35342116+radrow@users.noreply.github.com> Date: Wed, 14 Aug 2019 13:53:58 +0200 Subject: [PATCH] Added list comprehensions and standard List, Option, Func, Pair, and Triple library (#105) * Added standard List library and list comprehensions Added List library. Flatmaps WIP Fixed dependency in flat_map fcode generation Updated tests to use custom list lib Added comprehension test Added stdlib sanity Test * Extended stdlib for lists. Added error message for redefinition of stdlibx * Fixed type template * Improved stdlib * More functions * Fixed cyclic includes * Refixed imports and added few tests * Added fail test * Undelete removed type spec * Remove typo * Fix iter function * Fixed typo * Added if guards and let statements in list comp * Added more fail tests * Option stliv * 2 and 3 tuple stdlib * Updated stdlib to new syntax. Added recursor and changed all/any functions * Fixed performance issues. Changed include management * Fixed hash type --- src/aeso_ast_infer_types.erl | 61 ++++ src/aeso_ast_to_fcode.erl | 17 + src/aeso_ast_to_icode.erl | 18 + src/aeso_compiler.erl | 24 +- src/aeso_parser.erl | 93 ++++- src/aeso_pretty.erl | 2 + src/aeso_stdlib.erl | 434 +++++++++++++++++++++++ src/aeso_syntax.erl | 5 + test/aeso_abi_tests.erl | 14 +- test/aeso_aci_tests.erl | 5 +- test/aeso_calldata_tests.erl | 12 +- test/aeso_compiler_tests.erl | 30 +- test/aeso_parser_tests.erl | 14 +- test/contracts/cyclic_include.aes | 4 + test/contracts/cyclic_include_back.aes | 4 + test/contracts/cyclic_include_forth.aes | 4 + test/contracts/deadcode.aes | 6 +- test/contracts/double_include.aes | 7 + test/contracts/list_comp.aes | 23 ++ test/contracts/list_comp_bad_shadow.aes | 2 + test/contracts/list_comp_if_not_bool.aes | 2 + test/contracts/list_comp_not_a_list.aes | 2 + test/contracts/manual_stdlib_include.aes | 7 + test/contracts/multi_sig.aes | 4 +- test/contracts/nodeadcode.aes | 6 +- test/contracts/reason/voting.re | 6 +- test/contracts/reason/voting_test.re | 2 +- test/contracts/stdlib_include.aes | 3 + test/contracts/voting.aes | 6 +- 29 files changed, 760 insertions(+), 57 deletions(-) create mode 100644 src/aeso_stdlib.erl create mode 100644 test/contracts/cyclic_include.aes create mode 100644 test/contracts/cyclic_include_back.aes create mode 100644 test/contracts/cyclic_include_forth.aes create mode 100644 test/contracts/double_include.aes create mode 100644 test/contracts/list_comp.aes create mode 100644 test/contracts/list_comp_bad_shadow.aes create mode 100644 test/contracts/list_comp_if_not_bool.aes create mode 100644 test/contracts/list_comp_not_a_list.aes create mode 100644 test/contracts/manual_stdlib_include.aes create mode 100644 test/contracts/stdlib_include.aes diff --git a/src/aeso_ast_infer_types.erl b/src/aeso_ast_infer_types.erl index 725323d..0f506d8 100644 --- a/src/aeso_ast_infer_types.erl +++ b/src/aeso_ast_infer_types.erl @@ -363,6 +363,8 @@ global_env() -> Pair = fun(A, B) -> {tuple_t, Ann, [A, B]} end, Fun = fun(Ts, T) -> {type_sig, Ann, [], Ts, T} end, Fun1 = fun(S, T) -> Fun([S], T) end, + %% Lambda = fun(Ts, T) -> {fun_t, Ann, [], Ts, T} end, + %% Lambda1 = fun(S, T) -> Lambda([S], T) end, StateFun = fun(Ts, T) -> {type_sig, [stateful|Ann], [], Ts, T} end, TVar = fun(X) -> {tvar, Ann, "'" ++ X} end, SignId = {id, Ann, "signature"}, @@ -1074,6 +1076,58 @@ infer_expr(Env, {list, As, Elems}) -> ElemType = fresh_uvar(As), NewElems = [check_expr(Env, X, ElemType) || X <- Elems], {typed, As, {list, As, NewElems}, {app_t, As, {id, As, "list"}, [ElemType]}}; +infer_expr(Env, {list_comp, As, Yield, []}) -> + {typed, _, TypedYield, Type} = infer_expr(Env, Yield), + {typed, As, {list_comp, As, TypedYield, []}, {app_t, As, {id, As, "list"}, [Type]}}; +infer_expr(Env, {list_comp, As, Yield, [{comprehension_bind, Arg, BExpr}|Rest]}) -> + BindVarType = fresh_uvar(As), + TypedBind = {typed, As2, _, TypeBExpr} = infer_expr(Env, BExpr), + unify( Env + , TypeBExpr + , {app_t, As, {id, As, "list"}, [BindVarType]} + , {list_comp, TypedBind, TypeBExpr, {app_t, As2, {id, As, "list"}, [BindVarType]}}), + NewE = bind_var(Arg, BindVarType, Env), + {typed, _, {list_comp, _, TypedYield, TypedRest}, ResType} = + infer_expr(NewE, {list_comp, As, Yield, Rest}), + { typed + , As + , {list_comp, As, TypedYield, [{comprehension_bind, {typed, Arg, BindVarType}, TypedBind}|TypedRest]} + , ResType}; +infer_expr(Env, {list_comp, AttrsL, Yield, [{comprehension_if, AttrsIF, Cond}|Rest]}) -> + NewCond = check_expr(Env, Cond, {id, AttrsIF, "bool"}), + {typed, _, {list_comp, _, TypedYield, TypedRest}, ResType} = + infer_expr(Env, {list_comp, AttrsL, Yield, Rest}), + { typed + , AttrsL + , {list_comp, AttrsL, TypedYield, [{comprehension_if, AttrsIF, NewCond}|TypedRest]} + , ResType}; +infer_expr(Env, {list_comp, AsLC, Yield, [{letval, AsLV, Pattern, Type, E}|Rest]}) -> + NewE = {typed, _, _, PatType} = infer_expr(Env, {typed, AsLV, E, arg_type(Type)}), + BlockType = fresh_uvar(AsLV), + {'case', _, NewPattern, NewRest} = + infer_case( Env + , AsLC + , Pattern + , PatType + , {list_comp, AsLC, Yield, Rest} + , BlockType), + {typed, _, {list_comp, _, TypedYield, TypedRest}, ResType} = NewRest, + { typed + , AsLC + , {list_comp, AsLC, TypedYield, [{letval, AsLV, NewPattern, Type, NewE}|TypedRest]} + , ResType + }; +infer_expr(Env, {list_comp, AsLC, Yield, [Def={letfun, AsLF, _, _, _, _}|Rest]}) -> + {{Name, TypeSig}, LetFun} = infer_letfun(Env, Def), + FunT = freshen_type(AsLF, typesig_to_fun_t(TypeSig)), + NewE = bind_var({id, AsLF, Name}, FunT, Env), + {typed, _, {list_comp, _, TypedYield, TypedRest}, ResType} = + infer_expr(NewE, {list_comp, AsLC, Yield, Rest}), + { typed + , AsLC + , {list_comp, AsLC, TypedYield, [LetFun|TypedRest]} + , ResType + }; infer_expr(Env, {typed, As, Body, Type}) -> Type1 = check_type(Env, Type), {typed, _, NewBody, NewType} = check_expr(Env, Body, Type1), @@ -2253,6 +2307,13 @@ pp_when({check_expr, Expr, Inferred0, Expected0}) -> pp_when({checking_init_type, Ann}) -> io_lib:format("when checking that 'init' returns a value of type 'state' at ~s\n", [pp_loc(Ann)]); +pp_when({list_comp, BindExpr, Inferred0, Expected0}) -> + {Inferred, Expected} = instantiate({Inferred0, Expected0}), + io_lib:format("when checking rvalue of list comprehension binding at ~s\n~s\n" + "against type \n~s\n", + [pp_loc(BindExpr), pp_typed(" ", BindExpr, Inferred), pp_type(" ", Expected)] + ); + pp_when(unknown) -> "". -spec pp_why_record(why_record()) -> iolist(). diff --git a/src/aeso_ast_to_fcode.erl b/src/aeso_ast_to_fcode.erl index 7ce42ab..cc51155 100644 --- a/src/aeso_ast_to_fcode.erl +++ b/src/aeso_ast_to_fcode.erl @@ -444,6 +444,23 @@ expr_to_fcode(Env, _Type, {list, _, Es}) -> lists:foldr(fun(E, L) -> {op, '::', [expr_to_fcode(Env, E), L]} end, nil, Es); +expr_to_fcode(Env, _Type, {list_comp, _, Yield, []}) -> + {op, '::', [expr_to_fcode(Env, Yield), nil]}; +expr_to_fcode(Env, _Type, {list_comp, As, Yield, [{comprehension_bind, {typed, {id, _, Arg}, _}, BindExpr}|Rest]}) -> + Env1 = bind_var(Env, Arg), + Bind = {lam, [Arg], expr_to_fcode(Env1, {list_comp, As, Yield, Rest})}, + {def_u, FlatMap, _} = resolve_fun(Env, ["List", "flat_map"]), + {def, FlatMap, [Bind, expr_to_fcode(Env, BindExpr)]}; +expr_to_fcode(Env, Type, {list_comp, As, Yield, [{comprehension_if, _, Cond}|Rest]}) -> + make_if(expr_to_fcode(Env, Cond), + expr_to_fcode(Env, Type, {list_comp, As, Yield, Rest}), + nil + ); +expr_to_fcode(Env, Type, {list_comp, As, Yield, [LV = {letval, _, _, _, _}|Rest]}) -> + expr_to_fcode(Env, Type, {block, As, [LV, {list_comp, As, Yield, Rest}]}); +expr_to_fcode(Env, Type, {list_comp, As, Yield, [LF = {letfun, _, _, _, _, _}|Rest]}) -> + expr_to_fcode(Env, Type, {block, As, [LF, {list_comp, As, Yield, Rest}]}); + %% Conditionals expr_to_fcode(Env, _Type, {'if', _, Cond, Then, Else}) -> make_if(expr_to_fcode(Env, Cond), diff --git a/src/aeso_ast_to_icode.erl b/src/aeso_ast_to_icode.erl index e611f8f..6aac6c1 100644 --- a/src/aeso_ast_to_icode.erl +++ b/src/aeso_ast_to_icode.erl @@ -519,6 +519,24 @@ ast_body({app,As,Fun,Args}, Icode) -> #funcall{function=ast_body(Fun, Icode), args=[ast_body(A, Icode) || A <- Args]} end; +ast_body({list_comp, _, Yield, []}, Icode) -> + #list{elems = [ast_body(Yield, Icode)]}; +ast_body({list_comp, As, Yield, [{comprehension_bind, {typed, Arg, ArgType}, BindExpr}|Rest]}, Icode) -> + #funcall + { function = #var_ref{ name = ["List", "flat_map"] } + , args = + [ #lambda{ args=[#arg{name = ast_id(Arg), type = ast_type(ArgType, Icode)}] + , body = ast_body({list_comp, As, Yield, Rest}, Icode) + } + , ast_body(BindExpr, Icode) + ] + }; +ast_body({list_comp, As, Yield, [{comprehension_if, AsIF, Cond}|Rest]}, Icode) -> + ast_body({'if', AsIF, Cond, {list_comp, As, Yield, Rest}, {list, As, []}}, Icode); +ast_body({list_comp, As, Yield, [LV = {letval, _, _, _, _}|Rest]}, Icode) -> + ast_body({block, As, [LV, {list_comp, As, Yield, Rest}]}, Icode); +ast_body({list_comp, As, Yield, [LF = {letfun, _, _, _, _, _}|Rest]}, Icode) -> + ast_body({block, As, [LF, {list_comp, As, Yield, Rest}]}, Icode); ast_body({'if',_,Dec,Then,Else}, Icode) -> #ifte{decision = ast_body(Dec, Icode) ,then = ast_body(Then, Icode) diff --git a/src/aeso_compiler.erl b/src/aeso_compiler.erl index 0280edd..fae063f 100644 --- a/src/aeso_compiler.erl +++ b/src/aeso_compiler.erl @@ -36,6 +36,7 @@ | pp_assembler | pp_bytecode | no_code + | no_implicit_stdlib | {backend, aevm | fate} | {include, {file_system, [string()]} | {explicit_files, #{string() => binary()}}} @@ -139,7 +140,16 @@ from_string1(fate, ContractString, Options) -> -spec string_to_code(string(), options()) -> map(). string_to_code(ContractString, Options) -> - Ast = parse(ContractString, Options), + Ast = case lists:member(no_implicit_stdlib, Options) of + true -> parse(ContractString, Options); + false -> + IncludedSTD = sets:from_list( + [aeso_parser:hash_include(F, C) + || {F, C} <- aeso_stdlib:stdlib_list()]), + InitAst = parse(ContractString, IncludedSTD, Options), + STD = parse_stdlib(), + STD ++ InitAst + end, pp_sophia_code(Ast, Options), pp_ast(Ast, Options), {TypeEnv, TypedAst} = aeso_ast_infer_types:infer(Ast, [return_env]), @@ -568,6 +578,14 @@ pp(Code, Options, Option, PPFun) -> %% ------------------------------------------------------------------- %% TODO: Tempoary parser hook below... +parse_stdlib() -> + lists:foldr( + fun ({Lib, LibCode}, Acc) -> + parse(LibCode, [{src_file, Lib}]) ++ Acc + end, + [], + aeso_stdlib:stdlib_list()). + sophia_type_to_typerep(String) -> {ok, Ast} = aeso_parser:type(String), try aeso_ast_to_icode:ast_typerep(Ast) of @@ -576,8 +594,10 @@ sophia_type_to_typerep(String) -> end. parse(Text, Options) -> + parse(Text, sets:new(), Options). +parse(Text, Included, Options) -> %% Try and return something sensible here! - case aeso_parser:string(Text, Options) of + case aeso_parser:string(Text, Included, Options) of %% Yay, it worked! {ok, Contract} -> Contract; %% Scan errors. diff --git a/src/aeso_parser.erl b/src/aeso_parser.erl index cdcb2c8..f0bd60f 100644 --- a/src/aeso_parser.erl +++ b/src/aeso_parser.erl @@ -6,6 +6,8 @@ -export([string/1, string/2, + string/3, + hash_include/2, type/1]). -include("aeso_parse_lib.hrl"). @@ -14,15 +16,25 @@ | {error, {aeso_parse_lib:pos(), atom(), term()}} | {error, {aeso_parse_lib:pos(), atom()}}. +-type include_hash() :: {string(), binary()}. + -spec string(string()) -> parse_result(). string(String) -> - string(String, []). + string(String, sets:new(), []). --spec string(string(), aeso_compiler:options()) -> parse_result(). + +-spec string(string(), compiler:options()) -> parse_result(). string(String, Opts) -> + case lists:keyfind(src_file, 1, Opts) of + {src_file, File} -> string(String, sets:add_element(File, sets:new()), Opts); + false -> string(String, sets:new(), Opts) + end. + +-spec string(string(), sets:set(include_hash()), aeso_compiler:options()) -> parse_result(). +string(String, Included, Opts) -> case parse_and_scan(file(), String, Opts) of {ok, AST} -> - expand_includes(AST, Opts); + expand_includes(AST, Included, Opts); Err = {error, _} -> Err end. @@ -230,11 +242,25 @@ exprAtom() -> , {bool, keyword(false), false} , ?LET_P(Fs, brace_list(?LAZY_P(field_assignment())), record(Fs)) , {list, [], bracket_list(Expr)} + , ?RULE(keyword('['), Expr, token('|'), comma_sep(comprehension_exp()), tok(']'), list_comp_e(_1, _2, _4)) , ?RULE(tok('['), Expr, binop('..'), Expr, tok(']'), _3(_2, _4)) , ?RULE(keyword('('), comma_sep(Expr), tok(')'), tuple_e(_1, _2)) ]) end). +comprehension_exp() -> + ?LAZY_P(choice( + [ comprehension_bind() + , letdecl() + , comprehension_if() + ])). + +comprehension_if() -> + ?RULE(keyword('if'), parens(expr()), {comprehension_if, _1, _2}). + +comprehension_bind() -> + ?RULE(id(), tok('<-'), expr(), {comprehension_bind, _1, _3}). + arg_expr() -> ?LAZY_P( choice([ ?RULE(id(), tok('='), expr(), {named_arg, [], _1, _3}) @@ -481,6 +507,8 @@ fun_t(Domains, Type) -> tuple_e(_Ann, [Expr]) -> Expr; %% Not a tuple tuple_e(Ann, Exprs) -> {tuple, Ann, Exprs}. +list_comp_e(Ann, Expr, Binds) -> {list_comp, Ann, Expr, Binds}. + -spec parse_pattern(aeso_syntax:expr()) -> aeso_parse_lib:parser(aeso_syntax:pat()). parse_pattern({app, Ann, Con = {'::', _}, Es}) -> {app, Ann, Con, lists:map(fun parse_pattern/1, Es)}; @@ -521,26 +549,36 @@ bad_expr_err(Reason, E) -> prettypr:nest(2, aeso_pretty:expr(E))])). %% -- Helper functions ------------------------------------------------------- -expand_includes(AST, Opts) -> - expand_includes(AST, [], Opts). +expand_includes(AST, Included, Opts) -> + expand_includes(AST, Included, [], Opts). -expand_includes([], Acc, _Opts) -> +expand_includes([], _Included, Acc, _Opts) -> {ok, lists:reverse(Acc)}; -expand_includes([{include, _, S = {string, _, File}} | AST], Acc, Opts) -> - case read_file(File, Opts) of - {ok, Bin} -> - Opts1 = lists:keystore(src_file, 1, Opts, {src_file, File}), - case string(binary_to_list(Bin), Opts1) of - {ok, AST1} -> - expand_includes(AST1 ++ AST, Acc, Opts); - Err = {error, _} -> - Err +expand_includes([{include, Ann, {string, SAnn, File}} | AST], Included, Acc, Opts) -> + case get_include_code(File, Ann, Opts) of + {ok, Code} -> + Hashed = hash_include(File, Code), + case sets:is_element(Hashed, Included) of + false -> + Opts1 = lists:keystore(src_file, 1, Opts, {src_file, File}), + Included1 = sets:add_element(Hashed, Included), + case string(Code, Included1, Opts1) of + {ok, AST1} -> + Dependencies = [ {include, Ann, {string, SAnn, Dep}} + || Dep <- aeso_stdlib:dependencies(File) + ], + expand_includes(Dependencies ++ AST1 ++ AST, Included1, Acc, Opts); + Err = {error, _} -> + Err + end; + true -> + expand_includes(AST, Included, Acc, Opts) end; - {error, _} -> - {error, {get_pos(S), include_error, File}} + Err = {error, _} -> + Err end; -expand_includes([E | AST], Acc, Opts) -> - expand_includes(AST, [E | Acc], Opts). +expand_includes([E | AST], Included, Acc, Opts) -> + expand_includes(AST, Included, [E | Acc], Opts). read_file(File, Opts) -> case proplists:get_value(include, Opts, {explicit_files, #{}}) of @@ -555,3 +593,20 @@ read_file(File, Opts) -> end end. +get_include_code(File, Ann, Opts) -> + case {read_file(File, Opts), maps:find(File, aeso_stdlib:stdlib())} of + {{ok, _}, {ok,_ }} -> + return_error(ann_pos(Ann), "Illegal redefinition of standard library " ++ File); + {_, {ok, Lib}} -> + {ok, Lib}; + {{ok, Bin}, _} -> + {ok, binary_to_list(Bin)}; + {_, _} -> + {error, {ann_pos(Ann), include_error, File}} + end. + +-spec hash_include(string() | binary(), string()) -> include_hash(). +hash_include(File, Code) when is_binary(File) -> + hash_include(binary_to_list(File), Code); +hash_include(File, Code) when is_list(File) -> + {filename:basename(File), crypto:hash(sha256, Code)}. diff --git a/src/aeso_pretty.erl b/src/aeso_pretty.erl index ea76b42..e368354 100644 --- a/src/aeso_pretty.erl +++ b/src/aeso_pretty.erl @@ -235,6 +235,8 @@ type(Type, Options) -> -spec type(aeso_syntax:type()) -> doc(). type({fun_t, _, Named, Args, Ret}) -> follow(hsep(args_type(Named ++ Args), text("=>")), type(Ret)); +type({type_sig, _, Named, Args, Ret}) -> + follow(hsep(tuple_type(Named ++ Args), text("=>")), type(Ret)); type({app_t, _, Type, []}) -> type(Type); type({app_t, _, Type, Args}) -> diff --git a/src/aeso_stdlib.erl b/src/aeso_stdlib.erl new file mode 100644 index 0000000..f154c7b --- /dev/null +++ b/src/aeso_stdlib.erl @@ -0,0 +1,434 @@ +%%%------------------------------------------------------------------- +%%% @author Radosław Rowicki +%%% @copyright (C) 2019, Aeternity Anstalt +%%% @doc +%%% Standard library for Sophia +%%% @end +%%% Created : 6 July 2019 +%%% +%%%------------------------------------------------------------------- + +-module(aeso_stdlib). + +-export([stdlib/0, stdlib_list/0, dependencies/1]). + +stdlib() -> + maps:from_list(stdlib_list()). + +stdlib_list() -> + [ {<<"List.aes">>, std_list()} + , {<<"Func.aes">>, std_func()} + , {<<"Option.aes">>, std_option()} + , {<<"Pair.aes">>, std_pair()} + , {<<"Triple.aes">>, std_triple()} + ]. + +dependencies(Q) -> + case Q of + <<"Option.aes">> -> + [<<"List.aes">>]; + _ -> [] + end. + +std_func() -> +" +namespace Func = + + function id(x : 'a) : 'a = x + + function const(x : 'a) : 'b => 'a = (y) => x + + function flip(f : ('a, 'b) => 'c) : ('b, 'a) => 'c = (b, a) => f(a, b) + + function comp(f : 'b => 'c, g : 'a => 'b) : 'a => 'c = (x) => f(g(x)) + + function pipe(f : 'a => 'b, g : 'b => 'c) : 'a => 'c = (x) => g(f(x)) + + function rapply(x : 'a, f : 'a => 'b) : 'b = f(x) + + /* The Z combinator - replacement for local and anonymous recursion. + */ + function recur(f : ('arg => 'res, 'arg) => 'res) : 'arg => 'res = + (x) => f(recur(f), x) + + function iter(n : int, f : 'a => 'a) : 'a => 'a = iter_(n, f, (x) => x) + private function iter_(n : int, f : 'a => 'a, acc : 'a => 'a) : 'a => 'a = + if(n == 0) acc + elif(n == 1) comp(f, acc) + else iter_(n / 2, comp(f, f), if(n mod 2 == 0) acc else comp(f, acc)) + + function curry2(f : ('a, 'b) => 'c) : 'a => ('b => 'c) = + (x) => (y) => f(x, y) + function curry3(f : ('a, 'b, 'c) => 'd) : 'a => ('b => ('c => 'd)) = + (x) => (y) => (z) => f(x, y, z) + + function uncurry2(f : 'a => ('b => 'c)) : ('a, 'b) => 'c = + (x, y) => f(x)(y) + function uncurry3(f : 'a => ('b => ('c => 'd))) : ('a, 'b, 'c) => 'd = + (x, y, z) => f(x)(y)(z) + + function tuplify2(f : ('a, 'b) => 'c) : (('a * 'b)) => 'c = + (t) => switch(t) + (x, y) => f(x, y) + function tuplify3(f : ('a, 'b, 'c) => 'd) : 'a * 'b * 'c => 'd = + (t) => switch(t) + (x, y, z) => f(x, y, z) + + function untuplify2(f : 'a * 'b => 'c) : ('a, 'b) => 'c = + (x, y) => f((x, y)) + function untuplify3(f : 'a * 'b * 'c => 'd) : ('a, 'b, 'c) => 'd = + (x, y, z) => f((x, y, z)) +". + +std_list() ->" +namespace List = + + function is_empty(l : list('a)) : bool = switch(l) + [] => true + _ => false + + function first(l : list('a)) : option('a) = switch(l) + [] => None + h::_ => Some(h) + + function tail(l : list('a)) : option(list('a)) = switch(l) + [] => None + _::t => Some(t) + + function last(l : list('a)) : option('a) = switch(l) + [] => None + [x] => Some(x) + _::t => last(t) + + function find(p : 'a => bool, l : list('a)) : option('a) = switch(l) + [] => None + h::t => if(p(h)) Some(h) else find(p, t) + + function find_all(p : 'a => bool, l : list('a)) : list('a) = find_all_(p, l, []) + private function find_all_(p : 'a => bool, l : list('a), acc : list('a)) : list('a) = switch(l) + [] => reverse(acc) + h::t => find_all_(p, t, if(p(h)) h::acc else acc) + + function find_indices(p : 'a => bool, l : list('a)) : list(int) = find_indices_(p, l, 0, []) + private function find_indices_( p : 'a => bool + , l : list('a) + , n : int + , acc : list(int) + ) : list(int) = switch(l) + [] => reverse(acc) + h::t => find_indices_(p, t, n+1, if(p(h)) n::acc else acc) + + function nth(n : int, l : list('a)) : option('a) = switch(l) + [] => None + h::t => if(n == 0) Some(h) else nth(n-1, t) + + /* Unsafe version of `nth` */ + function get(n : int, l : list('a)) : 'a = switch(l) + [] => abort(\"Out of index get\") + h::t => if(n == 0) h else get(n-1, t) + + + function length(l : list('a)) : int = length_(l, 0) + private function length_(l : list('a), acc : int) : int = switch(l) + [] => acc + _::t => length_(t, acc + 1) + + + /* Unsafe. Replaces `n`th element of `l` with `e`. Crashes on over/underflow */ + function replace_at(n : int, e : 'a, l : list('a)) : list('a) = + if(n<0) abort(\"insert_at underflow\") else replace_at_(n, e, l, []) + private function replace_at_(n : int, e : 'a, l : list('a), acc : list('a)) : list('a) = + switch(l) + [] => abort(\"replace_at overflow\") + h::t => if (n == 0) reverse(e::acc) ++ t + else replace_at_(n-1, e, t, h::acc) + + /* Unsafe. Adds `e` to `l` to be its `n`th element. Crashes on over/underflow */ + function insert_at(n : int, e : 'a, l : list('a)) : list('a) = + if(n<0) abort(\"insert_at underflow\") else insert_at_(n, e, l, []) + private function insert_at_(n : int, e : 'a, l : list('a), acc : list('a)) : list('a) = + if (n == 0) reverse(e::acc) ++ l + else switch(l) + [] => abort(\"insert_at overflow\") + h::t => insert_at_(n-1, e, t, h::acc) + + function insert_by(f : (('a, 'a) => bool), x : 'a, l : list('a)) : list('a) = + switch(l) + [] => [x] + (e :: l') => + if(f(x, e)) + e :: insert_by(f, x, l') + else + x :: l + + function foldr(cons : ('a, 'b) => 'b, nil : 'b, l : list('a)) : 'b = switch(l) + [] => nil + h::t => cons(h, foldr(cons, nil, t)) + + function foldl(rcons : ('b, 'a) => 'b, acc : 'b, l : list('a)) : 'b = switch(l) + [] => acc + h::t => foldl(rcons, rcons(acc, h), t) + + function foreach(f : 'a => unit, l : list('a)) : unit = + switch(l) + [] => () + e :: l' => + f(e) + foreach(f, l') + + + function reverse(l : list('a)) : list('a) = foldl((lst, el) => el :: lst, [], l) + + + function map(f : 'a => 'b, l : list('a)) : list('b) = map_(f, l, []) + private function map_(f : 'a => 'b, l : list('a), acc : list('b)) : list('b) = switch(l) + [] => reverse(acc) + h::t => map_(f, t, f(h)::acc) + + function flat_map(f : 'a => list('b), l : list('a)) : list('b) = flat_map_(f, l, []) + private function flat_map_(f : 'a => list('b), l : list('a), acc : list('b)) : list('b) = switch(l) + [] => reverse(acc) + h::t => flat_map_(f, t, reverse(f(h)) ++ acc) + + function filter(p : 'a => bool, l : list('a)) : list('a) = filter_(p, l, []) + private function filter_(p : 'a => bool, l : list('a), acc : list('a)) : list('a) = switch(l) + [] => reverse(acc) + h::t => filter_(p, t, if(p(h)) h::acc else acc) + + /* Take `n` first elements */ + function take(n : int, l : list('a)) : list('a) = + if(n < 0) abort(\"Take negative number of elements\") else take_(n, l, []) + private function take_(n : int, l : list('a), acc : list('a)) : list('a) = + if(n == 0) reverse(acc) + else switch(l) + [] => reverse(acc) + h::t => take_(n-1, t, h::acc) + + /* Drop `n` first elements */ + function drop(n : int, l : list('a)) : list('a) = + if(n < 0) abort(\"Drop negative number of elements\") + elif (n == 0) l + else switch(l) + [] => [] + h::t => drop(n-1, t) + + /* Get the longest prefix of a list in which every element matches predicate `p` */ + function take_while(p : 'a => bool, l : list('a)) : list('a) = take_while_(p, l, []) + private function take_while_(p : 'a => bool, l : list('a), acc : list('a)) : list('a) = switch(l) + [] => reverse(acc) + h::t => if(p(h)) take_while_(p, t, h::acc) else reverse(acc) + + /* Drop elements from `l` until `p` holds */ + function drop_while(p : 'a => bool, l : list('a)) : list('a) = switch(l) + [] => [] + h::t => if(p(h)) drop_while(p, t) else l + + /* Splits list into two lists of elements that respectively match and don't match predicate `p` */ + function partition(p : 'a => bool, l : list('a)) : (list('a) * list('a)) = partition_(p, l, [], []) + private function partition_( p : 'a => bool + , l : list('a) + , acc_t : list('a) + , acc_f : list('a) + ) : (list('a) * list('a)) = switch(l) + [] => (reverse(acc_t), reverse(acc_f)) + h::t => if(p(h)) partition_(p, t, h::acc_t, acc_f) else partition_(p, t, acc_t, h::acc_f) + + + function concats(ll : list(list('a))) : list('a) = foldr((l1, l2) => l1 ++ l2, [], ll) + + function all(p : 'a => bool, l : list('a)) : bool = switch(l) + [] => true + h::t => if(p(h)) all(p, t) else false + + function any(p : 'a => bool, l : list('a)) : bool = switch(l) + [] => false + h::t => if(p(h)) true else any(p, t) + + function sum(l : list(int)) : int = foldl ((a, b) => a + b, 0, l) + + function product(l : list(int)) : int = foldl((a, b) => a * b, 1, l) + + + /* Zips two list by applying bimapping function on respective elements. Drops longer tail. */ + function zip_with(f : ('a, 'b) => 'c, l1 : list('a), l2 : list('b)) : list('c) = zip_with_(f, l1, l2, []) + private function zip_with_( f : ('a, 'b) => 'c + , l1 : list('a) + , l2 : list('b) + , acc : list('c) + ) : list('c) = switch ((l1, l2)) + (h1::t1, h2::t2) => zip_with_(f, t1, t2, f(h1, h2)::acc) + _ => reverse(acc) + + /* Zips two lists into list of pairs. Drops longer tail. */ + function zip(l1 : list('a), l2 : list('b)) : list('a * 'b) = zip_with((a, b) => (a, b), l1, l2) + + function unzip(l : list('a * 'b)) : list('a) * list('b) = unzip_(l, [], []) + private function unzip_( l : list('a * 'b) + , acc_l : list('a) + , acc_r : list('b) + ) : (list('a) * list('b)) = switch(l) + [] => (reverse(acc_l), reverse(acc_r)) + (left, right)::t => unzip_(t, left::acc_l, right::acc_r) + + + // TODO: Improve? + function sort(lesser_cmp : ('a, 'a) => bool, l : list('a)) : list('a) = switch(l) + [] => [] + h::t => switch (partition((x) => lesser_cmp(x, h), t)) + (lesser, bigger) => sort(lesser_cmp, lesser) ++ h::sort(lesser_cmp, bigger) + + + function intersperse(delim : 'a, l : list('a)) : list('a) = intersperse_(delim, l, []) + private function intersperse_(delim : 'a, l : list('a), acc : list('a)) : list('a) = switch(l) + [] => reverse(acc) + [e] => reverse(e::acc) + h::t => intersperse_(delim, t, h::delim::acc) + + + function enumerate(l : list('a)) : list(int * 'a) = enumerate_(l, 0, []) + private function enumerate_(l : list('a), n : int, acc : list(int * 'a)) : list(int * 'a) = switch(l) + [] => reverse(acc) + h::t => enumerate_(t, n + 1, (n, h)::acc) + +". + +std_option() -> " +namespace Option = + + function is_none(o : option('a)) : bool = switch(o) + None => true + Some(_) => false + + function is_some(o : option('a)) : bool = switch(o) + None => false + Some(_) => true + + + function match(n : 'b, s : 'a => 'b, o : option('a)) : 'b = switch(o) + None => n + Some(x) => s(x) + + function default(def : 'a, o : option('a)) : 'a = match(def, (x) => x, o) + + function force(o : option('a)) : 'a = default(abort(\"Forced None value\"), o) + + function on_elem(f : 'a => unit, o : option('a)) : unit = match((), f, o) + + + function map(f : 'a => 'b, o : option('a)) : option('b) = switch(o) + None => None + Some(x) => Some(f(x)) + + function map2(f : ('a, 'b) => 'c + , o1 : option('a) + , o2 : option('b) + ) : option('c) = switch((o1, o2)) + (Some(x1), Some(x2)) => Some(f(x1, x2)) + _ => None + + function map3( f : ('a, 'b, 'c) => 'd + , o1 : option('a) + , o2 : option('b) + , o3 : option('c) + ) : option('d) = switch((o1, o2, o3)) + (Some(x1), Some(x2), Some(x3)) => Some(f(x1, x2, x3)) + _ => None + + function app_over(f : option ('a => 'b), o : option('a)) : option('b) = switch((f, o)) + (Some(ff), Some(xx)) => Some(ff(xx)) + _ => None + + function flat_map(f : 'a => option('b), o : option('a)) : option('b) = switch(o) + None => None + Some(x) => f(x) + + + function to_list(o : option('a)) : list('a) = switch(o) + None => [] + Some(x) => [x] + + function filter_options(l : list(option('a))) : list('a) = filter_options_(l, []) + private function filter_options_(l : list (option('a)), acc : list('a)) : list('a) = switch(l) + [] => List.reverse(acc) + None::t => filter_options_(t, acc) + Some(x)::t => filter_options_(t, x::acc) + + function seq_options(l : list (option('a))) : option (list('a)) = seq_options_(l, []) + private function seq_options_(l : list (option('a)), acc : list('a)) : option(list('a)) = switch(l) + [] => Some(List.reverse(acc)) + None::t => None + Some(x)::t => seq_options_(t, x::acc) + + + function choose(o1 : option('a), o2 : option('a)) : option('a) = + if(is_some(o1)) o1 else o2 + + function choose_first(l : list(option('a))) : option('a) = switch(l) + [] => None + None::t => choose_first(t) + Some(x)::_ => Some(x) +". + +std_pair() -> " +namespace Pair = + + function fst(t : ('a * 'b)) : 'a = switch(t) + (x, _) => x + + function snd(t : ('a * 'b)) : 'b = switch(t) + (_, y) => y + + + function map1(f : 'a => 'c, t : ('a * 'b)) : ('c * 'b) = switch(t) + (x, y) => (f(x), y) + + function map2(f : 'b => 'c, t : ('a * 'b)) : ('a * 'c) = switch(t) + (x, y) => (x, f(y)) + + function bimap(f : 'a => 'c, g : 'b => 'd, t : ('a * 'b)) : ('c * 'd) = switch(t) + (x, y) => (f(x), g(y)) + + + function swap(t : ('a * 'b)) : ('b * 'a) = switch(t) + (x, y) => (y, x) +". + +std_triple() -> " +namespace Triple = + + function fst(t : ('a * 'b * 'c)) : 'a = switch(t) + (x, _, _) => x + + function snd(t : ('a * 'b * 'c)) : 'b = switch(t) + (_, y, _) => y + + function thd(t : ('a * 'b * 'c)) : 'c = switch(t) + (_, _, z) => z + + + function map1(f : 'a => 'm, t : ('a * 'b * 'c)) : ('m * 'b * 'c) = switch(t) + (x, y, z) => (f(x), y, z) + + function map2(f : 'b => 'm, t : ('a * 'b * 'c)) : ('a * 'm * 'c) = switch(t) + (x, y, z) => (x, f(y), z) + + function map3(f : 'c => 'm, t : ('a * 'b * 'c)) : ('a * 'b * 'm) = switch(t) + (x, y, z) => (x, y, f(z)) + + function trimap( f : 'a => 'x + , g : 'b => 'y + , h : 'c => 'z + , t : ('a * 'b * 'c) + ) : ('x * 'y * 'z) = switch(t) + (x, y, z) => (f(x), g(y), h(z)) + + + function swap(t : ('a * 'b * 'c)) : ('c * 'b * 'a) = switch(t) + (x, y, z) => (z, y, x) + + function rotr(t : ('a * 'b * 'c)) : ('c * 'a * 'b) = switch(t) + (x, y, z) => (z, x, y) + + function rotl(t : ('a * 'b * 'c)) : ('b * 'c * 'a) = switch(t) + (x, y, z) => (y, z, x) +". diff --git a/src/aeso_syntax.erl b/src/aeso_syntax.erl index 5c9e81c..403dfaa 100644 --- a/src/aeso_syntax.erl +++ b/src/aeso_syntax.erl @@ -92,6 +92,7 @@ | {proj, ann(), expr(), id()} | {tuple, ann(), [expr()]} | {list, ann(), [expr()]} + | {list_comp, ann(), expr(), [comprehension_exp()]} | {typed, ann(), expr(), type()} | {record, ann(), [field(expr())]} | {record, ann(), expr(), [field(expr())]} %% record update @@ -104,6 +105,10 @@ | id() | qid() | con() | qcon() | constant(). +-type comprehension_exp() :: [{ comprehension_bind, ann(), id(), expr()} + | {comprehension_if, expr()} + | letbind()]. + -type arg_expr() :: expr() | {named_arg, ann(), id(), expr()}. %% When lvalue is a projection this is sugar for accessing fields in nested diff --git a/test/aeso_abi_tests.erl b/test/aeso_abi_tests.erl index c7e0c57..9d0a022 100644 --- a/test/aeso_abi_tests.erl +++ b/test/aeso_abi_tests.erl @@ -80,11 +80,11 @@ encode_decode_sophia_string(SophiaType, String) -> , " record r = {x : an_alias(int), y : variant}\n" , " datatype variant = Red | Blue(map(string, int))\n" , " entrypoint foo : arg_type => arg_type\n" ], - case aeso_compiler:check_call(lists:flatten(Code), "foo", [String], []) of + case aeso_compiler:check_call(lists:flatten(Code), "foo", [String], [no_implicit_stdlib]) of {ok, _, {[Type], _}, [Arg]} -> io:format("Type ~p~n", [Type]), Data = encode(Arg), - case aeso_compiler:to_sophia_value(Code, "foo", ok, Data) of + case aeso_compiler:to_sophia_value(Code, "foo", ok, Data, [no_implicit_stdlib]) of {ok, Sophia} -> lists:flatten(io_lib:format("~s", [prettypr:format(aeso_pretty:expr(Sophia))])); {error, Err} -> @@ -152,7 +152,7 @@ oracle_test() -> " Oracle.get_question(o, q)\n", {ok, _, {[word, word], {list, string}}, [16#123, 16#456]} = aeso_compiler:check_call(Contract, "question", ["ok_111111111111111111111111111111ZrdqRz9", - "oq_1111111111111111111111111111113AFEFpt5"], []), + "oq_1111111111111111111111111111113AFEFpt5"], [no_implicit_stdlib]), ok. @@ -162,7 +162,7 @@ permissive_literals_fail_test() -> " stateful entrypoint haxx(o : oracle(list(string), option(int))) =\n" " Chain.spend(o, 1000000)\n", {error, <<"Type errors\nCannot unify", _/binary>>} = - aeso_compiler:check_call(Contract, "haxx", ["#123"], []), + aeso_compiler:check_call(Contract, "haxx", ["#123"], [no_implicit_stdlib]), ok. encode_decode_calldata(FunName, Types, Args) -> @@ -173,8 +173,8 @@ encode_decode_calldata(FunName, Types, Args, RetType) -> encode_decode_calldata_(Code, FunName, Args, RetType). encode_decode_calldata_(Code, FunName, Args, RetVMType) -> - {ok, Calldata} = aeso_compiler:create_calldata(Code, FunName, Args), - {ok, _, {ArgTypes, RetType}, _} = aeso_compiler:check_call(Code, FunName, Args, [{backend, aevm}]), + {ok, Calldata} = aeso_compiler:create_calldata(Code, FunName, Args, [no_implicit_stdlib]), + {ok, _, {ArgTypes, RetType}, _} = aeso_compiler:check_call(Code, FunName, Args, [{backend, aevm}, no_implicit_stdlib]), ?assertEqual(RetType, RetVMType), CalldataType = {tuple, [word, {tuple, ArgTypes}]}, {ok, {_Hash, ArgTuple}} = aeb_heap:from_binary(CalldataType, Calldata), @@ -182,7 +182,7 @@ encode_decode_calldata_(Code, FunName, Args, RetVMType) -> "init" -> ok; _ -> - {ok, _ArgTypes, ValueASTs} = aeso_compiler:decode_calldata(Code, FunName, Calldata), + {ok, _ArgTypes, ValueASTs} = aeso_compiler:decode_calldata(Code, FunName, Calldata, [no_implicit_stdlib]), Values = [ prettypr:format(aeso_pretty:expr(V)) || V <- ValueASTs ], ?assertMatch({X, X}, {Args, Values}) end, diff --git a/test/aeso_aci_tests.erl b/test/aeso_aci_tests.erl index ee719be..6f348fd 100644 --- a/test/aeso_aci_tests.erl +++ b/test/aeso_aci_tests.erl @@ -9,7 +9,7 @@ simple_aci_test_() -> test_contract(N) -> {Contract,MapACI,DecACI} = test_cases(N), - {ok,JSON} = aeso_aci:contract_interface(json, Contract), + {ok,JSON} = aeso_aci:contract_interface(json, Contract, [no_implicit_stdlib]), ?assertEqual([MapACI], JSON), ?assertEqual({ok, DecACI}, aeso_aci:render_aci_json(JSON)). @@ -87,7 +87,8 @@ aci_test_() -> fun() -> aci_test_contract(ContractName) end} || ContractName <- all_contracts()]. -all_contracts() -> aeso_compiler_tests:compilable_contracts(). +all_contracts() -> [C || C <- aeso_compiler_tests:compilable_contracts() + , not aeso_compiler_tests:wants_stdlib(C)]. aci_test_contract(Name) -> String = aeso_test_utils:read_contract(Name), diff --git a/test/aeso_calldata_tests.erl b/test/aeso_calldata_tests.erl index a68f3b9..7fab206 100644 --- a/test/aeso_calldata_tests.erl +++ b/test/aeso_calldata_tests.erl @@ -21,12 +21,14 @@ calldata_test_() -> ContractString = aeso_test_utils:read_contract(ContractName), AevmExprs = case not lists:member(ContractName, not_yet_compilable(aevm)) of - true -> ast_exprs(ContractString, Fun, Args, [{backend, aevm}]); + true -> ast_exprs(ContractString, Fun, Args, [{backend, aevm}] + ++ [no_implicit_stdlib || not aeso_compiler_tests:wants_stdlib(ContractName)]); false -> undefined end, FateExprs = case not lists:member(ContractName, not_yet_compilable(fate)) of - true -> ast_exprs(ContractString, Fun, Args, [{backend, fate}]); + true -> ast_exprs(ContractString, Fun, Args, [{backend, fate}] + ++ [no_implicit_stdlib || not aeso_compiler_tests:wants_stdlib(ContractName)]); false -> undefined end, case FateExprs == undefined orelse AevmExprs == undefined of @@ -45,12 +47,14 @@ calldata_aci_test_() -> io:format("ACI:\n~s\n", [ContractACIBin]), AevmExprs = case not lists:member(ContractName, not_yet_compilable(aevm)) of - true -> ast_exprs(ContractACI, Fun, Args, [{backend, aevm}]); + true -> ast_exprs(ContractACI, Fun, Args, [{backend, aevm}] + ++ [no_implicit_stdlib || not aeso_compiler_tests:wants_stdlib(ContractName)]); false -> undefined end, FateExprs = case not lists:member(ContractName, not_yet_compilable(fate)) of - true -> ast_exprs(ContractACI, Fun, Args, [{backend, fate}]); + true -> ast_exprs(ContractACI, Fun, Args, [{backend, fate}] + ++ [no_implicit_stdlib || not aeso_compiler_tests:wants_stdlib(ContractName)]); false -> undefined end, case FateExprs == undefined orelse AevmExprs == undefined of diff --git a/test/aeso_compiler_tests.erl b/test/aeso_compiler_tests.erl index 911e635..47f0efb 100644 --- a/test/aeso_compiler_tests.erl +++ b/test/aeso_compiler_tests.erl @@ -73,7 +73,9 @@ check_errors(Expect, ErrorString) -> end. compile(Backend, Name) -> - compile(Backend, Name, [{include, {file_system, [aeso_test_utils:contract_path()]}}]). + compile(Backend, Name, + [{include, {file_system, [aeso_test_utils:contract_path()]}}] + ++ [no_implicit_stdlib || not wants_stdlib(Name)]). compile(Backend, Name, Options) -> String = aeso_test_utils:read_contract(Name), @@ -118,7 +120,12 @@ compilable_contracts() -> "namespace_bug", "bytes_to_x", "aens", - "tuple_match" + "tuple_match", + "cyclic_include", + "stdlib_include", + "double_include", + "manual_stdlib_include", + "list_comp" ]. not_yet_compilable(fate) -> []; @@ -354,4 +361,23 @@ failing_contracts() -> <<"Use 'entrypoint' for declaration of foo (at line 6, column 3):\n entrypoint foo : () => unit">>, <<"Use 'entrypoint' instead of 'function' for public function foo (at line 10, column 3):\n entrypoint foo() = ()">>, <<"Use 'entrypoint' instead of 'function' for public function foo (at line 6, column 3):\n entrypoint foo : () => unit">>]} + , {"list_comp_not_a_list", + [<<"Cannot unify int\n and list('a)\nwhen checking rvalue of list comprehension binding at line 2, column 36\n 1 : int\nagainst type \n list('a)">> + ]} + , {"list_comp_if_not_bool", + [<<"Cannot unify int\n and bool\nwhen checking the type of the expression at line 2, column 44\n 3 : int\nagainst the expected type\n bool">> + ]} + , {"list_comp_bad_shadow", + [<<"Cannot unify int\n and string\nwhen checking the type of the pattern at line 2, column 53\n x : int\nagainst the expected type\n string">> + ]} ]. + +wants_stdlib(Name) -> + lists:member + (Name, + [ "stdlib_include", + "list_comp", + "list_comp_not_a_list", + "list_comp_if_not_bool", + "list_comp_bad_shadow" + ]). diff --git a/test/aeso_parser_tests.erl b/test/aeso_parser_tests.erl index dcbbcd0..9b54d94 100644 --- a/test/aeso_parser_tests.erl +++ b/test/aeso_parser_tests.erl @@ -15,7 +15,7 @@ simple_contracts_test_() -> ?assertMatch( [{contract, _, {con, _, "Identity"}, [{letfun, _, {id, _, "id"}, [{arg, _, {id, _, "x"}, {id, _, "_"}}], {id, _, "_"}, - {id, _, "x"}}]}], parse_string(Text)), + {id, _, "x"}}]}], parse_string(Text, [no_implicit_stdlib])), ok end}, {"Operator precedence test.", @@ -71,21 +71,23 @@ parse_contract(Name) -> roundtrip_contract(Name) -> round_trip(aeso_test_utils:read_contract(Name)). -parse_string(Text) -> - case aeso_parser:string(Text) of +parse_string(Text) -> parse_string(Text, []). + +parse_string(Text, Opts) -> + case aeso_parser:string(Text, Opts) of {ok, Contract} -> Contract; Err -> error(Err) end. parse_expr(Text) -> [{letval, _, _, _, Expr}] = - parse_string("let _ = " ++ Text), + parse_string("let _ = " ++ Text, [no_implicit_stdlib]), Expr. round_trip(Text) -> - Contract = parse_string(Text), + Contract = parse_string(Text, [no_implicit_stdlib]), Text1 = prettypr:format(aeso_pretty:decls(Contract)), - Contract1 = parse_string(Text1), + Contract1 = parse_string(Text1, [no_implicit_stdlib]), NoSrcLoc = remove_line_numbers(Contract), NoSrcLoc1 = remove_line_numbers(Contract1), ?assertMatch(NoSrcLoc, diff(NoSrcLoc, NoSrcLoc1)). diff --git a/test/contracts/cyclic_include.aes b/test/contracts/cyclic_include.aes new file mode 100644 index 0000000..3cc2cfb --- /dev/null +++ b/test/contracts/cyclic_include.aes @@ -0,0 +1,4 @@ +include "cyclic_include_forth.aes" + +contract CI = + entrypoint ci() = Back.back() + Forth.forth() diff --git a/test/contracts/cyclic_include_back.aes b/test/contracts/cyclic_include_back.aes new file mode 100644 index 0000000..fd92a15 --- /dev/null +++ b/test/contracts/cyclic_include_back.aes @@ -0,0 +1,4 @@ +include "cyclic_include_forth.aes" + +namespace Back = + function back() = 2 diff --git a/test/contracts/cyclic_include_forth.aes b/test/contracts/cyclic_include_forth.aes new file mode 100644 index 0000000..765a87d --- /dev/null +++ b/test/contracts/cyclic_include_forth.aes @@ -0,0 +1,4 @@ +include "cyclic_include_back.aes" + +namespace Forth = + function forth() = 3 diff --git a/test/contracts/deadcode.aes b/test/contracts/deadcode.aes index 450e52a..c94ef6d 100644 --- a/test/contracts/deadcode.aes +++ b/test/contracts/deadcode.aes @@ -1,5 +1,5 @@ -namespace List = +namespace MyList = function map1(f : 'a => 'b, xs : list('a)) = switch(xs) @@ -14,8 +14,8 @@ namespace List = contract Deadcode = entrypoint inc1(xs : list(int)) : list(int) = - List.map1((x) => x + 1, xs) + MyList.map1((x) => x + 1, xs) entrypoint inc2(xs : list(int)) : list(int) = - List.map1((x) => x + 1, xs) + MyList.map1((x) => x + 1, xs) diff --git a/test/contracts/double_include.aes b/test/contracts/double_include.aes new file mode 100644 index 0000000..e9818b0 --- /dev/null +++ b/test/contracts/double_include.aes @@ -0,0 +1,7 @@ +include "included.aes" +include "../contracts/included.aes" + +contract Include = + entrypoint foo() = + Included.foo() + diff --git a/test/contracts/list_comp.aes b/test/contracts/list_comp.aes new file mode 100644 index 0000000..266f2e8 --- /dev/null +++ b/test/contracts/list_comp.aes @@ -0,0 +1,23 @@ +contract ListComp = + + entrypoint sample1() = [1,2,3] + entrypoint sample2() = [4,5] + + entrypoint l1() = [x | x <- sample1()] + entrypoint l1_true() = [1,2,3] + + entrypoint l2() = [x + y | x <- sample1(), y <- sample2()] + entrypoint l2_true() = [5,6,6,7,7,8] + + entrypoint l3() = [x ++ y | x <- [[":)"] | x <- [1,2]] + , y <- [[":("]]] + entrypoint l3_true() = [[":)", ":("], [":)", ":("]] + + entrypoint l4() = [(a, b, c) | let is_pit(a, b, c) = a*a + b*b == c*c + , let base = [1,2,3,4,5,6,7,8,9,10] + , a <- base + , b <- base, if (b >= a) + , c <- base, if (c >= b) + , if (is_pit(a, b, c)) + ] + entrypoint l4_true() = [(3, 4, 5), (6, 8, 10)] diff --git a/test/contracts/list_comp_bad_shadow.aes b/test/contracts/list_comp_bad_shadow.aes new file mode 100644 index 0000000..b54735c --- /dev/null +++ b/test/contracts/list_comp_bad_shadow.aes @@ -0,0 +1,2 @@ +contract BadComp = + entrypoint failing() = [x + 1 | x <- [1,2,3], let x = "XD"] diff --git a/test/contracts/list_comp_if_not_bool.aes b/test/contracts/list_comp_if_not_bool.aes new file mode 100644 index 0000000..cd3c458 --- /dev/null +++ b/test/contracts/list_comp_if_not_bool.aes @@ -0,0 +1,2 @@ +contract BadComp = + entrypoint failing() = [x | x <- [], if (3)] diff --git a/test/contracts/list_comp_not_a_list.aes b/test/contracts/list_comp_not_a_list.aes new file mode 100644 index 0000000..41321cb --- /dev/null +++ b/test/contracts/list_comp_not_a_list.aes @@ -0,0 +1,2 @@ +contract ListCompBad = + entrypoint failing() = [x | x <- 1] diff --git a/test/contracts/manual_stdlib_include.aes b/test/contracts/manual_stdlib_include.aes new file mode 100644 index 0000000..5937c37 --- /dev/null +++ b/test/contracts/manual_stdlib_include.aes @@ -0,0 +1,7 @@ +// This contract should be compiled with no_implicit_stdlib option. +// It should include Lists.aes implicitly however, because Option.aes depends on it. +include "Option.aes" + +contract Test = + entrypoint i_should_build() = + List.is_empty(Option.to_list(None)) diff --git a/test/contracts/multi_sig.aes b/test/contracts/multi_sig.aes index 028b621..cb1363f 100644 --- a/test/contracts/multi_sig.aes +++ b/test/contracts/multi_sig.aes @@ -28,8 +28,8 @@ contract MultiSig = let n = length(owners) + 1 { nRequired = nRequired, nOwners = n, - owners = Map.from_list(List.zip([1..n], caller() :: owners)), - ownerIndex = Map.from_list(List.zip(caller() :: owners, [1..n])) } + owners = Map.from_list(MyList.zip([1..n], caller() :: owners)), + ownerIndex = Map.from_list(MyList.zip(caller() :: owners, [1..n])) } function lookup(map, key) = switch(Map.get(key, map)) diff --git a/test/contracts/nodeadcode.aes b/test/contracts/nodeadcode.aes index 76f6f3b..b7df43f 100644 --- a/test/contracts/nodeadcode.aes +++ b/test/contracts/nodeadcode.aes @@ -1,5 +1,5 @@ -namespace List = +namespace MyList = function map1(f : 'a => 'b, xs : list('a)) = switch(xs) @@ -14,8 +14,8 @@ namespace List = contract Deadcode = entrypoint inc1(xs : list(int)) : list(int) = - List.map1((x) => x + 1, xs) + MyList.map1((x) => x + 1, xs) entrypoint inc2(xs : list(int)) : list(int) = - List.map2((x) => x + 1, xs) + MyList.map2((x) => x + 1, xs) diff --git a/test/contracts/reason/voting.re b/test/contracts/reason/voting.re index 5736350..6739af7 100644 --- a/test/contracts/reason/voting.re +++ b/test/contracts/reason/voting.re @@ -47,7 +47,7 @@ module Voting : Voting = { let init(proposalNames: args): state = { chairPerson: caller(), voters: AddrMap.empty, - proposals: List.map((name) => {name: name, voteCount: 0}, proposalNames) + proposals: MyList.map((name) => {name: name, voteCount: 0}, proposalNames) }; /* Boilerplate */ @@ -73,7 +73,7 @@ module Voting : Voting = { }; let addVote(candidate, weight) = { - let proposal = List.nth(state().proposals, candidate); + let proposal = MyList.nth(state().proposals, candidate); proposal.voteCount = proposal.voteCount + weight; }; @@ -121,6 +121,6 @@ module Voting : Voting = { /* const */ let currentTally() = - List.map((p) => (p.name, p.voteCount), state().proposals); + MyList.map((p) => (p.name, p.voteCount), state().proposals); } diff --git a/test/contracts/reason/voting_test.re b/test/contracts/reason/voting_test.re index 85cd587..c0b7420 100644 --- a/test/contracts/reason/voting_test.re +++ b/test/contracts/reason/voting_test.re @@ -13,7 +13,7 @@ open Voting; let print_tally() = { let tally = call(other, () => currentTally()); - List.map(((name, count)) => Printf.printf("%s: %d\n", name, count), tally); + MyList.map(((name, count)) => Printf.printf("%s: %d\n", name, count), tally); let winner = call(other, () => winnerName()); Printf.printf("Winner: %s\n", winner); }; diff --git a/test/contracts/stdlib_include.aes b/test/contracts/stdlib_include.aes new file mode 100644 index 0000000..6149db2 --- /dev/null +++ b/test/contracts/stdlib_include.aes @@ -0,0 +1,3 @@ +contract StdInc = + entrypoint test() = List.map((x) => Func.id(x), [1,2,3,4]) + diff --git a/test/contracts/voting.aes b/test/contracts/voting.aes index 0154e28..d786f6d 100644 --- a/test/contracts/voting.aes +++ b/test/contracts/voting.aes @@ -36,7 +36,7 @@ contract Voting = function init(proposalNames: list(string)): state = { chairPerson = caller(), voters = Map.empty, - proposals = List.map((name) => {name = name, voteCount = 0}, proposalNames) } + proposals = MyList.map((name) => {name = name, voteCount = 0}, proposalNames) } function initVoter() = { weight = 1, vote = NotVoted} @@ -53,7 +53,7 @@ contract Voting = _ => delegate function addVote(candidate, weight) = - let proposal = List.nth(state.proposals, candidate) + let proposal = MyList.nth(state.proposals, candidate) proposal{ voteCount = proposal.voteCount + weight } function delegateVote(delegateTo: address, weight: uint) = @@ -93,5 +93,5 @@ contract Voting = // const function currentTally() = - List.map((p) => (p.name, p.voteCount), state.proposals) + MyList.map((p) => (p.name, p.voteCount), state.proposals)