Compare commits
36 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4b0a3e53d6 | |||
| 07c445082a | |||
| 4f612650e3 | |||
| 80ed24a4f6 | |||
| 05256eeb60 | |||
| 7592390059 | |||
| bb4ef61a50 | |||
| bb5a710626 | |||
| 758fecbb9b | |||
| b1e882b115 | |||
| bea524635b | |||
| e44a890292 | |||
| d3a13eafed | |||
| 0532c54ca0 | |||
| 02d0025fd7 | |||
| 0409a658b0 | |||
| c045e5d653 | |||
| a95913e793 | |||
| ec678878fa | |||
| 4b0837dc59 | |||
| ed96dc1d42 | |||
| 60d9581fae | |||
| 0ded431df8 | |||
| e7419b79fd | |||
| c60999edf0 | |||
| ea17dae93e | |||
| 8a16bd4fa1 | |||
| 1ed40f1cca | |||
| 5c98317a5a | |||
| 33dbeeefad | |||
| 098dac65e2 | |||
| 9cf8733f77 | |||
| 98f349f67c | |||
| 96547ea2ec | |||
| ee03442ddf | |||
| 0fa09467f6 |
+18
-1
@@ -9,6 +9,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
### Changed
|
### Changed
|
||||||
### Removed
|
### Removed
|
||||||
|
|
||||||
|
## [3.1.0] - 2019-06-03
|
||||||
|
### Added
|
||||||
|
### Changed
|
||||||
|
- Keyword `indexed` is now optional for word typed (`bool`, `int`, `address`,
|
||||||
|
...) event arguments.
|
||||||
|
- State variable pretty printing now produce `'a, 'b, ...` instead of `'1, '2, ...`.
|
||||||
|
- ACI is restructured and improved:
|
||||||
|
- `state` and `event` types (if present) now appear at the top level.
|
||||||
|
- Namespaces and remote interfaces are no longer ignored.
|
||||||
|
- All type definitions are included in the interface rendering.
|
||||||
|
- API functions are renamed, new functions are `contract_interface`
|
||||||
|
and `render_aci_json`.
|
||||||
|
- Fixed a bug in `create_calldata`/`to_sophia_value` - it can now handle negative
|
||||||
|
literals.
|
||||||
|
### Removed
|
||||||
|
|
||||||
## [3.0.0] - 2019-05-21
|
## [3.0.0] - 2019-05-21
|
||||||
### Added
|
### Added
|
||||||
- `stateful` annotations are now properly enforced. Functions must be marked stateful
|
- `stateful` annotations are now properly enforced. Functions must be marked stateful
|
||||||
@@ -55,7 +71,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
- Simplify calldata creation - instead of passing a compiled contract, simply
|
- Simplify calldata creation - instead of passing a compiled contract, simply
|
||||||
pass a (stubbed) contract string.
|
pass a (stubbed) contract string.
|
||||||
|
|
||||||
[Unreleased]: https://github.com/aeternity/aesophia/compare/v3.0.0...HEAD
|
[Unreleased]: https://github.com/aeternity/aesophia/compare/v3.1.0...HEAD
|
||||||
|
[3.1.0]: https://github.com/aeternity/aesophia/compare/v3.0.0...v3.1.0
|
||||||
[3.0.0]: https://github.com/aeternity/aesophia/compare/v2.1.0...v3.0.0
|
[3.0.0]: https://github.com/aeternity/aesophia/compare/v2.1.0...v3.0.0
|
||||||
[2.1.0]: https://github.com/aeternity/aesophia/compare/v2.0.0...v2.1.0
|
[2.1.0]: https://github.com/aeternity/aesophia/compare/v2.0.0...v2.1.0
|
||||||
[2.0.0]: https://github.com/aeternity/aesophia/tag/v2.0.0
|
[2.0.0]: https://github.com/aeternity/aesophia/tag/v2.0.0
|
||||||
|
|||||||
+76
-55
@@ -30,28 +30,14 @@ generates the following JSON structure representing the contract interface:
|
|||||||
``` json
|
``` json
|
||||||
{
|
{
|
||||||
"contract": {
|
"contract": {
|
||||||
"name": "Answers",
|
|
||||||
"type_defs": [
|
|
||||||
{
|
|
||||||
"name": "state",
|
|
||||||
"vars": [],
|
|
||||||
"typedef": "{a : map(string,int)}"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "answers",
|
|
||||||
"vars": [],
|
|
||||||
"typedef": "map(string,int)"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"functions": [
|
"functions": [
|
||||||
{
|
{
|
||||||
"name": "init",
|
|
||||||
"arguments": [],
|
"arguments": [],
|
||||||
"type": "{a : map(string,int)}",
|
"name": "init",
|
||||||
|
"returns": "Answers.state",
|
||||||
"stateful": true
|
"stateful": true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "new_answer",
|
|
||||||
"arguments": [
|
"arguments": [
|
||||||
{
|
{
|
||||||
"name": "q",
|
"name": "q",
|
||||||
@@ -62,9 +48,36 @@ generates the following JSON structure representing the contract interface:
|
|||||||
"type": "int"
|
"type": "int"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"type": "map(string,int)",
|
"name": "new_answer",
|
||||||
|
"returns": {
|
||||||
|
"map": [
|
||||||
|
"string",
|
||||||
|
"int"
|
||||||
|
]
|
||||||
|
},
|
||||||
"stateful": false
|
"stateful": false
|
||||||
}
|
}
|
||||||
|
],
|
||||||
|
"name": "Answers",
|
||||||
|
"state": {
|
||||||
|
"record": [
|
||||||
|
{
|
||||||
|
"name": "a",
|
||||||
|
"type": "Answers.answers"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"type_defs": [
|
||||||
|
{
|
||||||
|
"name": "answers",
|
||||||
|
"typedef": {
|
||||||
|
"map": [
|
||||||
|
"string",
|
||||||
|
"int"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"vars": []
|
||||||
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -74,62 +87,70 @@ When that encoding is decoded the following include definition is generated:
|
|||||||
|
|
||||||
```
|
```
|
||||||
contract Answers =
|
contract Answers =
|
||||||
function new_answer : (string, int) => map(string,int)
|
record state = {a : Answers.answers}
|
||||||
|
type answers = map(string, int)
|
||||||
|
function init : () => Answers.state
|
||||||
|
function new_answer : (string, int) => map(string, int)
|
||||||
```
|
```
|
||||||
|
|
||||||
### Types
|
### Types
|
||||||
``` erlang
|
```erlang
|
||||||
contract_string() = string() | binary()
|
-type aci_type() :: json | string.
|
||||||
json_string() = binary()
|
-type json() :: jsx:json_term().
|
||||||
|
-type json_text() :: binary().
|
||||||
```
|
```
|
||||||
|
|
||||||
### Exports
|
### Exports
|
||||||
|
|
||||||
#### encode(ContractString) -> {ok,JSONstring} | {error,ErrorString}
|
#### contract\_interface(aci\_type(), string()) -> {ok, json() | string()} | {error, term()}
|
||||||
|
|
||||||
Types
|
Generate the JSON encoding of the interface to a contract. The type definitions
|
||||||
|
and non-private functions are included in the JSON string.
|
||||||
|
|
||||||
``` erlang
|
#### render\_aci\_json(json() | json\_text()) -> string().
|
||||||
ConstractString = contract_string()
|
|
||||||
JSONstring = json_string()
|
|
||||||
```
|
|
||||||
|
|
||||||
Generate the JSON encoding of the interface to a contract. The type definitions and non-private functions are included in the JSON string.
|
Take a JSON encoding of a contract interface and generate a contract interface
|
||||||
|
that can be included in another contract.
|
||||||
#### decode(JSONstring) -> ConstractString.
|
|
||||||
|
|
||||||
Types
|
|
||||||
|
|
||||||
``` erlang
|
|
||||||
ConstractString = contract_string()
|
|
||||||
JSONstring = json_string()
|
|
||||||
```
|
|
||||||
|
|
||||||
Take a JSON encoding of a contract interface and generate and generate a contract definition which can be included in another contract.
|
|
||||||
|
|
||||||
### Example run
|
### Example run
|
||||||
|
|
||||||
This is an example of using the ACI generator from an Erlang shell. The file called `aci_test.aes` contains the contract in the description from which we want to generate files `aci_test.json` which is the JSON encoding of the contract interface and `aci_test.include` which is the contract definition to be included inside another contract.
|
This is an example of using the ACI generator from an Erlang shell. The file
|
||||||
|
called `aci_test.aes` contains the contract in the description from which we
|
||||||
|
want to generate files `aci_test.json` which is the JSON encoding of the
|
||||||
|
contract interface and `aci_test.include` which is the contract definition to
|
||||||
|
be included inside another contract.
|
||||||
|
|
||||||
``` erlang
|
``` erlang
|
||||||
1> {ok,Contract} = file:read_file("aci_test.aes").
|
1> {ok,Contract} = file:read_file("aci_test.aes").
|
||||||
{ok,<<"contract Answers =\n record state = { a : answers }\n type answers() = map(string, int)\n\n stateful function"...>>}
|
{ok,<<"contract Answers =\n record state = { a : answers }\n type answers() = map(string, int)\n\n stateful function"...>>}
|
||||||
2> {ok,Encoding} = aeso_aci:encode(Contract).
|
2> {ok,JsonACI} = aeso_aci:contract_interface(json, Contract).
|
||||||
<<"{\"contract\":{\"name\":\"Answers\",\"type_defs\":[{\"name\":\"state\",\"vars\":[],\"typedef\":\"{a : map(string,int)}\"},{\"name\":\"ans"...>>
|
{ok,[#{contract =>
|
||||||
3> file:write_file("aci_test.aci", Encoding).
|
#{functions =>
|
||||||
|
[#{arguments => [],name => <<"init">>,
|
||||||
|
returns => <<"Answers.state">>,stateful => true},
|
||||||
|
#{arguments =>
|
||||||
|
[#{name => <<"q">>,type => <<"string">>},
|
||||||
|
#{name => <<"a">>,type => <<"int">>}],
|
||||||
|
name => <<"new_answer">>,
|
||||||
|
returns => #{<<"map">> => [<<"string">>,<<"int">>]},
|
||||||
|
stateful => false}],
|
||||||
|
name => <<"Answers">>,
|
||||||
|
state =>
|
||||||
|
#{record =>
|
||||||
|
[#{name => <<"a">>,type => <<"Answers.answers">>}]},
|
||||||
|
type_defs =>
|
||||||
|
[#{name => <<"answers">>,
|
||||||
|
typedef => #{<<"map">> => [<<"string">>,<<"int">>]},
|
||||||
|
vars => []}]}}]}
|
||||||
|
3> file:write_file("aci_test.aci", jsx:encode(JsonACI)).
|
||||||
ok
|
ok
|
||||||
4> Decoded = aeso_aci:decode(Encoding).
|
4> {ok,InterfaceStub} = aeso_aci:render_aci_json(JsonACI).
|
||||||
<<"contract Answers =\n function new_answer : (string, int) => map(string,int)\n">>
|
{ok,<<"contract Answers =\n record state = {a : Answers.answers}\n type answers = map(string, int)\n function init "...>>}
|
||||||
5> file:write_file("aci_test.include", Decoded).
|
5> file:write_file("aci_test.include", InterfaceStub).
|
||||||
ok
|
ok
|
||||||
6> jsx:prettify(Encoding).
|
6> jsx:prettify(jsx:encode(JsonACI)).
|
||||||
<<"{\n \"contract\": {\n \"name\": \"Answers\",\n \"type_defs\": [\n {\n \"name\": \"state\",\n \"vars\": [],\n "...>>
|
<<"[\n {\n \"contract\": {\n \"functions\": [\n {\n \"arguments\": [],\n \"name\": \"init\",\n "...>>
|
||||||
```
|
```
|
||||||
|
|
||||||
The final call to `jsx:prettify(Encoding)` returns the encoding in a
|
The final call to `jsx:prettify(jsx:encode(JsonACI))` returns the encoding in a
|
||||||
more easily readable form. This is what is shown in the description
|
more easily readable form. This is what is shown in the description above.
|
||||||
above.
|
|
||||||
|
|
||||||
### Notes
|
|
||||||
|
|
||||||
The ACI generator currently cannot properly handle types defined using `datatype`.
|
|
||||||
|
|||||||
+2
-3
@@ -2,8 +2,7 @@
|
|||||||
|
|
||||||
{erl_opts, [debug_info]}.
|
{erl_opts, [debug_info]}.
|
||||||
|
|
||||||
{deps, [ {aebytecode, {git, "https://github.com/aeternity/aebytecode.git",
|
{deps, [ {aebytecode, {git, "https://github.com/aeternity/aebytecode.git", {ref, "f129887"}}}
|
||||||
{ref, "2f4e188"}}}
|
|
||||||
, {getopt, "1.0.1"}
|
, {getopt, "1.0.1"}
|
||||||
, {jsx, {git, "https://github.com/talentdeficit/jsx.git",
|
, {jsx, {git, "https://github.com/talentdeficit/jsx.git",
|
||||||
{tag, "2.8.0"}}}
|
{tag, "2.8.0"}}}
|
||||||
@@ -15,7 +14,7 @@
|
|||||||
{base_plt_apps, [erts, kernel, stdlib, crypto, mnesia]}
|
{base_plt_apps, [erts, kernel, stdlib, crypto, mnesia]}
|
||||||
]}.
|
]}.
|
||||||
|
|
||||||
{relx, [{release, {aesophia, "3.0.0"},
|
{relx, [{release, {aesophia, "3.1.0"},
|
||||||
[aesophia, aebytecode, getopt]},
|
[aesophia, aebytecode, getopt]},
|
||||||
|
|
||||||
{dev_mode, true},
|
{dev_mode, true},
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
{"1.1.0",
|
{"1.1.0",
|
||||||
[{<<"aebytecode">>,
|
[{<<"aebytecode">>,
|
||||||
{git,"https://github.com/aeternity/aebytecode.git",
|
{git,"https://github.com/aeternity/aebytecode.git",
|
||||||
{ref,"2f4e1888c241a7347ffec855ab6761c2c2972f37"}},
|
{ref,"f1298870e526f4e9330447d3a281af5ef4e06e17"}},
|
||||||
0},
|
0},
|
||||||
{<<"aeserialization">>,
|
{<<"aeserialization">>,
|
||||||
{git,"https://github.com/aeternity/aeserialization.git",
|
{git,"https://github.com/aeternity/aeserialization.git",
|
||||||
|
|||||||
+212
-269
@@ -9,76 +9,56 @@
|
|||||||
|
|
||||||
-module(aeso_aci).
|
-module(aeso_aci).
|
||||||
|
|
||||||
-export([encode/1,encode/2,decode/1]).
|
-export([ contract_interface/2
|
||||||
-export([encode_type/1,encode_stmt/1,encode_expr/1]).
|
, contract_interface/3
|
||||||
|
|
||||||
%% Define records for the various typed syntactic forms. These make
|
, render_aci_json/1
|
||||||
%% the code easier but don't seem to exist elsewhere.
|
|
||||||
|
|
||||||
%% Top-level
|
, json_encode_expr/1
|
||||||
-record(contract, {ann,con,decls}).
|
, json_encode_type/1]).
|
||||||
%% -record(namespace, {ann,con,decls}).
|
|
||||||
-record(letfun, {ann,id,args,type,body}).
|
|
||||||
-record(type_def, {ann,id,vars,typedef}).
|
|
||||||
|
|
||||||
%% Types
|
-type aci_type() :: json | string.
|
||||||
-record(app_t, {ann,id,fields}).
|
-type json() :: jsx:json_term().
|
||||||
-record(tuple_t, {ann,args}).
|
-type json_text() :: binary().
|
||||||
-record(bytes_t, {ann,len}).
|
|
||||||
-record(record_t, {fields}).
|
|
||||||
-record(field_t, {ann,id,type}).
|
|
||||||
-record(alias_t, {type}).
|
|
||||||
-record(variant_t, {cons}).
|
|
||||||
-record(constr_t, {ann,con,args}).
|
|
||||||
-record(fun_t, {ann,named,args,type}).
|
|
||||||
|
|
||||||
%% Tokens
|
%% External API
|
||||||
-record(arg, {ann,id,type}).
|
-spec contract_interface(aci_type(), string()) ->
|
||||||
-record(id, {ann,name}).
|
{ok, json() | string()} | {error, term()}.
|
||||||
-record(con, {ann,name}).
|
contract_interface(Type, ContractString) ->
|
||||||
-record(qid, {ann,names}).
|
contract_interface(Type, ContractString, []).
|
||||||
-record(qcon, {ann,names}).
|
|
||||||
-record(tvar, {ann,name}).
|
|
||||||
|
|
||||||
%% Expressions
|
-spec contract_interface(aci_type(), string(), [term()]) ->
|
||||||
-record(bool, {ann,bool}).
|
{ok, json() | string()} | {error, term()}.
|
||||||
-record(int, {ann,value}).
|
contract_interface(Type, ContractString, CompilerOpts) ->
|
||||||
-record(string, {ann,bin}).
|
do_contract_interface(Type, ContractString, CompilerOpts).
|
||||||
-record(bytes, {ann,bin}).
|
|
||||||
-record(tuple, {ann,args}).
|
|
||||||
-record(list, {ann,args}).
|
|
||||||
-record(app, {ann,func,args}).
|
|
||||||
-record(typed, {ann,expr,type}).
|
|
||||||
|
|
||||||
%% encode(ContractString) -> {ok,JSON} | {error,String}.
|
-spec render_aci_json(json() | json_text()) -> {ok, binary()}.
|
||||||
%% encode(ContractString, Options) -> {ok,JSON} | {error,String}.
|
render_aci_json(Json) ->
|
||||||
%% Build a JSON structure with lists and tuples, not maps, as this
|
do_render_aci_json(Json).
|
||||||
%% allows us to order the fields in the contructed JSON string.
|
|
||||||
|
|
||||||
encode(ContractString) -> encode(ContractString, []).
|
-spec json_encode_expr(aeso_syntax:expr()) -> json().
|
||||||
|
json_encode_expr(Expr) ->
|
||||||
|
encode_expr(Expr).
|
||||||
|
|
||||||
encode(ContractString, Options) when is_binary(ContractString) ->
|
-spec json_encode_type(aeso_syntax:type()) -> json().
|
||||||
encode(binary_to_list(ContractString), Options);
|
json_encode_type(Type) ->
|
||||||
encode(ContractString, Options) ->
|
encode_type(Type).
|
||||||
|
|
||||||
|
%% Internal functions
|
||||||
|
do_contract_interface(Type, Contract, Options) when is_binary(Contract) ->
|
||||||
|
do_contract_interface(Type, binary_to_list(Contract), Options);
|
||||||
|
do_contract_interface(Type, ContractString, Options) ->
|
||||||
try
|
try
|
||||||
Ast = parse(ContractString, Options),
|
Ast = aeso_compiler:parse(ContractString, Options),
|
||||||
%% io:format("~p\n", [Ast]),
|
%% io:format("~p\n", [Ast]),
|
||||||
%% aeso_ast:pp(Ast),
|
TypedAst = aeso_ast_infer_types:infer(Ast, [dont_unfold]),
|
||||||
TypedAst = aeso_ast_infer_types:infer(Ast, Options),
|
|
||||||
%% io:format("~p\n", [TypedAst]),
|
%% io:format("~p\n", [TypedAst]),
|
||||||
%% aeso_ast:pp_typed(TypedAst),
|
JArray = [ encode_contract(C) || C <- TypedAst ],
|
||||||
%% We find and look at the last contract.
|
|
||||||
Contract = lists:last(TypedAst),
|
case Type of
|
||||||
Cname = contract_name(Contract),
|
json -> {ok, JArray};
|
||||||
Tdefs = [ encode_typedef(T) ||
|
string -> do_render_aci_json(JArray)
|
||||||
T <- sort_decls(contract_types(Contract)) ],
|
end
|
||||||
Fdefs = [ encode_func(F) || F <- sort_decls(contract_funcs(Contract)),
|
|
||||||
not is_private_func(F) ],
|
|
||||||
Jmap = [{<<"contract">>, [{<<"name">>, encode_name(Cname)},
|
|
||||||
{<<"type_defs">>, Tdefs},
|
|
||||||
{<<"functions">>, Fdefs}]}],
|
|
||||||
%% io:format("~p\n", [Jmap]),
|
|
||||||
{ok,jsx:encode(Jmap)}
|
|
||||||
catch
|
catch
|
||||||
%% The compiler errors.
|
%% The compiler errors.
|
||||||
error:{parse_errors, Errors} ->
|
error:{parse_errors, Errors} ->
|
||||||
@@ -95,201 +75,208 @@ join_errors(Prefix, Errors, Pfun) ->
|
|||||||
Ess = [ Pfun(E) || E <- Errors ],
|
Ess = [ Pfun(E) || E <- Errors ],
|
||||||
list_to_binary(string:join([Prefix|Ess], "\n")).
|
list_to_binary(string:join([Prefix|Ess], "\n")).
|
||||||
|
|
||||||
%% encode_func(Function) -> JSON
|
encode_contract(Contract) ->
|
||||||
|
C0 = #{name => encode_name(contract_name(Contract))},
|
||||||
|
|
||||||
|
Tdefs0 = [ encode_typedef(T) || T <- sort_decls(contract_types(Contract)) ],
|
||||||
|
FilterT = fun(N) -> fun(#{name := N1}) -> N == N1 end end,
|
||||||
|
{Es, Tdefs1} = lists:partition(FilterT(<<"event">>), Tdefs0),
|
||||||
|
{Ss, Tdefs} = lists:partition(FilterT(<<"state">>), Tdefs1),
|
||||||
|
|
||||||
|
C1 = C0#{type_defs => Tdefs},
|
||||||
|
|
||||||
|
C2 = case Es of
|
||||||
|
[] -> C1;
|
||||||
|
[#{typedef := ET}] -> C1#{event => ET}
|
||||||
|
end,
|
||||||
|
|
||||||
|
C3 = case Ss of
|
||||||
|
[] -> C2;
|
||||||
|
[#{typedef := ST}] -> C2#{state => ST}
|
||||||
|
end,
|
||||||
|
|
||||||
|
Fdefs = [ encode_function(F)
|
||||||
|
|| F <- sort_decls(contract_funcs(Contract)),
|
||||||
|
not is_private(F) ],
|
||||||
|
|
||||||
|
#{contract => C3#{functions => Fdefs}}.
|
||||||
|
|
||||||
%% Encode a function definition. Currently we are only interested in
|
%% Encode a function definition. Currently we are only interested in
|
||||||
%% the interface and type.
|
%% the interface and type.
|
||||||
|
encode_function(FDef = {letfun, _, {id, _, Name}, Args, Type, _}) ->
|
||||||
|
#{name => encode_name(Name),
|
||||||
|
arguments => encode_args(Args),
|
||||||
|
returns => encode_type(Type),
|
||||||
|
stateful => is_stateful(FDef)};
|
||||||
|
encode_function(FDecl = {fun_decl, _, {id, _, Name}, {fun_t, _, _, Args, Type}}) ->
|
||||||
|
#{name => encode_name(Name),
|
||||||
|
arguments => encode_anon_args(Args),
|
||||||
|
returns => encode_type(Type),
|
||||||
|
stateful => is_stateful(FDecl)}.
|
||||||
|
|
||||||
encode_func(Fdef) ->
|
encode_anon_args(Types) ->
|
||||||
Name = function_name(Fdef),
|
Anons = [ list_to_binary("_" ++ integer_to_list(X)) || X <- lists:seq(1, length(Types))],
|
||||||
Args = function_args(Fdef),
|
[ #{name => V, type => encode_type(T)}
|
||||||
Type = function_type(Fdef),
|
|| {V, T} <- lists:zip(Anons, Types) ].
|
||||||
[{<<"name">>, encode_name(Name)},
|
|
||||||
{<<"arguments">>, encode_args(Args)},
|
|
||||||
{<<"returns">>, encode_type(Type)},
|
|
||||||
{<<"stateful">>, is_stateful_func(Fdef)}].
|
|
||||||
|
|
||||||
%% encode_args(Args) -> [JSON].
|
encode_args(Args) -> [ encode_arg(A) || A <- Args ].
|
||||||
%% encode_arg(Args) -> JSON.
|
|
||||||
|
|
||||||
encode_args(Args) ->
|
encode_arg({arg, _, Id, T}) ->
|
||||||
[ encode_arg(A) || A <- Args ].
|
#{name => encode_type(Id),
|
||||||
|
type => encode_type(T)}.
|
||||||
encode_arg(#arg{id=Id,type=T}) ->
|
|
||||||
[{<<"name">>,encode_type(Id)},
|
|
||||||
{<<"type">>,[encode_type(T)]}].
|
|
||||||
|
|
||||||
%% encode_types(Types) -> [JSON].
|
|
||||||
%% encode_type(Type) -> JSON.
|
|
||||||
|
|
||||||
encode_types(Types) ->
|
|
||||||
[ encode_type(T) || T <- Types ].
|
|
||||||
|
|
||||||
encode_type(#tvar{name=N}) -> encode_name(N);
|
|
||||||
encode_type(#id{name=N}) -> encode_name(N);
|
|
||||||
encode_type(#con{name=N}) -> encode_name(N);
|
|
||||||
encode_type(#qid{names=Ns}) ->
|
|
||||||
encode_name(lists:join(".", Ns));
|
|
||||||
encode_type(#qcon{names=Ns}) ->
|
|
||||||
encode_name(lists:join(".", Ns)); %?
|
|
||||||
encode_type(#tuple_t{args=As}) ->
|
|
||||||
Eas = encode_types(As),
|
|
||||||
[{<<"tuple">>,Eas}];
|
|
||||||
encode_type(#bytes_t{len=Len}) ->
|
|
||||||
{<<"bytes">>, Len};
|
|
||||||
encode_type(#record_t{fields=Fs}) ->
|
|
||||||
Efs = encode_fields(Fs),
|
|
||||||
[{<<"record">>,Efs}];
|
|
||||||
encode_type(#app_t{id=Id,fields=Fs}) ->
|
|
||||||
Name = encode_type(Id),
|
|
||||||
Efs = encode_types(Fs),
|
|
||||||
[{Name,Efs}];
|
|
||||||
encode_type(#variant_t{cons=Cs}) ->
|
|
||||||
Ecs = encode_types(Cs),
|
|
||||||
[{<<"variant">>,Ecs}];
|
|
||||||
encode_type(#constr_t{con=C,args=As}) ->
|
|
||||||
Ec = encode_type(C),
|
|
||||||
Eas = encode_types(As),
|
|
||||||
[{Ec,Eas}];
|
|
||||||
encode_type(#fun_t{args=As,type=T}) ->
|
|
||||||
Eas = encode_types(As),
|
|
||||||
Et = encode_type(T),
|
|
||||||
[{<<"function">>,[{<<"arguments">>,Eas},{<<"returns">>,Et}]}].
|
|
||||||
|
|
||||||
encode_name(Name) ->
|
|
||||||
list_to_binary(Name).
|
|
||||||
|
|
||||||
%% encode_fields(Fields) -> [JSON].
|
|
||||||
%% encode_field(Field) -> JSON.
|
|
||||||
%% Encode a record field.
|
|
||||||
|
|
||||||
encode_fields(Fs) ->
|
|
||||||
[ encode_field(F) || F <- Fs ].
|
|
||||||
|
|
||||||
encode_field(#field_t{id=Id,type=T}) ->
|
|
||||||
[{<<"name">>,encode_type(Id)},
|
|
||||||
{<<"type">>,[encode_type(T)]}].
|
|
||||||
|
|
||||||
%% encode_typedef(TypeDef) -> JSON.
|
|
||||||
|
|
||||||
encode_typedef(Type) ->
|
encode_typedef(Type) ->
|
||||||
Name = typedef_name(Type),
|
Name = typedef_name(Type),
|
||||||
Vars = typedef_vars(Type),
|
Vars = typedef_vars(Type),
|
||||||
Def = typedef_def(Type),
|
Def = typedef_def(Type),
|
||||||
[{<<"name">>, encode_name(Name)},
|
#{name => encode_name(Name),
|
||||||
{<<"vars">>, encode_tvars(Vars)},
|
vars => encode_tvars(Vars),
|
||||||
{<<"typedef">>, encode_alias(Def)}].
|
typedef => encode_type(Def)}.
|
||||||
|
|
||||||
encode_tvars(Vars) ->
|
encode_tvars(Vars) ->
|
||||||
[ encode_tvar(V) || V <- Vars ].
|
[ #{name => encode_type(V)} || V <- Vars ].
|
||||||
|
|
||||||
encode_tvar(#tvar{name=N}) ->
|
%% Encode type
|
||||||
[{<<"name">>, encode_name(N)}].
|
encode_type({tvar, _, N}) -> encode_name(N);
|
||||||
|
encode_type({id, _, N}) -> encode_name(N);
|
||||||
|
encode_type({con, _, N}) -> encode_name(N);
|
||||||
|
encode_type({qid, _, Ns}) -> encode_name(lists:join(".", Ns));
|
||||||
|
encode_type({qcon, _, Ns}) -> encode_name(lists:join(".", Ns));
|
||||||
|
encode_type({tuple_t, _, As}) -> #{tuple => encode_types(As)};
|
||||||
|
encode_type({bytes_t, _, Len}) -> #{bytes => Len};
|
||||||
|
encode_type({record_t, Fs}) -> #{record => encode_type_fields(Fs)};
|
||||||
|
encode_type({app_t, _, Id, Fs}) -> #{encode_type(Id) => encode_types(Fs)};
|
||||||
|
encode_type({variant_t, Cs}) -> #{variant => encode_types(Cs)};
|
||||||
|
encode_type({constr_t, _, C, As}) -> #{encode_type(C) => encode_types(As)};
|
||||||
|
encode_type({alias_t, Type}) -> encode_type(Type);
|
||||||
|
encode_type({fun_t, _, _, As, T}) -> #{function =>
|
||||||
|
#{arguments => encode_types(As),
|
||||||
|
returns => encode_type(T)}}.
|
||||||
|
|
||||||
encode_alias(#alias_t{type=T}) ->
|
encode_types(Ts) -> [ encode_type(T) || T <- Ts ].
|
||||||
encode_type(T);
|
|
||||||
encode_alias(A) -> encode_type(A).
|
|
||||||
|
|
||||||
%% encode_stmt(Stmt) -> JSON.
|
encode_type_fields(Fs) -> [ encode_type_field(F) || F <- Fs ].
|
||||||
|
|
||||||
encode_stmt(E) ->
|
encode_type_field({field_t, _, Id, T}) ->
|
||||||
encode_expr(E).
|
#{name => encode_type(Id),
|
||||||
|
type => encode_type(T)}.
|
||||||
|
|
||||||
%% encode_exprs(Exprs) -> [JSON].
|
encode_name(Name) when is_list(Name) ->
|
||||||
%% encode_expr(Expr) -> JSON.
|
list_to_binary(Name);
|
||||||
|
encode_name(Name) when is_binary(Name) ->
|
||||||
|
Name.
|
||||||
|
|
||||||
encode_exprs(Es) ->
|
%% Encode Expr
|
||||||
[ encode_expr(E) || E <- Es ].
|
encode_exprs(Es) -> [ encode_expr(E) || E <- Es ].
|
||||||
|
|
||||||
encode_expr(#id{name=N}) -> encode_name(N);
|
encode_expr({id, _, N}) -> encode_name(N);
|
||||||
encode_expr(#con{name=N}) -> encode_name(N);
|
encode_expr({con, _, N}) -> encode_name(N);
|
||||||
encode_expr(#qid{names=Ns}) ->
|
encode_expr({qid, _, Ns}) -> encode_name(lists:join(".", Ns));
|
||||||
encode_name(lists:join(".", Ns));
|
encode_expr({qcon, _, Ns}) -> encode_name(lists:join(".", Ns));
|
||||||
encode_expr(#qcon{names=Ns}) ->
|
encode_expr({typed, _, E}) -> encode_expr(E);
|
||||||
encode_name(lists:join(".", Ns)); %?
|
encode_expr({bool, _, B}) -> B;
|
||||||
encode_expr(#typed{expr=E}) ->
|
encode_expr({int, _, V}) -> V;
|
||||||
encode_expr(E);
|
encode_expr({string, _, S}) -> S;
|
||||||
encode_expr(#bool{bool=B}) -> B;
|
encode_expr({tuple, _, As}) -> encode_exprs(As);
|
||||||
encode_expr(#int{value=V}) -> V;
|
encode_expr({list, _, As}) -> encode_exprs(As);
|
||||||
encode_expr(#string{bin=B}) -> B;
|
encode_expr({bytes, _, B}) ->
|
||||||
encode_expr(#bytes{bin=B}) -> B;
|
Digits = byte_size(B),
|
||||||
encode_expr(#tuple{args=As}) ->
|
<<N:Digits/unit:8>> = B,
|
||||||
Eas = encode_exprs(As),
|
list_to_binary(lists:flatten(io_lib:format("#~*.16.0b", [Digits*2, N])));
|
||||||
[{<<"tuple">>,Eas}];
|
encode_expr({Lit, _, L}) when Lit == oracle_pubkey; Lit == oracle_query_id;
|
||||||
encode_expr(#list{args=As}) ->
|
Lit == contract_pubkey; Lit == account_pubkey ->
|
||||||
Eas = encode_exprs(As),
|
aeser_api_encoder:encode(Lit, L);
|
||||||
[{<<"list">>,Eas}];
|
encode_expr({app, _, F, As}) ->
|
||||||
encode_expr(#app{func=F,args=As}) ->
|
|
||||||
Ef = encode_expr(F),
|
Ef = encode_expr(F),
|
||||||
Eas = encode_exprs(As),
|
Eas = encode_exprs(As),
|
||||||
[{<<"apply">>,[{<<"function">>,Ef},
|
#{Ef => Eas};
|
||||||
{<<"arguments">>,Eas}]}];
|
encode_expr({record, _, Flds}) -> maps:from_list(encode_fields(Flds));
|
||||||
|
encode_expr({map, _, KVs}) -> [ [encode_expr(K), encode_expr(V)] || {K, V} <- KVs ];
|
||||||
encode_expr({Op,_Ann}) ->
|
encode_expr({Op,_Ann}) ->
|
||||||
list_to_binary(atom_to_list(Op)).
|
error({encode_expr_todo, Op}).
|
||||||
|
|
||||||
%% decode(JSON) -> ContractString.
|
encode_fields(Flds) -> [ encode_field(F) || F <- Flds ].
|
||||||
%% Decode a JSON string and generate a suitable contract string which
|
|
||||||
%% can be included in a contract definition. We decode into a map
|
|
||||||
%% here as this is easier to work with and order is not important.
|
|
||||||
|
|
||||||
decode(Json) ->
|
encode_field({field, _, [{proj, _, {id, _, Fld}}], Val}) ->
|
||||||
Map = jsx:decode(Json, [return_maps]),
|
{encode_name(Fld), encode_expr(Val)}.
|
||||||
%% io:format("~p\n", [Map]),
|
|
||||||
#{<<"contract">> := C} = Map,
|
|
||||||
list_to_binary(decode_contract(C)).
|
|
||||||
|
|
||||||
decode_contract(#{<<"name">> := Name,
|
do_render_aci_json(Json) ->
|
||||||
<<"type_defs">> := Ts,
|
Contracts =
|
||||||
<<"functions">> := Fs}) ->
|
case Json of
|
||||||
|
JArray when is_list(JArray) -> JArray;
|
||||||
|
JObject when is_map(JObject) -> [JObject];
|
||||||
|
JText when is_binary(JText) ->
|
||||||
|
case jsx:decode(Json, [{labels, atom}, return_maps]) of
|
||||||
|
JArray when is_list(JArray) -> JArray;
|
||||||
|
JObject when is_map(JObject) -> [JObject];
|
||||||
|
_ -> error(bad_aci_json)
|
||||||
|
end
|
||||||
|
end,
|
||||||
|
DecodedContracts = [ decode_contract(C) || #{contract := C} <- Contracts ],
|
||||||
|
{ok, list_to_binary(string:join(DecodedContracts, "\n"))}.
|
||||||
|
|
||||||
|
decode_contract(#{name := Name,
|
||||||
|
type_defs := Ts0,
|
||||||
|
functions := Fs} = C) ->
|
||||||
|
MkTDef = fun(N, T) -> #{name => N, vars => [], typedef => T} end,
|
||||||
|
Ts = [ MkTDef(<<"state">>, maps:get(state, C)) || maps:is_key(state, C) ] ++
|
||||||
|
[ MkTDef(<<"event">>, maps:get(event, C)) || maps:is_key(event, C) ] ++ Ts0,
|
||||||
["contract"," ",io_lib:format("~s", [Name])," =\n",
|
["contract"," ",io_lib:format("~s", [Name])," =\n",
|
||||||
decode_tdefs(Ts),
|
decode_tdefs(Ts), decode_funcs(Fs)].
|
||||||
decode_funcs(Fs)].
|
|
||||||
|
|
||||||
decode_funcs(Fs) -> [ decode_func(F) || F <- Fs ].
|
decode_funcs(Fs) -> [ decode_func(F) || F <- Fs ].
|
||||||
|
|
||||||
decode_func(#{<<"name">> := <<"init">>}) -> [];
|
%% decode_func(#{name := init}) -> [];
|
||||||
decode_func(#{<<"name">> := Name,<<"arguments">> := As,<<"returns">> := T}) ->
|
decode_func(#{name := Name, arguments := As, returns := T}) ->
|
||||||
[" function"," ",io_lib:format("~s", [Name])," : ",
|
[" function", " ", io_lib:format("~s", [Name]), " : ",
|
||||||
decode_args(As)," => ",decode_type(T),$\n].
|
decode_args(As), " => ", decode_type(T), $\n].
|
||||||
|
|
||||||
decode_args(As) ->
|
decode_args(As) ->
|
||||||
Das = [ decode_arg(A) || A <- As ],
|
Das = [ decode_arg(A) || A <- As ],
|
||||||
[$(,lists:join(", ", Das),$)].
|
[$(,lists:join(", ", Das),$)].
|
||||||
|
|
||||||
decode_arg(#{<<"type">> := [T]}) -> decode_type(T).
|
decode_arg(#{type := T}) -> decode_type(T).
|
||||||
|
|
||||||
decode_types(Ets) ->
|
decode_types(Ets) ->
|
||||||
[ decode_type(Et) || Et <- Ets ].
|
[ decode_type(Et) || Et <- Ets ].
|
||||||
|
|
||||||
decode_type(#{<<"tuple">> := Ets}) ->
|
decode_type(#{tuple := Ets}) ->
|
||||||
Ts = decode_types(Ets),
|
Ts = decode_types(Ets),
|
||||||
[$(,lists:join(",", Ts),$)];
|
[$(,lists:join(",", Ts),$)];
|
||||||
decode_type(#{<<"record">> := Efs}) ->
|
decode_type(#{record := Efs}) ->
|
||||||
Fs = decode_fields(Efs),
|
Fs = decode_fields(Efs),
|
||||||
[${,lists:join(",", Fs),$}];
|
[${,lists:join(",", Fs),$}];
|
||||||
decode_type(#{<<"list">> := [Et]}) ->
|
decode_type(#{list := [Et]}) ->
|
||||||
T = decode_type(Et),
|
T = decode_type(Et),
|
||||||
["list",$(,T,$)];
|
["list",$(,T,$)];
|
||||||
decode_type(#{<<"map">> := Ets}) ->
|
decode_type(#{map := Ets}) ->
|
||||||
Ts = decode_types(Ets),
|
Ts = decode_types(Ets),
|
||||||
["map",$(,lists:join(",", Ts),$)];
|
["map",$(,lists:join(",", Ts),$)];
|
||||||
decode_type(#{<<"variant">> := Ets}) ->
|
decode_type(#{bytes := Len}) ->
|
||||||
|
["bytes(", integer_to_list(Len), ")"];
|
||||||
|
decode_type(#{variant := Ets}) ->
|
||||||
Ts = decode_types(Ets),
|
Ts = decode_types(Ets),
|
||||||
lists:join(" | ", Ts);
|
lists:join(" | ", Ts);
|
||||||
|
decode_type(#{function := #{arguments := Args, returns := R}}) ->
|
||||||
|
[decode_type(#{tuple => Args}), " => ", decode_type(R)];
|
||||||
decode_type(Econs) when is_map(Econs) -> %General constructor
|
decode_type(Econs) when is_map(Econs) -> %General constructor
|
||||||
[{Ec,Ets}] = maps:to_list(Econs),
|
[{Ec,Ets}] = maps:to_list(Econs),
|
||||||
C = decode_name(Ec),
|
AppName = decode_name(Ec),
|
||||||
Ts = decode_types(Ets),
|
AppArgs = decode_types(Ets),
|
||||||
[C,$(,lists:join(",", Ts),$)];
|
case AppArgs of
|
||||||
|
[] -> [AppName];
|
||||||
|
_ -> [AppName,$(,lists:join(", ", AppArgs),$)]
|
||||||
|
end;
|
||||||
decode_type(T) -> %Just raw names.
|
decode_type(T) -> %Just raw names.
|
||||||
decode_name(T).
|
decode_name(T).
|
||||||
|
|
||||||
decode_name(En) ->
|
decode_name(En) when is_atom(En) -> erlang:atom_to_list(En);
|
||||||
binary_to_list(En).
|
decode_name(En) when is_binary(En) -> binary_to_list(En).
|
||||||
|
|
||||||
decode_fields(Efs) ->
|
decode_fields(Efs) ->
|
||||||
[ decode_field(Ef) || Ef <- Efs ].
|
[ decode_field(Ef) || Ef <- Efs ].
|
||||||
|
|
||||||
decode_field(#{<<"name">> := En,<<"type">> := [Et]}) ->
|
decode_field(#{name := En, type := Et}) ->
|
||||||
Name = decode_name(En),
|
Name = decode_name(En),
|
||||||
Type = decode_type(Et),
|
Type = decode_type(Et),
|
||||||
[Name," : ",Type].
|
[Name," : ",Type].
|
||||||
@@ -298,39 +285,41 @@ decode_field(#{<<"name">> := En,<<"type">> := [Et]}) ->
|
|||||||
%% Here we are only interested in the type definitions and ignore the
|
%% Here we are only interested in the type definitions and ignore the
|
||||||
%% aliases. We find them as they always have variants.
|
%% aliases. We find them as they always have variants.
|
||||||
|
|
||||||
decode_tdefs(Ts) -> [ decode_tdef(T) ||
|
decode_tdefs(Ts) -> [ decode_tdef(T) || T <- Ts ].
|
||||||
#{<<"typedef">> := #{<<"variant">> := _}} = T <- Ts
|
|
||||||
].
|
|
||||||
|
|
||||||
decode_tdef(#{<<"name">> := Name,<<"vars">> := Vs,<<"typedef">> := T}) ->
|
decode_tdef(#{name := Name, vars := Vs, typedef := T}) ->
|
||||||
[" datatype"," ",decode_name(Name),decode_tvars(Vs),
|
TypeDef = decode_type(T),
|
||||||
" = ",decode_type(T),$\n].
|
DefType = decode_deftype(T),
|
||||||
|
[" ", DefType, " ", decode_name(Name), decode_tvars(Vs), " = ", TypeDef, $\n].
|
||||||
|
|
||||||
|
decode_deftype(#{record := _Efs}) -> "record";
|
||||||
|
decode_deftype(#{variant := _}) -> "datatype";
|
||||||
|
decode_deftype(_T) -> "type".
|
||||||
|
|
||||||
decode_tvars([]) -> []; %No tvars, no parentheses
|
decode_tvars([]) -> []; %No tvars, no parentheses
|
||||||
decode_tvars(Vs) ->
|
decode_tvars(Vs) ->
|
||||||
Dvs = [ decode_tvar(V) || V <- Vs ],
|
Dvs = [ decode_tvar(V) || V <- Vs ],
|
||||||
[$(,lists:join(", ", Dvs),$)].
|
[$(,lists:join(", ", Dvs),$)].
|
||||||
|
|
||||||
decode_tvar(#{<<"name">> := N}) -> io_lib:format("~s", [N]).
|
decode_tvar(#{name := N}) -> io_lib:format("~s", [N]).
|
||||||
|
|
||||||
%% #contract{Ann, Con, [Declarations]}.
|
%% #contract{Ann, Con, [Declarations]}.
|
||||||
|
|
||||||
contract_name(#contract{con=#con{name=N}}) -> N.
|
contract_name({contract, _, {con, _, Name}, _}) -> Name;
|
||||||
|
contract_name({namespace, _, {con, _, Name}, _}) -> Name.
|
||||||
|
|
||||||
contract_funcs(#contract{decls=Decls}) ->
|
contract_funcs({C, _, _, Decls}) when C == contract; C == namespace ->
|
||||||
[ D || D <- Decls, is_record(D, letfun) ].
|
[ D || D <- Decls, is_fun(D)].
|
||||||
|
|
||||||
contract_types(#contract{decls=Decls}) ->
|
contract_types({C, _, _, Decls}) when C == contract; C == namespace ->
|
||||||
[ D || D <- Decls, is_record(D, type_def) ].
|
[ D || D <- Decls, is_type(D) ].
|
||||||
|
|
||||||
%% To keep dialyzer happy and quiet.
|
is_fun({letfun, _, _, _, _, _}) -> true;
|
||||||
%% namespace_name(#namespace{con=#con{name=N}}) -> N.
|
is_fun({fun_decl, _, _, _}) -> true;
|
||||||
%%
|
is_fun(_) -> false.
|
||||||
%% namespace_funcs(#namespace{decls=Decls}) ->
|
|
||||||
%% [ D || D <- Decls, is_record(D, letfun) ].
|
is_type({type_def, _, _, _, _}) -> true;
|
||||||
%%
|
is_type(_) -> false.
|
||||||
%% namespace_types(#namespace{decls=Decls}) ->
|
|
||||||
%% [ D || D <- Decls, is_record(D, type_def) ].
|
|
||||||
|
|
||||||
sort_decls(Ds) ->
|
sort_decls(Ds) ->
|
||||||
Sort = fun (D1, D2) ->
|
Sort = fun (D1, D2) ->
|
||||||
@@ -339,58 +328,12 @@ sort_decls(Ds) ->
|
|||||||
end,
|
end,
|
||||||
lists:sort(Sort, Ds).
|
lists:sort(Sort, Ds).
|
||||||
|
|
||||||
%% #letfun{Ann, Id, [Arg], Type, Typedef}.
|
|
||||||
|
|
||||||
function_name(#letfun{id=#id{name=N}}) -> N.
|
is_private(Node) -> aeso_syntax:get_ann(private, Node, false).
|
||||||
|
is_stateful(Node) -> aeso_syntax:get_ann(stateful, Node, false).
|
||||||
|
|
||||||
function_args(#letfun{args=Args}) -> Args.
|
typedef_name({type_def, _, {id, _, Name}, _, _}) -> Name.
|
||||||
|
|
||||||
function_type(#letfun{type=Type}) -> Type.
|
typedef_vars({type_def, _, _, Vars, _}) -> Vars.
|
||||||
|
|
||||||
is_private_func(#letfun{ann=A}) -> aeso_syntax:get_ann(private, A, false).
|
typedef_def({type_def, _, _, _, Def}) -> Def.
|
||||||
|
|
||||||
is_stateful_func(#letfun{ann=A}) -> aeso_syntax:get_ann(stateful, A, false).
|
|
||||||
|
|
||||||
%% #type_def{Ann, Id, [Var], Typedef}.
|
|
||||||
|
|
||||||
typedef_name(#type_def{id=#id{name=N}}) -> N.
|
|
||||||
|
|
||||||
typedef_vars(#type_def{vars=Vars}) -> Vars.
|
|
||||||
|
|
||||||
typedef_def(#type_def{typedef=Def}) -> Def.
|
|
||||||
|
|
||||||
%% parse(ContractString, Options) -> {ok,AST}.
|
|
||||||
%% Signal errors, the sophia compiler way. Sigh!
|
|
||||||
|
|
||||||
parse(Text, Options) ->
|
|
||||||
%% Try and return something sensible here!
|
|
||||||
case aeso_parser:string(Text, Options) of
|
|
||||||
%% Yay, it worked!
|
|
||||||
{ok, Contract} -> Contract;
|
|
||||||
%% Scan errors.
|
|
||||||
{error, {Pos, scan_error}} ->
|
|
||||||
parse_error(Pos, "scan error");
|
|
||||||
{error, {Pos, scan_error_no_state}} ->
|
|
||||||
parse_error(Pos, "scan error");
|
|
||||||
%% Parse errors.
|
|
||||||
{error, {Pos, parse_error, Error}} ->
|
|
||||||
parse_error(Pos, Error);
|
|
||||||
{error, {Pos, ambiguous_parse, As}} ->
|
|
||||||
ErrorString = io_lib:format("Ambiguous ~p", [As]),
|
|
||||||
parse_error(Pos, ErrorString);
|
|
||||||
%% Include error
|
|
||||||
{error, {Pos, include_error, File}} ->
|
|
||||||
parse_error(Pos, io_lib:format("could not find include file '~s'", [File]))
|
|
||||||
end.
|
|
||||||
|
|
||||||
parse_error(Pos, ErrorString) ->
|
|
||||||
%% io:format("Error ~p ~p\n", [Pos,ErrorString]),
|
|
||||||
Error = io_lib:format("~s: ~s", [pos_error(Pos), ErrorString]),
|
|
||||||
error({parse_errors, [Error]}).
|
|
||||||
|
|
||||||
pos_error({Line, Pos}) ->
|
|
||||||
io_lib:format("line ~p, column ~p", [Line, Pos]);
|
|
||||||
pos_error({no_file, Line, Pos}) ->
|
|
||||||
pos_error({Line, Pos});
|
|
||||||
pos_error({File, Line, Pos}) ->
|
|
||||||
io_lib:format("file ~s, line ~p, column ~p", [File, Line, Pos]).
|
|
||||||
|
|||||||
@@ -514,7 +514,7 @@ map_t(As, K, V) -> {app_t, As, {id, As, "map"}, [K, V]}.
|
|||||||
infer(Contracts) ->
|
infer(Contracts) ->
|
||||||
infer(Contracts, []).
|
infer(Contracts, []).
|
||||||
|
|
||||||
-type option() :: return_env.
|
-type option() :: return_env | dont_unfold.
|
||||||
|
|
||||||
-spec init_env(list(option())) -> env().
|
-spec init_env(list(option())) -> env().
|
||||||
init_env(_Options) -> global_env().
|
init_env(_Options) -> global_env().
|
||||||
@@ -526,7 +526,7 @@ infer(Contracts, Options) ->
|
|||||||
Env = init_env(Options),
|
Env = init_env(Options),
|
||||||
create_options(Options),
|
create_options(Options),
|
||||||
ets_new(type_vars, [set]),
|
ets_new(type_vars, [set]),
|
||||||
{Env1, Decls} = infer1(Env, Contracts, []),
|
{Env1, Decls} = infer1(Env, Contracts, [], Options),
|
||||||
case proplists:get_value(return_env, Options, false) of
|
case proplists:get_value(return_env, Options, false) of
|
||||||
false -> Decls;
|
false -> Decls;
|
||||||
true -> {Env1, Decls}
|
true -> {Env1, Decls}
|
||||||
@@ -535,21 +535,22 @@ infer(Contracts, Options) ->
|
|||||||
clean_up_ets()
|
clean_up_ets()
|
||||||
end.
|
end.
|
||||||
|
|
||||||
-spec infer1(env(), [aeso_syntax:decl()], [aeso_syntax:decl()]) -> {env(), [aeso_syntax:decl()]}.
|
-spec infer1(env(), [aeso_syntax:decl()], [aeso_syntax:decl()], list(option())) ->
|
||||||
infer1(Env, [], Acc) -> {Env, lists:reverse(Acc)};
|
{env(), [aeso_syntax:decl()]}.
|
||||||
infer1(Env, [{contract, Ann, ConName, Code} | Rest], Acc) ->
|
infer1(Env, [], Acc, _Options) -> {Env, lists:reverse(Acc)};
|
||||||
|
infer1(Env, [{contract, Ann, ConName, Code} | Rest], Acc, Options) ->
|
||||||
%% do type inference on each contract independently.
|
%% do type inference on each contract independently.
|
||||||
check_scope_name_clash(Env, contract, ConName),
|
check_scope_name_clash(Env, contract, ConName),
|
||||||
{Env1, Code1} = infer_contract_top(push_scope(contract, ConName, Env), contract, Code),
|
{Env1, Code1} = infer_contract_top(push_scope(contract, ConName, Env), contract, Code, Options),
|
||||||
Contract1 = {contract, Ann, ConName, Code1},
|
Contract1 = {contract, Ann, ConName, Code1},
|
||||||
Env2 = pop_scope(Env1),
|
Env2 = pop_scope(Env1),
|
||||||
Env3 = bind_contract(Contract1, Env2),
|
Env3 = bind_contract(Contract1, Env2),
|
||||||
infer1(Env3, Rest, [Contract1 | Acc]);
|
infer1(Env3, Rest, [Contract1 | Acc], Options);
|
||||||
infer1(Env, [{namespace, Ann, Name, Code} | Rest], Acc) ->
|
infer1(Env, [{namespace, Ann, Name, Code} | Rest], Acc, Options) ->
|
||||||
check_scope_name_clash(Env, namespace, Name),
|
check_scope_name_clash(Env, namespace, Name),
|
||||||
{Env1, Code1} = infer_contract_top(push_scope(namespace, Name, Env), namespace, Code),
|
{Env1, Code1} = infer_contract_top(push_scope(namespace, Name, Env), namespace, Code, Options),
|
||||||
Namespace1 = {namespace, Ann, Name, Code1},
|
Namespace1 = {namespace, Ann, Name, Code1},
|
||||||
infer1(pop_scope(Env1), Rest, [Namespace1 | Acc]).
|
infer1(pop_scope(Env1), Rest, [Namespace1 | Acc], Options).
|
||||||
|
|
||||||
check_scope_name_clash(Env, Kind, Name) ->
|
check_scope_name_clash(Env, Kind, Name) ->
|
||||||
case get_scope(Env, qname(Name)) of
|
case get_scope(Env, qname(Name)) of
|
||||||
@@ -560,13 +561,16 @@ check_scope_name_clash(Env, Kind, Name) ->
|
|||||||
destroy_and_report_type_errors(Env)
|
destroy_and_report_type_errors(Env)
|
||||||
end.
|
end.
|
||||||
|
|
||||||
-spec infer_contract_top(env(), contract | namespace, [aeso_syntax:decl()]) -> {env(), [aeso_syntax:decl()]}.
|
-spec infer_contract_top(env(), contract | namespace, [aeso_syntax:decl()], list(option())) ->
|
||||||
infer_contract_top(Env, Kind, Defs0) ->
|
{env(), [aeso_syntax:decl()]}.
|
||||||
|
infer_contract_top(Env, Kind, Defs0, Options) ->
|
||||||
Defs = desugar(Defs0),
|
Defs = desugar(Defs0),
|
||||||
{Env1, Defs1} = infer_contract(Env, Kind, Defs),
|
{Env1, Defs1} = infer_contract(Env, Kind, Defs),
|
||||||
Env2 = on_current_scope(Env1, fun(Scope) -> unfold_record_types(Env1, Scope) end),
|
case proplists:get_value(dont_unfold, Options, false) of
|
||||||
Defs2 = unfold_record_types(Env2, Defs1),
|
true -> {Env1, Defs1};
|
||||||
{Env2, Defs2}.
|
false -> Env2 = on_current_scope(Env1, fun(Scope) -> unfold_record_types(Env1, Scope) end),
|
||||||
|
{Env2, unfold_record_types(Env2, Defs1)}
|
||||||
|
end.
|
||||||
|
|
||||||
%% TODO: revisit
|
%% TODO: revisit
|
||||||
infer_constant({letval, Attrs,_Pattern, Type, E}) ->
|
infer_constant({letval, Attrs,_Pattern, Type, E}) ->
|
||||||
@@ -611,11 +615,11 @@ infer_contract(Env, What, Defs) ->
|
|||||||
{Env4, TypeDefs ++ Decls ++ Defs1}.
|
{Env4, TypeDefs ++ Decls ++ Defs1}.
|
||||||
|
|
||||||
-spec check_typedefs(env(), [aeso_syntax:decl()]) -> {env(), [aeso_syntax:decl()]}.
|
-spec check_typedefs(env(), [aeso_syntax:decl()]) -> {env(), [aeso_syntax:decl()]}.
|
||||||
check_typedefs(Env, Defs) ->
|
check_typedefs(Env = #env{ namespace = Ns }, Defs) ->
|
||||||
create_type_errors(),
|
create_type_errors(),
|
||||||
GetName = fun({type_def, _, {id, _, Name}, _, _}) -> Name end,
|
GetName = fun({type_def, _, {id, _, Name}, _, _}) -> Name end,
|
||||||
TypeMap = maps:from_list([ {GetName(Def), Def} || Def <- Defs ]),
|
TypeMap = maps:from_list([ {GetName(Def), Def} || Def <- Defs ]),
|
||||||
DepGraph = maps:map(fun(_, Def) -> aeso_syntax_utils:used_types(Def) end, TypeMap),
|
DepGraph = maps:map(fun(_, Def) -> aeso_syntax_utils:used_types(Ns, Def) end, TypeMap),
|
||||||
SCCs = aeso_utils:scc(DepGraph),
|
SCCs = aeso_utils:scc(DepGraph),
|
||||||
{Env1, Defs1} = check_typedef_sccs(Env, TypeMap, SCCs, []),
|
{Env1, Defs1} = check_typedef_sccs(Env, TypeMap, SCCs, []),
|
||||||
destroy_and_report_type_errors(Env),
|
destroy_and_report_type_errors(Env),
|
||||||
@@ -738,25 +742,23 @@ check_event(Env, "event", Ann, Def) ->
|
|||||||
check_event(_Env, _Name, _Ann, Def) -> Def.
|
check_event(_Env, _Name, _Ann, Def) -> Def.
|
||||||
|
|
||||||
check_event_con(Env, {constr_t, Ann, Con, Args}) ->
|
check_event_con(Env, {constr_t, Ann, Con, Args}) ->
|
||||||
IsIndexed = fun(T) -> case aeso_syntax:get_ann(indexed, T, false) of
|
IsIndexed = fun(T) ->
|
||||||
true -> indexed;
|
T1 = unfold_types_in_type(Env, T),
|
||||||
false -> notindexed
|
%% `indexed` is optional but if used it has to be correctly used
|
||||||
end end,
|
case {is_word_type(T1), is_string_type(T1), aeso_syntax:get_ann(indexed, T, false)} of
|
||||||
|
{true, _, _} -> indexed;
|
||||||
|
{false, true, true} -> type_error({indexed_type_must_be_word, T, T1});
|
||||||
|
{false, true, _} -> notindexed;
|
||||||
|
{false, false, _} -> type_error({event_arg_type_word_or_string, T, T1}), error
|
||||||
|
end
|
||||||
|
end,
|
||||||
Indices = lists:map(IsIndexed, Args),
|
Indices = lists:map(IsIndexed, Args),
|
||||||
Indexed = [ T || T <- Args, IsIndexed(T) == indexed ],
|
Indexed = [ T || T <- Args, IsIndexed(T) == indexed ],
|
||||||
NonIndexed = Args -- Indexed,
|
NonIndexed = Args -- Indexed,
|
||||||
[ check_event_arg_type(Env, Ix, Type) || {Ix, Type} <- lists:zip(Indices, Args) ],
|
|
||||||
[ type_error({event_0_to_3_indexed_values, Con}) || length(Indexed) > 3 ],
|
[ type_error({event_0_to_3_indexed_values, Con}) || length(Indexed) > 3 ],
|
||||||
[ type_error({event_0_to_1_string_values, Con}) || length(NonIndexed) > 1 ],
|
[ type_error({event_0_to_1_string_values, Con}) || length(NonIndexed) > 1 ],
|
||||||
{constr_t, [{indices, Indices} | Ann], Con, Args}.
|
{constr_t, [{indices, Indices} | Ann], Con, Args}.
|
||||||
|
|
||||||
check_event_arg_type(Env, Ix, Type0) ->
|
|
||||||
Type = unfold_types_in_type(Env, Type0),
|
|
||||||
case Ix of
|
|
||||||
indexed -> [ type_error({indexed_type_must_be_word, Type0, Type}) || not is_word_type(Type) ];
|
|
||||||
notindexed -> [ type_error({payload_type_must_be_string, Type0, Type}) || not is_string_type(Type) ]
|
|
||||||
end.
|
|
||||||
|
|
||||||
%% Not so nice.
|
%% Not so nice.
|
||||||
is_word_type({id, _, Name}) ->
|
is_word_type({id, _, Name}) ->
|
||||||
lists:member(Name, ["int", "address", "hash", "bits", "bool"]);
|
lists:member(Name, ["int", "address", "hash", "bits", "bool"]);
|
||||||
@@ -1852,8 +1854,8 @@ instantiate(E) ->
|
|||||||
instantiate1(dereference(E)).
|
instantiate1(dereference(E)).
|
||||||
|
|
||||||
instantiate1({uvar, Attr, R}) ->
|
instantiate1({uvar, Attr, R}) ->
|
||||||
Next = proplists:get_value(next, ets_lookup(type_vars, next), 1),
|
Next = proplists:get_value(next, ets_lookup(type_vars, next), 0),
|
||||||
TVar = {tvar, Attr, "'" ++ integer_to_list(Next)},
|
TVar = {tvar, Attr, "'" ++ integer_to_tvar(Next)},
|
||||||
ets_insert(type_vars, [{next, Next + 1}, {R, TVar}]),
|
ets_insert(type_vars, [{next, Next + 1}, {R, TVar}]),
|
||||||
TVar;
|
TVar;
|
||||||
instantiate1({fun_t, Ann, Named, Args, Ret}) ->
|
instantiate1({fun_t, Ann, Named, Args, Ret}) ->
|
||||||
@@ -1873,6 +1875,12 @@ instantiate1([A|B]) ->
|
|||||||
instantiate1(X) ->
|
instantiate1(X) ->
|
||||||
X.
|
X.
|
||||||
|
|
||||||
|
integer_to_tvar(X) when X < 26 ->
|
||||||
|
[$a + X];
|
||||||
|
integer_to_tvar(X) ->
|
||||||
|
[integer_to_tvar(X div 26)] ++ [$a + (X rem 26)].
|
||||||
|
|
||||||
|
|
||||||
%% Save unification failures for error messages.
|
%% Save unification failures for error messages.
|
||||||
|
|
||||||
cannot_unify(A, B, When) ->
|
cannot_unify(A, B, When) ->
|
||||||
|
|||||||
+46
-22
@@ -330,6 +330,19 @@ type_to_fcode(_Env, _Sub, Type) ->
|
|||||||
args_to_fcode(Env, Args) ->
|
args_to_fcode(Env, Args) ->
|
||||||
[ {Name, type_to_fcode(Env, Type)} || {arg, _, {id, _, Name}, Type} <- Args ].
|
[ {Name, type_to_fcode(Env, Type)} || {arg, _, {id, _, Name}, Type} <- Args ].
|
||||||
|
|
||||||
|
-define(make_let(X, Expr, Body),
|
||||||
|
make_let(Expr, fun(X) -> Body end)).
|
||||||
|
|
||||||
|
make_let(Expr, Body) ->
|
||||||
|
case Expr of
|
||||||
|
{var, _} -> Body(Expr);
|
||||||
|
{lit, {int, _}} -> Body(Expr);
|
||||||
|
{lit, {bool, _}} -> Body(Expr);
|
||||||
|
_ ->
|
||||||
|
X = fresh_name(),
|
||||||
|
{'let', X, Expr, Body({var, X})}
|
||||||
|
end.
|
||||||
|
|
||||||
-spec expr_to_fcode(env(), aeso_syntax:expr()) -> fexpr().
|
-spec expr_to_fcode(env(), aeso_syntax:expr()) -> fexpr().
|
||||||
expr_to_fcode(Env, {typed, _, Expr, Type}) ->
|
expr_to_fcode(Env, {typed, _, Expr, Type}) ->
|
||||||
expr_to_fcode(Env, Type, Expr);
|
expr_to_fcode(Env, Type, Expr);
|
||||||
@@ -415,17 +428,9 @@ expr_to_fcode(Env, _Type, {list, _, Es}) ->
|
|||||||
|
|
||||||
%% Conditionals
|
%% Conditionals
|
||||||
expr_to_fcode(Env, _Type, {'if', _, Cond, Then, Else}) ->
|
expr_to_fcode(Env, _Type, {'if', _, Cond, Then, Else}) ->
|
||||||
Switch = fun(X) ->
|
make_if(expr_to_fcode(Env, Cond),
|
||||||
{switch, {split, boolean, X,
|
expr_to_fcode(Env, Then),
|
||||||
[{'case', {bool, false}, {nosplit, expr_to_fcode(Env, Else)}},
|
expr_to_fcode(Env, Else));
|
||||||
{'case', {bool, true}, {nosplit, expr_to_fcode(Env, Then)}}]}}
|
|
||||||
end,
|
|
||||||
case Cond of
|
|
||||||
{var, X} -> Switch(X);
|
|
||||||
_ ->
|
|
||||||
X = fresh_name(),
|
|
||||||
{'let', X, expr_to_fcode(Env, Cond), Switch(X)}
|
|
||||||
end;
|
|
||||||
|
|
||||||
%% Switch
|
%% Switch
|
||||||
expr_to_fcode(Env, _, {switch, _, Expr = {typed, _, E, Type}, Alts}) ->
|
expr_to_fcode(Env, _, {switch, _, Expr = {typed, _, E, Type}, Alts}) ->
|
||||||
@@ -484,19 +489,24 @@ expr_to_fcode(Env, Type, {map, Ann, KVs}) ->
|
|||||||
Fields = [{field, Ann, [{map_get, Ann, K}], V} || {K, V} <- KVs],
|
Fields = [{field, Ann, [{map_get, Ann, K}], V} || {K, V} <- KVs],
|
||||||
expr_to_fcode(Env, Type, {map, Ann, {map, Ann, []}, Fields});
|
expr_to_fcode(Env, Type, {map, Ann, {map, Ann, []}, Fields});
|
||||||
expr_to_fcode(Env, _Type, {map, _, Map, KVs}) ->
|
expr_to_fcode(Env, _Type, {map, _, Map, KVs}) ->
|
||||||
X = fresh_name(),
|
?make_let(Map1, expr_to_fcode(Env, Map),
|
||||||
Map1 = {var, X},
|
|
||||||
{'let', X, expr_to_fcode(Env, Map),
|
|
||||||
lists:foldr(fun(Fld, M) ->
|
lists:foldr(fun(Fld, M) ->
|
||||||
case Fld of
|
case Fld of
|
||||||
{field, _, [{map_get, _, K}], V} ->
|
{field, _, [{map_get, _, K}], V} ->
|
||||||
{op, map_set, [M, expr_to_fcode(Env, K), expr_to_fcode(Env, V)]};
|
{op, map_set, [M, expr_to_fcode(Env, K), expr_to_fcode(Env, V)]};
|
||||||
{field_upd, _, [{map_get, _, K}], {typed, _, {lam, _, [{arg, _, {id, _, Z}, _}], V}, _}} ->
|
{field_upd, _, [MapGet], {typed, _, {lam, _, [{arg, _, {id, _, Z}, _}], V}, _}} when element(1, MapGet) == map_get ->
|
||||||
Y = fresh_name(),
|
[map_get, _, K | Default] = tuple_to_list(MapGet),
|
||||||
{'let', Y, expr_to_fcode(Env, K),
|
?make_let(Key, expr_to_fcode(Env, K),
|
||||||
{'let', Z, {op, map_get, [Map1, {var, Y}]},
|
begin
|
||||||
{op, map_set, [M, {var, Y}, expr_to_fcode(bind_var(Env, Z), V)]}}}
|
GetExpr =
|
||||||
end end, Map1, KVs)};
|
case Default of
|
||||||
|
[] -> {op, map_get, [Map1, Key]};
|
||||||
|
[D] -> {op, map_get_d, [Map1, Key, expr_to_fcode(Env, D)]}
|
||||||
|
end,
|
||||||
|
{'let', Z, GetExpr,
|
||||||
|
{op, map_set, [M, Key, expr_to_fcode(bind_var(Env, Z), V)]}}
|
||||||
|
end)
|
||||||
|
end end, Map1, KVs));
|
||||||
expr_to_fcode(Env, _Type, {map_get, _, Map, Key}) ->
|
expr_to_fcode(Env, _Type, {map_get, _, Map, Key}) ->
|
||||||
{op, map_get, [expr_to_fcode(Env, Map), expr_to_fcode(Env, Key)]};
|
{op, map_get, [expr_to_fcode(Env, Map), expr_to_fcode(Env, Key)]};
|
||||||
expr_to_fcode(Env, _Type, {map_get, _, Map, Key, Def}) ->
|
expr_to_fcode(Env, _Type, {map_get, _, Map, Key, Def}) ->
|
||||||
@@ -510,6 +520,14 @@ expr_to_fcode(Env, _Type, {lam, _, Args, Body}) ->
|
|||||||
expr_to_fcode(_Env, Type, Expr) ->
|
expr_to_fcode(_Env, Type, Expr) ->
|
||||||
error({todo, {Expr, ':', Type}}).
|
error({todo, {Expr, ':', Type}}).
|
||||||
|
|
||||||
|
make_if({var, X}, Then, Else) ->
|
||||||
|
{switch, {split, boolean, X,
|
||||||
|
[{'case', {bool, false}, {nosplit, Else}},
|
||||||
|
{'case', {bool, true}, {nosplit, Then}}]}};
|
||||||
|
make_if(Cond, Then, Else) ->
|
||||||
|
X = fresh_name(),
|
||||||
|
{'let', X, Cond, make_if({var, X}, Then, Else)}.
|
||||||
|
|
||||||
%% -- Pattern matching --
|
%% -- Pattern matching --
|
||||||
|
|
||||||
-spec alts_to_fcode(env(), ftype(), var_name(), [aeso_syntax:alt()]) -> fsplit().
|
-spec alts_to_fcode(env(), ftype(), var_name(), [aeso_syntax:alt()]) -> fsplit().
|
||||||
@@ -738,8 +756,14 @@ op_builtins() ->
|
|||||||
bits_set, bits_clear, bits_test, bits_sum, bits_intersection, bits_union,
|
bits_set, bits_clear, bits_test, bits_sum, bits_intersection, bits_union,
|
||||||
bits_difference, int_to_str, address_to_str].
|
bits_difference, int_to_str, address_to_str].
|
||||||
|
|
||||||
builtin_to_fcode(map_lookup, [Key, Map]) ->
|
builtin_to_fcode(map_member, [Key, Map]) ->
|
||||||
{op, map_get, [Map, Key]};
|
{op, map_member, [Map, Key]};
|
||||||
|
builtin_to_fcode(map_lookup, [Key0, Map0]) ->
|
||||||
|
?make_let(Key, Key0,
|
||||||
|
?make_let(Map, Map0,
|
||||||
|
make_if({op, map_member, [Map, Key]},
|
||||||
|
{con, [0, 1], 1, [{op, map_get, [Map, Key]}]},
|
||||||
|
{con, [0, 1], 0, []})));
|
||||||
builtin_to_fcode(map_lookup_default, [Key, Map, Def]) ->
|
builtin_to_fcode(map_lookup_default, [Key, Map, Def]) ->
|
||||||
{op, map_get_d, [Map, Key, Def]};
|
{op, map_get_d, [Map, Key, Def]};
|
||||||
builtin_to_fcode(Builtin, Args) ->
|
builtin_to_fcode(Builtin, Args) ->
|
||||||
|
|||||||
@@ -173,8 +173,7 @@ ast_body({qid, _, [Con, "put"]}, #{ contract_name := Con }) ->
|
|||||||
|
|
||||||
%% Abort
|
%% Abort
|
||||||
ast_body(?id_app("abort", [String], _, _), Icode) ->
|
ast_body(?id_app("abort", [String], _, _), Icode) ->
|
||||||
#funcall{ function = #var_ref{ name = {builtin, abort} },
|
builtin_call(abort, [ast_body(String, Icode)]);
|
||||||
args = [ast_body(String, Icode)] };
|
|
||||||
|
|
||||||
%% Authentication
|
%% Authentication
|
||||||
ast_body({qid, _, ["Auth", "tx_hash"]}, _Icode) ->
|
ast_body({qid, _, ["Auth", "tx_hash"]}, _Icode) ->
|
||||||
@@ -370,13 +369,11 @@ ast_body(?qid_app(["String", "blake2b"], [String], _, _), Icode) ->
|
|||||||
%% Strings
|
%% Strings
|
||||||
%% -- String length
|
%% -- String length
|
||||||
ast_body(?qid_app(["String", "length"], [String], _, _), Icode) ->
|
ast_body(?qid_app(["String", "length"], [String], _, _), Icode) ->
|
||||||
#funcall{ function = #var_ref{ name = {builtin, string_length} },
|
builtin_call(string_length, [ast_body(String, Icode)]);
|
||||||
args = [ast_body(String, Icode)] };
|
|
||||||
|
|
||||||
%% -- String concat
|
%% -- String concat
|
||||||
ast_body(?qid_app(["String", "concat"], [String1, String2], _, _), Icode) ->
|
ast_body(?qid_app(["String", "concat"], [String1, String2], _, _), Icode) ->
|
||||||
#funcall{ function = #var_ref{ name = {builtin, string_concat} },
|
builtin_call(string_concat, [ast_body(String1, Icode), ast_body(String2, Icode)]);
|
||||||
args = [ast_body(String1, Icode), ast_body(String2, Icode)] };
|
|
||||||
|
|
||||||
%% -- String hash (sha3)
|
%% -- String hash (sha3)
|
||||||
ast_body(?qid_app(["String", "sha3"], [String], _, _), Icode) ->
|
ast_body(?qid_app(["String", "sha3"], [String], _, _), Icode) ->
|
||||||
@@ -602,13 +599,11 @@ ast_binop(Op, Ann, {typed, _, A, Type}, B, Icode)
|
|||||||
Builtin =
|
Builtin =
|
||||||
case OtherType of
|
case OtherType of
|
||||||
string ->
|
string ->
|
||||||
#funcall{ function = #var_ref{name = {builtin, str_equal}},
|
builtin_call(str_equal, Args);
|
||||||
args = Args };
|
|
||||||
{tuple, Types} ->
|
{tuple, Types} ->
|
||||||
case lists:usort(Types) of
|
case lists:usort(Types) of
|
||||||
[word] ->
|
[word] ->
|
||||||
#funcall{ function = #var_ref{name = {builtin, str_equal_p}},
|
builtin_call(str_equal_p, [ #integer{value = 32 * length(Types)} | Args]);
|
||||||
args = [ #integer{value = 32 * length(Types)} | Args] };
|
|
||||||
_ -> gen_error({cant_compare, Ann, Op, Type})
|
_ -> gen_error({cant_compare, Ann, Op, Type})
|
||||||
end;
|
end;
|
||||||
_ ->
|
_ ->
|
||||||
@@ -617,8 +612,7 @@ ast_binop(Op, Ann, {typed, _, A, Type}, B, Icode)
|
|||||||
Neg(Builtin)
|
Neg(Builtin)
|
||||||
end;
|
end;
|
||||||
ast_binop('++', _, A, B, Icode) ->
|
ast_binop('++', _, A, B, Icode) ->
|
||||||
#funcall{ function = #var_ref{ name = {builtin, list_concat} },
|
builtin_call(list_concat, [ast_body(A, Icode), ast_body(B, Icode)]);
|
||||||
args = [ast_body(A, Icode), ast_body(B, Icode)] };
|
|
||||||
ast_binop(Op, _, A, B, Icode) ->
|
ast_binop(Op, _, A, B, Icode) ->
|
||||||
#binop{op = Op, left = ast_body(A, Icode), right = ast_body(B, Icode)}.
|
#binop{op = Op, left = ast_body(A, Icode), right = ast_body(B, Icode)}.
|
||||||
|
|
||||||
|
|||||||
+30
-17
@@ -18,6 +18,7 @@
|
|||||||
, to_sophia_value/4
|
, to_sophia_value/4
|
||||||
, to_sophia_value/5
|
, to_sophia_value/5
|
||||||
, decode_calldata/3
|
, decode_calldata/3
|
||||||
|
, parse/2
|
||||||
]).
|
]).
|
||||||
|
|
||||||
-include_lib("aebytecode/include/aeb_opcodes.hrl").
|
-include_lib("aebytecode/include/aeb_opcodes.hrl").
|
||||||
@@ -75,23 +76,14 @@ file(File, Options) ->
|
|||||||
end.
|
end.
|
||||||
|
|
||||||
-spec from_string(binary() | string(), options()) -> {ok, map()} | {error, binary()}.
|
-spec from_string(binary() | string(), options()) -> {ok, map()} | {error, binary()}.
|
||||||
from_string(ContractBin, Options) when is_binary(ContractBin) ->
|
from_string(Contract, Options) ->
|
||||||
from_string(binary_to_list(ContractBin), Options);
|
from_string(proplists:get_value(backend, Options, aevm), Contract, Options).
|
||||||
from_string(ContractString, Options) ->
|
|
||||||
|
from_string(Backend, ContractBin, Options) when is_binary(ContractBin) ->
|
||||||
|
from_string(Backend, binary_to_list(ContractBin), Options);
|
||||||
|
from_string(Backend, ContractString, Options) ->
|
||||||
try
|
try
|
||||||
#{icode := Icode} = string_to_icode(ContractString, Options),
|
from_string1(Backend, ContractString, Options)
|
||||||
TypeInfo = extract_type_info(Icode),
|
|
||||||
Assembler = assemble(Icode, Options),
|
|
||||||
pp_assembler(Assembler, Options),
|
|
||||||
ByteCodeList = to_bytecode(Assembler, Options),
|
|
||||||
ByteCode = << << B:8 >> || B <- ByteCodeList >>,
|
|
||||||
pp_bytecode(ByteCode, Options),
|
|
||||||
{ok, Version} = version(),
|
|
||||||
{ok, #{byte_code => ByteCode,
|
|
||||||
compiler_version => Version,
|
|
||||||
contract_source => ContractString,
|
|
||||||
type_info => TypeInfo
|
|
||||||
}}
|
|
||||||
catch
|
catch
|
||||||
%% The compiler errors.
|
%% The compiler errors.
|
||||||
error:{parse_errors, Errors} ->
|
error:{parse_errors, Errors} ->
|
||||||
@@ -104,6 +96,26 @@ from_string(ContractString, Options) ->
|
|||||||
%% General programming errors in the compiler just signal error.
|
%% General programming errors in the compiler just signal error.
|
||||||
end.
|
end.
|
||||||
|
|
||||||
|
from_string1(aevm, ContractString, Options) ->
|
||||||
|
#{icode := Icode} = string_to_icode(ContractString, Options),
|
||||||
|
TypeInfo = extract_type_info(Icode),
|
||||||
|
Assembler = assemble(Icode, Options),
|
||||||
|
pp_assembler(Assembler, Options),
|
||||||
|
ByteCodeList = to_bytecode(Assembler, Options),
|
||||||
|
ByteCode = << << B:8 >> || B <- ByteCodeList >>,
|
||||||
|
pp_bytecode(ByteCode, Options),
|
||||||
|
{ok, Version} = version(),
|
||||||
|
{ok, #{byte_code => ByteCode,
|
||||||
|
compiler_version => Version,
|
||||||
|
contract_source => ContractString,
|
||||||
|
type_info => TypeInfo
|
||||||
|
}};
|
||||||
|
from_string1(fate, ContractString, Options) ->
|
||||||
|
Ast = parse(ContractString, Options),
|
||||||
|
TypedAst = aeso_ast_infer_types:infer(Ast, Options),
|
||||||
|
FCode = aeso_ast_to_fcode:ast_to_fcode(TypedAst, Options),
|
||||||
|
{ok, aeso_fcode_to_fate:compile(FCode, Options)}.
|
||||||
|
|
||||||
-spec string_to_icode(string(), [option()]) -> map().
|
-spec string_to_icode(string(), [option()]) -> map().
|
||||||
string_to_icode(ContractString, Options) ->
|
string_to_icode(ContractString, Options) ->
|
||||||
Ast = parse(ContractString, Options),
|
Ast = parse(ContractString, Options),
|
||||||
@@ -264,7 +276,7 @@ translate_vm_value(word, {id, _, "address"}, N) -> address_l
|
|||||||
translate_vm_value(word, {app_t, _, {id, _, "oracle"}, _}, N) -> address_literal(oracle_pubkey, N);
|
translate_vm_value(word, {app_t, _, {id, _, "oracle"}, _}, N) -> address_literal(oracle_pubkey, N);
|
||||||
translate_vm_value(word, {app_t, _, {id, _, "oracle_query"}, _}, N) -> address_literal(oracle_query_id, N);
|
translate_vm_value(word, {app_t, _, {id, _, "oracle_query"}, _}, N) -> address_literal(oracle_query_id, N);
|
||||||
translate_vm_value(word, {con, _, _Name}, N) -> address_literal(contract_pubkey, N);
|
translate_vm_value(word, {con, _, _Name}, N) -> address_literal(contract_pubkey, N);
|
||||||
translate_vm_value(word, {id, _, "int"}, N) -> {int, [], N};
|
translate_vm_value(word, {id, _, "int"}, N) -> <<N1:256/signed>> = <<N:256>>, {int, [], N1};
|
||||||
translate_vm_value(word, {id, _, "bits"}, N) -> error({todo, bits, N});
|
translate_vm_value(word, {id, _, "bits"}, N) -> error({todo, bits, N});
|
||||||
translate_vm_value(word, {id, _, "bool"}, N) -> {bool, [], N /= 0};
|
translate_vm_value(word, {id, _, "bool"}, N) -> {bool, [], N /= 0};
|
||||||
translate_vm_value(word, {bytes_t, _, Len}, Val) when Len =< 32 ->
|
translate_vm_value(word, {bytes_t, _, Len}, Val) when Len =< 32 ->
|
||||||
@@ -400,6 +412,7 @@ get_decode_type(FunName, [_ | Contracts]) ->
|
|||||||
%% Translate an icode value (error if not value) to an Erlang term that can be
|
%% Translate an icode value (error if not value) to an Erlang term that can be
|
||||||
%% consumed by aeb_heap:to_binary().
|
%% consumed by aeb_heap:to_binary().
|
||||||
icode_to_term(word, {integer, N}) -> N;
|
icode_to_term(word, {integer, N}) -> N;
|
||||||
|
icode_to_term(word, {unop, '-', {integer, N}}) -> -N;
|
||||||
icode_to_term(string, {tuple, [{integer, Len} | Words]}) ->
|
icode_to_term(string, {tuple, [{integer, Len} | Words]}) ->
|
||||||
<<Str:Len/binary, _/binary>> = << <<W:256>> || {integer, W} <- Words >>,
|
<<Str:Len/binary, _/binary>> = << <<W:256>> || {integer, W} <- Words >>,
|
||||||
Str;
|
Str;
|
||||||
|
|||||||
+152
-127
@@ -18,7 +18,7 @@
|
|||||||
| switch_body
|
| switch_body
|
||||||
| tuple(). %% FATE instruction
|
| tuple(). %% FATE instruction
|
||||||
|
|
||||||
-type arg() :: tuple(). %% Not exported: aeb_fate_code:fate_arg().
|
-type arg() :: tuple(). %% Not exported: aeb_fate_ops:fate_arg().
|
||||||
|
|
||||||
%% Annotated scode
|
%% Annotated scode
|
||||||
-type scode_a() :: [sinstr_a()].
|
-type scode_a() :: [sinstr_a()].
|
||||||
@@ -39,6 +39,9 @@
|
|||||||
-define(i(X), {immediate, X}).
|
-define(i(X), {immediate, X}).
|
||||||
-define(a, {stack, 0}).
|
-define(a, {stack, 0}).
|
||||||
-define(s, {var, -1}). %% TODO: until we have state support in FATE
|
-define(s, {var, -1}). %% TODO: until we have state support in FATE
|
||||||
|
-define(void, {var, 9999}).
|
||||||
|
|
||||||
|
-define(IsState(X), (is_tuple(X) andalso tuple_size(X) =:= 2 andalso element(1, X) =:= var andalso element(2, X) < 0)).
|
||||||
|
|
||||||
-define(IsOp(Op), (
|
-define(IsOp(Op), (
|
||||||
Op =:= 'STORE' orelse
|
Op =:= 'STORE' orelse
|
||||||
@@ -65,6 +68,8 @@
|
|||||||
Op =:= 'MAP_DELETE' orelse
|
Op =:= 'MAP_DELETE' orelse
|
||||||
Op =:= 'MAP_MEMBER' orelse
|
Op =:= 'MAP_MEMBER' orelse
|
||||||
Op =:= 'MAP_FROM_LIST' orelse
|
Op =:= 'MAP_FROM_LIST' orelse
|
||||||
|
Op =:= 'MAP_TO_LIST' orelse
|
||||||
|
Op =:= 'MAP_SIZE' orelse
|
||||||
Op =:= 'NIL' orelse
|
Op =:= 'NIL' orelse
|
||||||
Op =:= 'IS_NIL' orelse
|
Op =:= 'IS_NIL' orelse
|
||||||
Op =:= 'CONS' orelse
|
Op =:= 'CONS' orelse
|
||||||
@@ -76,6 +81,7 @@
|
|||||||
Op =:= 'INT_TO_STR' orelse
|
Op =:= 'INT_TO_STR' orelse
|
||||||
Op =:= 'ADDR_TO_STR' orelse
|
Op =:= 'ADDR_TO_STR' orelse
|
||||||
Op =:= 'STR_REVERSE' orelse
|
Op =:= 'STR_REVERSE' orelse
|
||||||
|
Op =:= 'STR_LENGTH' orelse
|
||||||
Op =:= 'INT_TO_ADDR' orelse
|
Op =:= 'INT_TO_ADDR' orelse
|
||||||
Op =:= 'VARIANT_TEST' orelse
|
Op =:= 'VARIANT_TEST' orelse
|
||||||
Op =:= 'VARIANT_ELEMENT' orelse
|
Op =:= 'VARIANT_ELEMENT' orelse
|
||||||
@@ -107,17 +113,18 @@ debug(Tag, Options, Fmt, Args) ->
|
|||||||
%% @doc Main entry point.
|
%% @doc Main entry point.
|
||||||
compile(FCode, Options) ->
|
compile(FCode, Options) ->
|
||||||
#{ contract_name := ContractName,
|
#{ contract_name := ContractName,
|
||||||
state_type := _StateType,
|
state_type := StateType,
|
||||||
functions := Functions } = FCode,
|
functions := Functions } = FCode,
|
||||||
SFuns = functions_to_scode(ContractName, Functions, Options),
|
SFuns = functions_to_scode(ContractName, Functions, Options),
|
||||||
SFuns1 = optimize_scode(SFuns, Options),
|
SFuns1 = optimize_scode(SFuns, Options),
|
||||||
BBFuns = to_basic_blocks(SFuns1, Options),
|
SFuns2 = add_default_init_function(SFuns1, StateType),
|
||||||
FateCode = #{ functions => BBFuns,
|
FateCode = to_basic_blocks(SFuns2),
|
||||||
symbols => #{},
|
|
||||||
annotations => #{} },
|
|
||||||
debug(compile, Options, "~s\n", [aeb_fate_asm:pp(FateCode)]),
|
debug(compile, Options, "~s\n", [aeb_fate_asm:pp(FateCode)]),
|
||||||
FateCode.
|
FateCode.
|
||||||
|
|
||||||
|
make_function_id(X) ->
|
||||||
|
aeb_fate_code:symbol_identifier(make_function_name(X)).
|
||||||
|
|
||||||
make_function_name(init) -> <<"init">>;
|
make_function_name(init) -> <<"init">>;
|
||||||
make_function_name({entrypoint, Name}) -> Name;
|
make_function_name({entrypoint, Name}) -> Name;
|
||||||
make_function_name({local_fun, Xs}) -> list_to_binary("." ++ string:join(Xs, ".")).
|
make_function_name({local_fun, Xs}) -> list_to_binary("." ++ string:join(Xs, ".")).
|
||||||
@@ -128,21 +135,35 @@ functions_to_scode(ContractName, Functions, Options) ->
|
|||||||
[ {make_function_name(Name), function_to_scode(ContractName, FunNames, Name, Args, Body, Type, Options)}
|
[ {make_function_name(Name), function_to_scode(ContractName, FunNames, Name, Args, Body, Type, Options)}
|
||||||
|| {Name, #{args := Args,
|
|| {Name, #{args := Args,
|
||||||
body := Body,
|
body := Body,
|
||||||
return := Type}} <- maps:to_list(Functions),
|
return := Type}} <- maps:to_list(Functions)]).
|
||||||
Name /= init ]). %% TODO: skip init for now
|
|
||||||
|
|
||||||
function_to_scode(ContractName, Functions, _Name, Args, Body, ResType, _Options) ->
|
function_to_scode(ContractName, Functions, _Name, Args, Body, ResType, _Options) ->
|
||||||
ArgTypes = [ type_to_scode(T) || {_, T} <- Args ],
|
ArgTypes = [ type_to_scode(T) || {_, T} <- Args ],
|
||||||
SCode = to_scode(init_env(ContractName, Functions, Args), Body),
|
SCode = to_scode(init_env(ContractName, Functions, Args), Body),
|
||||||
{{ArgTypes, type_to_scode(ResType)}, SCode}.
|
{{ArgTypes, type_to_scode(ResType)}, SCode}.
|
||||||
|
|
||||||
type_to_scode({variant, Cons}) -> {variant, lists:map(fun length/1, Cons)};
|
type_to_scode({variant, Cons}) -> {variant, lists:map(fun(T) -> type_to_scode({tuple, T}) end, Cons)};
|
||||||
type_to_scode({list, Type}) -> {list, type_to_scode(Type)};
|
type_to_scode({list, Type}) -> {list, type_to_scode(Type)};
|
||||||
type_to_scode({tuple, Types}) -> {tuple, lists:map(fun type_to_scode/1, Types)};
|
type_to_scode({tuple, Types}) -> {tuple, lists:map(fun type_to_scode/1, Types)};
|
||||||
type_to_scode({map, Key, Val}) -> {map, type_to_scode(Key), type_to_scode(Val)};
|
type_to_scode({map, Key, Val}) -> {map, type_to_scode(Key), type_to_scode(Val)};
|
||||||
type_to_scode({function, _Args, _Res}) -> {tuple, [string, any]};
|
type_to_scode({function, _Args, _Res}) -> {tuple, [string, any]};
|
||||||
type_to_scode(T) -> T.
|
type_to_scode(T) -> T.
|
||||||
|
|
||||||
|
add_default_init_function(SFuns, StateType) when StateType /= {tuple, []} ->
|
||||||
|
%% Only add default if the type is unit.
|
||||||
|
SFuns;
|
||||||
|
add_default_init_function(SFuns, {tuple, []}) ->
|
||||||
|
%% Only add default if the init function is not present
|
||||||
|
InitName = make_function_name(init),
|
||||||
|
case maps:find(InitName, SFuns) of
|
||||||
|
{ok, _} ->
|
||||||
|
SFuns;
|
||||||
|
error ->
|
||||||
|
Sig = {[], {tuple, []}},
|
||||||
|
Body = [tuple(0)],
|
||||||
|
SFuns#{ InitName => {Sig, Body} }
|
||||||
|
end.
|
||||||
|
|
||||||
%% -- Phase I ----------------------------------------------------------------
|
%% -- Phase I ----------------------------------------------------------------
|
||||||
%% Icode to structured assembly
|
%% Icode to structured assembly
|
||||||
|
|
||||||
@@ -188,7 +209,7 @@ to_scode(_Env, {lit, L}) ->
|
|||||||
end;
|
end;
|
||||||
|
|
||||||
to_scode(_Env, nil) ->
|
to_scode(_Env, nil) ->
|
||||||
[aeb_fate_code:nil(?a)];
|
[aeb_fate_ops:nil(?a)];
|
||||||
|
|
||||||
to_scode(Env, {var, X}) ->
|
to_scode(Env, {var, X}) ->
|
||||||
[push(lookup_var(Env, X))];
|
[push(lookup_var(Env, X))];
|
||||||
@@ -196,21 +217,21 @@ to_scode(Env, {var, X}) ->
|
|||||||
to_scode(Env, {con, Ar, I, As}) ->
|
to_scode(Env, {con, Ar, I, As}) ->
|
||||||
N = length(As),
|
N = length(As),
|
||||||
[[to_scode(notail(Env), A) || A <- As],
|
[[to_scode(notail(Env), A) || A <- As],
|
||||||
aeb_fate_code:variant(?a, ?i(Ar), ?i(I), ?i(N))];
|
aeb_fate_ops:variant(?a, ?i(Ar), ?i(I), ?i(N))];
|
||||||
|
|
||||||
to_scode(Env, {tuple, As}) ->
|
to_scode(Env, {tuple, As}) ->
|
||||||
N = length(As),
|
N = length(As),
|
||||||
[[ to_scode(notail(Env), A) || A <- As ],
|
[[ to_scode(notail(Env), A) || A <- As ],
|
||||||
aeb_fate_code:tuple(N)];
|
tuple(N)];
|
||||||
|
|
||||||
to_scode(Env, {proj, E, I}) ->
|
to_scode(Env, {proj, E, I}) ->
|
||||||
[to_scode(notail(Env), E),
|
[to_scode(notail(Env), E),
|
||||||
aeb_fate_code:element_op(?a, ?i(I), ?a)];
|
aeb_fate_ops:element_op(?a, ?i(I), ?a)];
|
||||||
|
|
||||||
to_scode(Env, {set_proj, R, I, E}) ->
|
to_scode(Env, {set_proj, R, I, E}) ->
|
||||||
[to_scode(notail(Env), E),
|
[to_scode(notail(Env), E),
|
||||||
to_scode(notail(Env), R),
|
to_scode(notail(Env), R),
|
||||||
aeb_fate_code:setelement(?a, ?i(I), ?a, ?a)];
|
aeb_fate_ops:setelement(?a, ?i(I), ?a, ?a)];
|
||||||
|
|
||||||
to_scode(Env, {op, Op, Args}) ->
|
to_scode(Env, {op, Op, Args}) ->
|
||||||
call_to_scode(Env, op_to_scode(Op), Args);
|
call_to_scode(Env, op_to_scode(Op), Args);
|
||||||
@@ -221,11 +242,11 @@ to_scode(Env, {'let', X, {var, Y}, Body}) ->
|
|||||||
to_scode(Env, {'let', X, Expr, Body}) ->
|
to_scode(Env, {'let', X, Expr, Body}) ->
|
||||||
{I, Env1} = bind_local(X, Env),
|
{I, Env1} = bind_local(X, Env),
|
||||||
[ to_scode(notail(Env), Expr),
|
[ to_scode(notail(Env), Expr),
|
||||||
aeb_fate_code:store({var, I}, {stack, 0}),
|
aeb_fate_ops:store({var, I}, {stack, 0}),
|
||||||
to_scode(Env1, Body) ];
|
to_scode(Env1, Body) ];
|
||||||
|
|
||||||
to_scode(Env, {def, Fun, Args}) ->
|
to_scode(Env, {def, Fun, Args}) ->
|
||||||
FName = make_function_name(Fun),
|
FName = make_function_id(Fun),
|
||||||
Lbl = aeb_fate_data:make_string(FName),
|
Lbl = aeb_fate_data:make_string(FName),
|
||||||
call_to_scode(Env, local_call(Env, ?i(Lbl)), Args);
|
call_to_scode(Env, local_call(Env, ?i(Lbl)), Args);
|
||||||
to_scode(Env, {funcall, Fun, Args}) ->
|
to_scode(Env, {funcall, Fun, Args}) ->
|
||||||
@@ -236,28 +257,28 @@ to_scode(Env, {builtin, B, Args}) ->
|
|||||||
|
|
||||||
to_scode(Env, {remote, Ct, Fun, [{builtin, call_gas_left, _}, Value | Args]}) ->
|
to_scode(Env, {remote, Ct, Fun, [{builtin, call_gas_left, _}, Value | Args]}) ->
|
||||||
%% Gas is not limited.
|
%% Gas is not limited.
|
||||||
Lbl = make_function_name(Fun),
|
Lbl = make_function_id(Fun),
|
||||||
Call = if Env#env.tailpos -> aeb_fate_code:call_tr(?a, Lbl, ?a);
|
Call = if Env#env.tailpos -> aeb_fate_ops:call_tr(?a, Lbl, ?a);
|
||||||
true -> aeb_fate_code:call_r(?a, Lbl, ?a)
|
true -> aeb_fate_ops:call_r(?a, Lbl, ?a)
|
||||||
end,
|
end,
|
||||||
call_to_scode(Env, Call, [Ct, Value | Args]);
|
call_to_scode(Env, Call, [Ct, Value | Args]);
|
||||||
|
|
||||||
to_scode(Env, {remote, Ct, Fun, [Gas, Value | Args]}) ->
|
to_scode(Env, {remote, Ct, Fun, [Gas, Value | Args]}) ->
|
||||||
%% Gas is limited.
|
%% Gas is limited.
|
||||||
Lbl = make_function_name(Fun),
|
Lbl = make_function_id(Fun),
|
||||||
Call = if Env#env.tailpos -> aeb_fate_code:call_gtr(?a, Lbl, ?a, ?a);
|
Call = if Env#env.tailpos -> aeb_fate_ops:call_gtr(?a, Lbl, ?a, ?a);
|
||||||
true -> aeb_fate_code:call_gr(?a, Lbl, ?a, ?a)
|
true -> aeb_fate_ops:call_gr(?a, Lbl, ?a, ?a)
|
||||||
end,
|
end,
|
||||||
call_to_scode(Env, Call, [Ct, Value, Gas | Args]);
|
call_to_scode(Env, Call, [Ct, Value, Gas | Args]);
|
||||||
|
|
||||||
to_scode(Env, {closure, Fun, FVs}) ->
|
to_scode(Env, {closure, Fun, FVs}) ->
|
||||||
to_scode(Env, {tuple, [{lit, {string, make_function_name(Fun)}}, FVs]});
|
to_scode(Env, {tuple, [{lit, {string, make_function_id(Fun)}}, FVs]});
|
||||||
|
|
||||||
to_scode(Env, {switch, Case}) ->
|
to_scode(Env, {switch, Case}) ->
|
||||||
split_to_scode(Env, Case).
|
split_to_scode(Env, Case).
|
||||||
|
|
||||||
local_call( Env, Fun) when Env#env.tailpos -> aeb_fate_code:call_t(Fun);
|
local_call( Env, Fun) when Env#env.tailpos -> aeb_fate_ops:call_t(Fun);
|
||||||
local_call(_Env, Fun) -> aeb_fate_code:call(Fun).
|
local_call(_Env, Fun) -> aeb_fate_ops:call(Fun).
|
||||||
|
|
||||||
split_to_scode(Env, {nosplit, Expr}) ->
|
split_to_scode(Env, {nosplit, Expr}) ->
|
||||||
[switch_body, to_scode(Env, Expr)];
|
[switch_body, to_scode(Env, Expr)];
|
||||||
@@ -295,13 +316,13 @@ split_to_scode(Env, {split, {list, _}, X, Alts}) ->
|
|||||||
[{'case', {'::', Y, Z}, S} | _] ->
|
[{'case', {'::', Y, Z}, S} | _] ->
|
||||||
{I, Env1} = bind_local(Y, Env),
|
{I, Env1} = bind_local(Y, Env),
|
||||||
{J, Env2} = bind_local(Z, Env1),
|
{J, Env2} = bind_local(Z, Env1),
|
||||||
[aeb_fate_code:hd({var, I}, Arg),
|
[aeb_fate_ops:hd({var, I}, Arg),
|
||||||
aeb_fate_code:tl({var, J}, Arg),
|
aeb_fate_ops:tl({var, J}, Arg),
|
||||||
split_to_scode(Env2, S)]
|
split_to_scode(Env2, S)]
|
||||||
end
|
end
|
||||||
end,
|
end,
|
||||||
SAlts = [GetAlt('::'), GetAlt(nil)],
|
SAlts = [GetAlt('::'), GetAlt(nil)],
|
||||||
[aeb_fate_code:is_nil(?a, Arg),
|
[aeb_fate_ops:is_nil(?a, Arg),
|
||||||
{switch, ?a, boolean, SAlts, Def}];
|
{switch, ?a, boolean, SAlts, Def}];
|
||||||
split_to_scode(Env, {split, Type, X, Alts}) when Type == integer; Type == string ->
|
split_to_scode(Env, {split, Type, X, Alts}) when Type == integer; Type == string ->
|
||||||
{Def, Alts1} = catchall_to_scode(Env, X, Alts),
|
{Def, Alts1} = catchall_to_scode(Env, X, Alts),
|
||||||
@@ -337,7 +358,7 @@ literal_split_to_scode(Env, Type, Arg, [{'case', Lit, Body} | Alts], Def) when T
|
|||||||
{int, N} -> N;
|
{int, N} -> N;
|
||||||
{string, S} -> aeb_fate_data:make_string(S)
|
{string, S} -> aeb_fate_data:make_string(S)
|
||||||
end,
|
end,
|
||||||
[aeb_fate_code:eq(?a, Arg, ?i(SLit)),
|
[aeb_fate_ops:eq(?a, Arg, ?i(SLit)),
|
||||||
{switch, ?a, boolean, [False, True], Def}].
|
{switch, ?a, boolean, [False, True], Def}].
|
||||||
|
|
||||||
catchall_to_scode(Env, X, Alts) -> catchall_to_scode(Env, X, Alts, []).
|
catchall_to_scode(Env, X, Alts) -> catchall_to_scode(Env, X, Alts, []).
|
||||||
@@ -351,10 +372,10 @@ catchall_to_scode(_, _, [], Acc) -> {missing, lists:reverse(Acc)}.
|
|||||||
|
|
||||||
%% Tuple is in the accumulator. Arguments are the variable names.
|
%% Tuple is in the accumulator. Arguments are the variable names.
|
||||||
match_tuple(Env, Arg, Xs) ->
|
match_tuple(Env, Arg, Xs) ->
|
||||||
match_tuple(Env, 0, fun aeb_fate_code:element_op/3, Arg, Xs).
|
match_tuple(Env, 0, fun aeb_fate_ops:element_op/3, Arg, Xs).
|
||||||
|
|
||||||
match_variant(Env, Arg, Xs) ->
|
match_variant(Env, Arg, Xs) ->
|
||||||
Elem = fun(Dst, I, Val) -> aeb_fate_code:variant_element(Dst, Val, I) end,
|
Elem = fun(Dst, I, Val) -> aeb_fate_ops:variant_element(Dst, Val, I) end,
|
||||||
match_tuple(Env, 0, Elem, Arg, Xs).
|
match_tuple(Env, 0, Elem, Arg, Xs).
|
||||||
|
|
||||||
match_tuple(Env, I, Elem, Arg, ["_" | Xs]) ->
|
match_tuple(Env, I, Elem, Arg, ["_" | Xs]) ->
|
||||||
@@ -375,49 +396,49 @@ call_to_scode(Env, CallCode, Args) ->
|
|||||||
builtin_to_scode(_Env, get_state, []) ->
|
builtin_to_scode(_Env, get_state, []) ->
|
||||||
[push(?s)];
|
[push(?s)];
|
||||||
builtin_to_scode(Env, set_state, [_] = Args) ->
|
builtin_to_scode(Env, set_state, [_] = Args) ->
|
||||||
call_to_scode(Env, [aeb_fate_code:store(?s, ?a),
|
call_to_scode(Env, [aeb_fate_ops:store(?s, ?a),
|
||||||
aeb_fate_code:tuple(0)], Args);
|
tuple(0)], Args);
|
||||||
builtin_to_scode(_Env, event, [_] = _Args) ->
|
builtin_to_scode(_Env, event, [_] = _Args) ->
|
||||||
?TODO(fate_event_instruction);
|
?TODO(fate_event_instruction);
|
||||||
builtin_to_scode(_Env, map_empty, []) ->
|
builtin_to_scode(_Env, map_empty, []) ->
|
||||||
[aeb_fate_code:map_empty(?a)];
|
[aeb_fate_ops:map_empty(?a)];
|
||||||
builtin_to_scode(_Env, bits_none, []) ->
|
builtin_to_scode(_Env, bits_none, []) ->
|
||||||
[aeb_fate_code:bits_none(?a)];
|
[aeb_fate_ops:bits_none(?a)];
|
||||||
builtin_to_scode(_Env, bits_all, []) ->
|
builtin_to_scode(_Env, bits_all, []) ->
|
||||||
[aeb_fate_code:bits_all(?a)];
|
[aeb_fate_ops:bits_all(?a)];
|
||||||
builtin_to_scode(Env, abort, [_] = Args) ->
|
builtin_to_scode(Env, abort, [_] = Args) ->
|
||||||
call_to_scode(Env, aeb_fate_code:abort(?a), Args);
|
call_to_scode(Env, aeb_fate_ops:abort(?a), Args);
|
||||||
builtin_to_scode(Env, chain_spend, [_, _] = Args) ->
|
builtin_to_scode(Env, chain_spend, [_, _] = Args) ->
|
||||||
call_to_scode(Env, [aeb_fate_code:spend(?a, ?a),
|
call_to_scode(Env, [aeb_fate_ops:spend(?a, ?a),
|
||||||
aeb_fate_code:tuple(0)], Args);
|
tuple(0)], Args);
|
||||||
builtin_to_scode(Env, chain_balance, [_] = Args) ->
|
builtin_to_scode(Env, chain_balance, [_] = Args) ->
|
||||||
call_to_scode(Env, aeb_fate_code:balance_other(?a, ?a), Args);
|
call_to_scode(Env, aeb_fate_ops:balance_other(?a, ?a), Args);
|
||||||
builtin_to_scode(Env, chain_block_hash, [_] = Args) ->
|
builtin_to_scode(Env, chain_block_hash, [_] = Args) ->
|
||||||
call_to_scode(Env, aeb_fate_code:blockhash(?a, ?a), Args);
|
call_to_scode(Env, aeb_fate_ops:blockhash(?a, ?a), Args);
|
||||||
builtin_to_scode(_Env, chain_coinbase, []) ->
|
builtin_to_scode(_Env, chain_coinbase, []) ->
|
||||||
[aeb_fate_code:beneficiary(?a)];
|
[aeb_fate_ops:beneficiary(?a)];
|
||||||
builtin_to_scode(_Env, chain_timestamp, []) ->
|
builtin_to_scode(_Env, chain_timestamp, []) ->
|
||||||
[aeb_fate_code:timestamp(?a)];
|
[aeb_fate_ops:timestamp(?a)];
|
||||||
builtin_to_scode(_Env, chain_block_height, []) ->
|
builtin_to_scode(_Env, chain_block_height, []) ->
|
||||||
[aeb_fate_code:generation(?a)];
|
[aeb_fate_ops:generation(?a)];
|
||||||
builtin_to_scode(_Env, chain_difficulty, []) ->
|
builtin_to_scode(_Env, chain_difficulty, []) ->
|
||||||
[aeb_fate_code:difficulty(?a)];
|
[aeb_fate_ops:difficulty(?a)];
|
||||||
builtin_to_scode(_Env, chain_gas_limit, []) ->
|
builtin_to_scode(_Env, chain_gas_limit, []) ->
|
||||||
[aeb_fate_code:gaslimit(?a)];
|
[aeb_fate_ops:gaslimit(?a)];
|
||||||
builtin_to_scode(_Env, contract_balance, []) ->
|
builtin_to_scode(_Env, contract_balance, []) ->
|
||||||
[aeb_fate_code:balance(?a)];
|
[aeb_fate_ops:balance(?a)];
|
||||||
builtin_to_scode(_Env, contract_address, []) ->
|
builtin_to_scode(_Env, contract_address, []) ->
|
||||||
[aeb_fate_code:address(?a)];
|
[aeb_fate_ops:address(?a)];
|
||||||
builtin_to_scode(_Env, call_origin, []) ->
|
builtin_to_scode(_Env, call_origin, []) ->
|
||||||
[aeb_fate_code:origin(?a)];
|
[aeb_fate_ops:origin(?a)];
|
||||||
builtin_to_scode(_Env, call_caller, []) ->
|
builtin_to_scode(_Env, call_caller, []) ->
|
||||||
[aeb_fate_code:caller(?a)];
|
[aeb_fate_ops:caller(?a)];
|
||||||
builtin_to_scode(_Env, call_value, []) ->
|
builtin_to_scode(_Env, call_value, []) ->
|
||||||
[aeb_fate_code:call_value(?a)];
|
[aeb_fate_ops:call_value(?a)];
|
||||||
builtin_to_scode(_Env, call_gas_price, []) ->
|
builtin_to_scode(_Env, call_gas_price, []) ->
|
||||||
[aeb_fate_code:gasprice(?a)];
|
[aeb_fate_ops:gasprice(?a)];
|
||||||
builtin_to_scode(_Env, call_gas_left, []) ->
|
builtin_to_scode(_Env, call_gas_left, []) ->
|
||||||
[aeb_fate_code:gas(?a)];
|
[aeb_fate_ops:gas(?a)];
|
||||||
builtin_to_scode(_Env, oracle_register, [_, _, _, _] = _Args) ->
|
builtin_to_scode(_Env, oracle_register, [_, _, _, _] = _Args) ->
|
||||||
?TODO(fate_oracle_register_instruction);
|
?TODO(fate_oracle_register_instruction);
|
||||||
builtin_to_scode(_Env, oracle_query_fee, [_] = _Args) ->
|
builtin_to_scode(_Env, oracle_query_fee, [_] = _Args) ->
|
||||||
@@ -457,44 +478,47 @@ builtin_to_scode(_Env, auth_tx_hash, []) ->
|
|||||||
|
|
||||||
%% -- Operators --
|
%% -- Operators --
|
||||||
|
|
||||||
op_to_scode('+') -> aeb_fate_code:add(?a, ?a, ?a);
|
op_to_scode('+') -> aeb_fate_ops:add(?a, ?a, ?a);
|
||||||
op_to_scode('-') -> aeb_fate_code:sub(?a, ?a, ?a);
|
op_to_scode('-') -> aeb_fate_ops:sub(?a, ?a, ?a);
|
||||||
op_to_scode('*') -> aeb_fate_code:mul(?a, ?a, ?a);
|
op_to_scode('*') -> aeb_fate_ops:mul(?a, ?a, ?a);
|
||||||
op_to_scode('/') -> aeb_fate_code:divide(?a, ?a, ?a);
|
op_to_scode('/') -> aeb_fate_ops:divide(?a, ?a, ?a);
|
||||||
op_to_scode(mod) -> aeb_fate_code:modulo(?a, ?a, ?a);
|
op_to_scode(mod) -> aeb_fate_ops:modulo(?a, ?a, ?a);
|
||||||
op_to_scode('^') -> aeb_fate_code:pow(?a, ?a, ?a);
|
op_to_scode('^') -> aeb_fate_ops:pow(?a, ?a, ?a);
|
||||||
op_to_scode('++') -> aeb_fate_code:append(?a, ?a, ?a);
|
op_to_scode('++') -> aeb_fate_ops:append(?a, ?a, ?a);
|
||||||
op_to_scode('::') -> aeb_fate_code:cons(?a, ?a, ?a);
|
op_to_scode('::') -> aeb_fate_ops:cons(?a, ?a, ?a);
|
||||||
op_to_scode('<') -> aeb_fate_code:lt(?a, ?a, ?a);
|
op_to_scode('<') -> aeb_fate_ops:lt(?a, ?a, ?a);
|
||||||
op_to_scode('>') -> aeb_fate_code:gt(?a, ?a, ?a);
|
op_to_scode('>') -> aeb_fate_ops:gt(?a, ?a, ?a);
|
||||||
op_to_scode('=<') -> aeb_fate_code:elt(?a, ?a, ?a);
|
op_to_scode('=<') -> aeb_fate_ops:elt(?a, ?a, ?a);
|
||||||
op_to_scode('>=') -> aeb_fate_code:egt(?a, ?a, ?a);
|
op_to_scode('>=') -> aeb_fate_ops:egt(?a, ?a, ?a);
|
||||||
op_to_scode('==') -> aeb_fate_code:eq(?a, ?a, ?a);
|
op_to_scode('==') -> aeb_fate_ops:eq(?a, ?a, ?a);
|
||||||
op_to_scode('!=') -> aeb_fate_code:neq(?a, ?a, ?a);
|
op_to_scode('!=') -> aeb_fate_ops:neq(?a, ?a, ?a);
|
||||||
op_to_scode('!') -> aeb_fate_code:not_op(?a, ?a);
|
op_to_scode('!') -> aeb_fate_ops:not_op(?a, ?a);
|
||||||
op_to_scode(map_get) -> aeb_fate_code:map_lookup(?a, ?a, ?a);
|
op_to_scode(map_get) -> aeb_fate_ops:map_lookup(?a, ?a, ?a);
|
||||||
op_to_scode(map_get_d) -> aeb_fate_code:map_lookup(?a, ?a, ?a, ?a);
|
op_to_scode(map_get_d) -> aeb_fate_ops:map_lookup(?a, ?a, ?a, ?a);
|
||||||
op_to_scode(map_set) -> aeb_fate_code:map_update(?a, ?a, ?a, ?a);
|
op_to_scode(map_set) -> aeb_fate_ops:map_update(?a, ?a, ?a, ?a);
|
||||||
op_to_scode(map_from_list) -> aeb_fate_code:map_from_list(?a, ?a);
|
op_to_scode(map_from_list) -> aeb_fate_ops:map_from_list(?a, ?a);
|
||||||
op_to_scode(map_to_list) -> ?TODO(fate_map_to_list_instruction);
|
op_to_scode(map_to_list) -> aeb_fate_ops:map_to_list(?a, ?a);
|
||||||
op_to_scode(map_delete) -> aeb_fate_code:map_delete(?a, ?a, ?a);
|
op_to_scode(map_delete) -> aeb_fate_ops:map_delete(?a, ?a, ?a);
|
||||||
op_to_scode(map_member) -> aeb_fate_code:map_member(?a, ?a, ?a);
|
op_to_scode(map_member) -> aeb_fate_ops:map_member(?a, ?a, ?a);
|
||||||
op_to_scode(map_size) -> ?TODO(fate_map_size_instruction);
|
op_to_scode(map_size) -> aeb_fate_ops:map_size_(?a, ?a);
|
||||||
op_to_scode(string_length) -> ?TODO(fate_string_length_instruction);
|
op_to_scode(string_length) -> aeb_fate_ops:str_length(?a, ?a);
|
||||||
op_to_scode(string_concat) -> aeb_fate_code:str_join(?a, ?a, ?a);
|
op_to_scode(string_concat) -> aeb_fate_ops:str_join(?a, ?a, ?a);
|
||||||
op_to_scode(bits_set) -> aeb_fate_code:bits_set(?a, ?a, ?a);
|
op_to_scode(bits_set) -> aeb_fate_ops:bits_set(?a, ?a, ?a);
|
||||||
op_to_scode(bits_clear) -> aeb_fate_code:bits_clear(?a, ?a, ?a);
|
op_to_scode(bits_clear) -> aeb_fate_ops:bits_clear(?a, ?a, ?a);
|
||||||
op_to_scode(bits_test) -> aeb_fate_code:bits_test(?a, ?a, ?a);
|
op_to_scode(bits_test) -> aeb_fate_ops:bits_test(?a, ?a, ?a);
|
||||||
op_to_scode(bits_sum) -> aeb_fate_code:bits_sum(?a, ?a);
|
op_to_scode(bits_sum) -> aeb_fate_ops:bits_sum(?a, ?a);
|
||||||
op_to_scode(bits_intersection) -> aeb_fate_code:bits_and(?a, ?a, ?a);
|
op_to_scode(bits_intersection) -> aeb_fate_ops:bits_and(?a, ?a, ?a);
|
||||||
op_to_scode(bits_union) -> aeb_fate_code:bits_or(?a, ?a, ?a);
|
op_to_scode(bits_union) -> aeb_fate_ops:bits_or(?a, ?a, ?a);
|
||||||
op_to_scode(bits_difference) -> aeb_fate_code:bits_diff(?a, ?a, ?a);
|
op_to_scode(bits_difference) -> aeb_fate_ops:bits_diff(?a, ?a, ?a);
|
||||||
op_to_scode(address_to_str) -> aeb_fate_code:addr_to_str(?a, ?a);
|
op_to_scode(address_to_str) -> aeb_fate_ops:addr_to_str(?a, ?a);
|
||||||
op_to_scode(int_to_str) -> aeb_fate_code:int_to_str(?a, ?a).
|
op_to_scode(int_to_str) -> aeb_fate_ops:int_to_str(?a, ?a).
|
||||||
|
|
||||||
%% PUSH and STORE ?a are the same, so we use STORE to make optimizations
|
%% PUSH and STORE ?a are the same, so we use STORE to make optimizations
|
||||||
%% easier, and specialize to PUSH (which is cheaper) at the end.
|
%% easier, and specialize to PUSH (which is cheaper) at the end.
|
||||||
push(A) -> aeb_fate_code:store(?a, A).
|
push(A) -> aeb_fate_ops:store(?a, A).
|
||||||
|
|
||||||
|
tuple(0) -> push(?i({tuple, {}}));
|
||||||
|
tuple(N) -> aeb_fate_ops:tuple(?a, N).
|
||||||
|
|
||||||
%% -- Phase II ---------------------------------------------------------------
|
%% -- Phase II ---------------------------------------------------------------
|
||||||
%% Optimize
|
%% Optimize
|
||||||
@@ -565,6 +589,7 @@ pp_ann(_, []) -> [].
|
|||||||
|
|
||||||
pp_arg(?i(I)) -> io_lib:format("~w", [I]);
|
pp_arg(?i(I)) -> io_lib:format("~w", [I]);
|
||||||
pp_arg({arg, N}) -> io_lib:format("arg~p", [N]);
|
pp_arg({arg, N}) -> io_lib:format("arg~p", [N]);
|
||||||
|
pp_arg({var, N}) when N < 0 -> io_lib:format("store~p", [-N]);
|
||||||
pp_arg({var, N}) -> io_lib:format("var~p", [N]);
|
pp_arg({var, N}) -> io_lib:format("var~p", [N]);
|
||||||
pp_arg(?a) -> "a".
|
pp_arg(?a) -> "a".
|
||||||
|
|
||||||
@@ -585,7 +610,7 @@ ann_writes([{switch, Arg, Type, Alts, Def} | Code], Writes, Acc) ->
|
|||||||
Writes1 = ordsets:union(Writes, ordsets:intersection([WritesDef | WritesAlts])),
|
Writes1 = ordsets:union(Writes, ordsets:intersection([WritesDef | WritesAlts])),
|
||||||
ann_writes(Code, Writes1, [{switch, Arg, Type, Alts1, Def1} | Acc]);
|
ann_writes(Code, Writes1, [{switch, Arg, Type, Alts1, Def1} | Acc]);
|
||||||
ann_writes([I | Code], Writes, Acc) ->
|
ann_writes([I | Code], Writes, Acc) ->
|
||||||
Ws = var_writes(I),
|
Ws = [ W || W <- var_writes(I), not ?IsState(W) ],
|
||||||
Writes1 = ordsets:union(Writes, Ws),
|
Writes1 = ordsets:union(Writes, Ws),
|
||||||
Ann = #{ writes_in => Writes, writes_out => Writes1 },
|
Ann = #{ writes_in => Writes, writes_out => Writes1 },
|
||||||
ann_writes(Code, Writes1, [{i, Ann, I} | Acc]);
|
ann_writes(Code, Writes1, [{i, Ann, I} | Acc]);
|
||||||
@@ -642,13 +667,13 @@ attributes(I) ->
|
|||||||
{'SWITCH_V3', A, _, _, _} -> Impure(pc, A);
|
{'SWITCH_V3', A, _, _, _} -> Impure(pc, A);
|
||||||
{'SWITCH_VN', A, _} -> Impure(pc, A);
|
{'SWITCH_VN', A, _} -> Impure(pc, A);
|
||||||
{'PUSH', A} -> Pure(?a, A);
|
{'PUSH', A} -> Pure(?a, A);
|
||||||
'DUPA' -> Pure(?a, []);
|
'DUPA' -> Pure(?a, ?a);
|
||||||
{'DUP', A} -> Pure(?a, A);
|
{'DUP', A} -> Pure(?a, A);
|
||||||
{'POP', A} -> Pure(A, ?a);
|
{'POP', A} -> Pure(A, ?a);
|
||||||
{'STORE', A, B} -> Pure(A, B);
|
{'STORE', A, B} -> Pure(A, B);
|
||||||
'INCA' -> Pure(?a, ?a);
|
'INCA' -> Pure(?a, ?a);
|
||||||
{'INC', A} -> Pure(A, A);
|
{'INC', A} -> Pure(A, A);
|
||||||
'DECA' -> Pure(?a, []);
|
'DECA' -> Pure(?a, ?a);
|
||||||
{'DEC', A} -> Pure(A, A);
|
{'DEC', A} -> Pure(A, A);
|
||||||
{'ADD', A, B, C} -> Pure(A, [B, C]);
|
{'ADD', A, B, C} -> Pure(A, [B, C]);
|
||||||
{'SUB', A, B, C} -> Pure(A, [B, C]);
|
{'SUB', A, B, C} -> Pure(A, [B, C]);
|
||||||
@@ -665,7 +690,7 @@ attributes(I) ->
|
|||||||
{'AND', A, B, C} -> Pure(A, [B, C]);
|
{'AND', A, B, C} -> Pure(A, [B, C]);
|
||||||
{'OR', A, B, C} -> Pure(A, [B, C]);
|
{'OR', A, B, C} -> Pure(A, [B, C]);
|
||||||
{'NOT', A, B} -> Pure(A, B);
|
{'NOT', A, B} -> Pure(A, B);
|
||||||
{'TUPLE', _} -> Pure(?a, []);
|
{'TUPLE', A, N} -> Pure(A, [?a || N > 0]);
|
||||||
{'ELEMENT', A, B, C} -> Pure(A, [B, C]);
|
{'ELEMENT', A, B, C} -> Pure(A, [B, C]);
|
||||||
{'SETELEMENT', A, B, C, D} -> Pure(A, [B, C, D]);
|
{'SETELEMENT', A, B, C, D} -> Pure(A, [B, C, D]);
|
||||||
{'MAP_EMPTY', A} -> Pure(A, []);
|
{'MAP_EMPTY', A} -> Pure(A, []);
|
||||||
@@ -675,6 +700,8 @@ attributes(I) ->
|
|||||||
{'MAP_DELETE', A, B, C} -> Pure(A, [B, C]);
|
{'MAP_DELETE', A, B, C} -> Pure(A, [B, C]);
|
||||||
{'MAP_MEMBER', A, B, C} -> Pure(A, [B, C]);
|
{'MAP_MEMBER', A, B, C} -> Pure(A, [B, C]);
|
||||||
{'MAP_FROM_LIST', A, B} -> Pure(A, B);
|
{'MAP_FROM_LIST', A, B} -> Pure(A, B);
|
||||||
|
{'MAP_TO_LIST', A, B} -> Pure(A, B);
|
||||||
|
{'MAP_SIZE', A, B} -> Pure(A, B);
|
||||||
{'NIL', A} -> Pure(A, []);
|
{'NIL', A} -> Pure(A, []);
|
||||||
{'IS_NIL', A, B} -> Pure(A, B);
|
{'IS_NIL', A, B} -> Pure(A, B);
|
||||||
{'CONS', A, B, C} -> Pure(A, [B, C]);
|
{'CONS', A, B, C} -> Pure(A, [B, C]);
|
||||||
@@ -686,6 +713,7 @@ attributes(I) ->
|
|||||||
{'INT_TO_STR', A, B} -> Pure(A, B);
|
{'INT_TO_STR', A, B} -> Pure(A, B);
|
||||||
{'ADDR_TO_STR', A, B} -> Pure(A, B);
|
{'ADDR_TO_STR', A, B} -> Pure(A, B);
|
||||||
{'STR_REVERSE', A, B} -> Pure(A, B);
|
{'STR_REVERSE', A, B} -> Pure(A, B);
|
||||||
|
{'STR_LENGTH', A, B} -> Pure(A, B);
|
||||||
{'INT_TO_ADDR', A, B} -> Pure(A, B);
|
{'INT_TO_ADDR', A, B} -> Pure(A, B);
|
||||||
{'VARIANT', A, B, C, D} -> Pure(A, [?a, B, C, D]);
|
{'VARIANT', A, B, C, D} -> Pure(A, [?a, B, C, D]);
|
||||||
{'VARIANT_TEST', A, B, C} -> Pure(A, [B, C]);
|
{'VARIANT_TEST', A, B, C} -> Pure(A, [B, C]);
|
||||||
@@ -708,7 +736,7 @@ attributes(I) ->
|
|||||||
{'ORIGIN', A} -> Pure(A, []);
|
{'ORIGIN', A} -> Pure(A, []);
|
||||||
{'CALLER', A} -> Pure(A, []);
|
{'CALLER', A} -> Pure(A, []);
|
||||||
{'GASPRICE', A} -> Pure(A, []);
|
{'GASPRICE', A} -> Pure(A, []);
|
||||||
{'BLOCKHASH', A} -> Pure(A, []);
|
{'BLOCKHASH', A, B} -> Impure(A, [B]);
|
||||||
{'BENEFICIARY', A} -> Pure(A, []);
|
{'BENEFICIARY', A} -> Pure(A, []);
|
||||||
{'TIMESTAMP', A} -> Pure(A, []);
|
{'TIMESTAMP', A} -> Pure(A, []);
|
||||||
{'GENERATION', A} -> Pure(A, []);
|
{'GENERATION', A} -> Pure(A, []);
|
||||||
@@ -792,6 +820,7 @@ swap_instrs({i, #{ live_in := Live1 }, I}, {i, #{ live_in := Live2, live_out :=
|
|||||||
{{i, #{ live_in => Live1, live_out => Live2_ }, J},
|
{{i, #{ live_in => Live1, live_out => Live2_ }, J},
|
||||||
{i, #{ live_in => Live2_, live_out => Live3 }, I}}.
|
{i, #{ live_in => Live2_, live_out => Live3 }, I}}.
|
||||||
|
|
||||||
|
live_in(R, _) when ?IsState(R) -> true;
|
||||||
live_in(R, #{ live_in := LiveIn }) -> ordsets:is_element(R, LiveIn);
|
live_in(R, #{ live_in := LiveIn }) -> ordsets:is_element(R, LiveIn);
|
||||||
live_in(R, {i, Ann, _}) -> live_in(R, Ann);
|
live_in(R, {i, Ann, _}) -> live_in(R, Ann);
|
||||||
live_in(R, [I = {i, _, _} | _]) -> live_in(R, I);
|
live_in(R, [I = {i, _, _} | _]) -> live_in(R, I);
|
||||||
@@ -801,6 +830,7 @@ live_in(R, [{switch, A, _, Alts, Def} | _]) ->
|
|||||||
live_in(_, missing) -> false;
|
live_in(_, missing) -> false;
|
||||||
live_in(_, []) -> false.
|
live_in(_, []) -> false.
|
||||||
|
|
||||||
|
live_out(R, _) when ?IsState(R) -> true;
|
||||||
live_out(R, #{ live_out := LiveOut }) -> ordsets:is_element(R, LiveOut).
|
live_out(R, #{ live_out := LiveOut }) -> ordsets:is_element(R, LiveOut).
|
||||||
|
|
||||||
%% -- Optimizations --
|
%% -- Optimizations --
|
||||||
@@ -845,8 +875,7 @@ merge_rules() ->
|
|||||||
|
|
||||||
rules() ->
|
rules() ->
|
||||||
merge_rules() ++
|
merge_rules() ++
|
||||||
[?RULE(r_dup_to_push),
|
[?RULE(r_swap_push),
|
||||||
?RULE(r_swap_push),
|
|
||||||
?RULE(r_swap_write),
|
?RULE(r_swap_write),
|
||||||
?RULE(r_constant_propagation),
|
?RULE(r_constant_propagation),
|
||||||
?RULE(r_prune_impossible_branches),
|
?RULE(r_prune_impossible_branches),
|
||||||
@@ -855,11 +884,6 @@ rules() ->
|
|||||||
].
|
].
|
||||||
|
|
||||||
%% Removing pushes that are immediately consumed.
|
%% Removing pushes that are immediately consumed.
|
||||||
r_push_consume({i, Ann1, {'STORE', ?a, A}}, [{i, Ann2, {'POP', B}} | Code]) ->
|
|
||||||
case live_out(B, Ann2) of
|
|
||||||
true -> {[{i, merge_ann(Ann1, Ann2), {'STORE', B, A}}], Code};
|
|
||||||
false -> {[], Code}
|
|
||||||
end;
|
|
||||||
r_push_consume({i, Ann1, {'STORE', ?a, A}}, Code) ->
|
r_push_consume({i, Ann1, {'STORE', ?a, A}}, Code) ->
|
||||||
inline_push(Ann1, A, 0, Code, []);
|
inline_push(Ann1, A, 0, Code, []);
|
||||||
%% Writing directly to memory instead of going through the accumulator.
|
%% Writing directly to memory instead of going through the accumulator.
|
||||||
@@ -905,14 +929,6 @@ split_stack_arg(N, [A | As], Acc) ->
|
|||||||
true -> N end,
|
true -> N end,
|
||||||
split_stack_arg(N1, As, [A | Acc]).
|
split_stack_arg(N1, As, [A | Acc]).
|
||||||
|
|
||||||
%% Changing PUSH A, DUPA to PUSH A, PUSH A enables further optimisations
|
|
||||||
r_dup_to_push({i, Ann1, Push={'STORE', ?a, _}}, [{i, Ann2, 'DUPA'} | Code]) ->
|
|
||||||
#{ live_in := LiveIn } = Ann1,
|
|
||||||
Ann1_ = Ann1#{ live_out => LiveIn },
|
|
||||||
Ann2_ = Ann2#{ live_in => LiveIn },
|
|
||||||
{[{i, Ann1_, Push}, {i, Ann2_, Push}], Code};
|
|
||||||
r_dup_to_push(_, _) -> false.
|
|
||||||
|
|
||||||
%% Move PUSH A past non-stack instructions.
|
%% Move PUSH A past non-stack instructions.
|
||||||
r_swap_push(Push = {i, _, {'STORE', ?a, _}}, [I | Code]) ->
|
r_swap_push(Push = {i, _, {'STORE', ?a, _}}, [I | Code]) ->
|
||||||
case independent(Push, I) of
|
case independent(Push, I) of
|
||||||
@@ -1112,15 +1128,15 @@ r_one_shot_var({i, Ann1, I}, [{i, Ann2, J} | Code]) ->
|
|||||||
r_one_shot_var(_, _) -> false.
|
r_one_shot_var(_, _) -> false.
|
||||||
|
|
||||||
%% Remove writes to dead variables
|
%% Remove writes to dead variables
|
||||||
|
r_write_to_dead_var({i, _, {'STORE', ?void, ?a}}, _) -> false; %% Avoid looping
|
||||||
r_write_to_dead_var({i, Ann, I}, Code) ->
|
r_write_to_dead_var({i, Ann, I}, Code) ->
|
||||||
case op_view(I) of
|
case op_view(I) of
|
||||||
{_Op, R = {var, _}, As} ->
|
{_Op, R = {var, _}, As} ->
|
||||||
case live_out(R, Ann) of
|
case live_out(R, Ann) of
|
||||||
false ->
|
false ->
|
||||||
%% Subtle: we still have to pop the stack if any of the arguments
|
%% Subtle: we still have to pop the stack if any of the arguments
|
||||||
%% came from there. In this case we pop to R, which we know is
|
%% came from there.
|
||||||
%% unused.
|
{[{i, Ann, {'STORE', ?void, ?a}} || X <- As, X == ?a], Code};
|
||||||
{[{i, Ann, {'POP', R}} || X <- As, X == ?a], Code};
|
|
||||||
true -> false
|
true -> false
|
||||||
end;
|
end;
|
||||||
_ -> false
|
_ -> false
|
||||||
@@ -1150,9 +1166,9 @@ unannotate(Code) when is_list(Code) ->
|
|||||||
unannotate({i, _Ann, I}) -> [I].
|
unannotate({i, _Ann, I}) -> [I].
|
||||||
|
|
||||||
%% Desugar and specialize
|
%% Desugar and specialize
|
||||||
desugar({'ADD', ?a, ?i(1), ?a}) -> [aeb_fate_code:inc()];
|
desugar({'ADD', ?a, ?i(1), ?a}) -> [aeb_fate_ops:inc()];
|
||||||
desugar({'SUB', ?a, ?a, ?i(1)}) -> [aeb_fate_code:dec()];
|
desugar({'SUB', ?a, ?a, ?i(1)}) -> [aeb_fate_ops:dec()];
|
||||||
desugar({'STORE', ?a, A}) -> [aeb_fate_code:push(A)];
|
desugar({'STORE', ?a, A}) -> [aeb_fate_ops:push(A)];
|
||||||
desugar({switch, Arg, Type, Alts, Def}) ->
|
desugar({switch, Arg, Type, Alts, Def}) ->
|
||||||
[{switch, Arg, Type, [desugar(A) || A <- Alts], desugar(Def)}];
|
[{switch, Arg, Type, [desugar(A) || A <- Alts], desugar(Def)}];
|
||||||
desugar(missing) -> missing;
|
desugar(missing) -> missing;
|
||||||
@@ -1163,12 +1179,16 @@ desugar(I) -> [I].
|
|||||||
%% -- Phase III --------------------------------------------------------------
|
%% -- Phase III --------------------------------------------------------------
|
||||||
%% Constructing basic blocks
|
%% Constructing basic blocks
|
||||||
|
|
||||||
to_basic_blocks(Funs, Options) ->
|
to_basic_blocks(Funs) ->
|
||||||
maps:from_list([ {Name, {{Args, Res},
|
to_basic_blocks(maps:to_list(Funs), aeb_fate_code:new()).
|
||||||
bb(Name, Code ++ [aeb_fate_code:return()], Options)}}
|
|
||||||
|| {Name, {{Args, Res}, Code}} <- maps:to_list(Funs) ]).
|
|
||||||
|
|
||||||
bb(_Name, Code, _Options) ->
|
to_basic_blocks([{Name, {Sig, Code}}|Left], Acc) ->
|
||||||
|
BB = bb(Name, Code ++ [aeb_fate_ops:return()]),
|
||||||
|
to_basic_blocks(Left, aeb_fate_code:insert_fun(Name, Sig, BB, Acc));
|
||||||
|
to_basic_blocks([], Acc) ->
|
||||||
|
Acc.
|
||||||
|
|
||||||
|
bb(_Name, Code) ->
|
||||||
Blocks0 = blocks(Code),
|
Blocks0 = blocks(Code),
|
||||||
Blocks1 = optimize_blocks(Blocks0),
|
Blocks1 = optimize_blocks(Blocks0),
|
||||||
Blocks = lists:flatmap(fun split_calls/1, Blocks1),
|
Blocks = lists:flatmap(fun split_calls/1, Blocks1),
|
||||||
@@ -1219,7 +1239,7 @@ block(Blk = #blk{code = [{switch, Arg, Type, Alts, Default} | Code],
|
|||||||
{DefRef, DefBlk} =
|
{DefRef, DefBlk} =
|
||||||
case Default of
|
case Default of
|
||||||
missing when Catchall == none ->
|
missing when Catchall == none ->
|
||||||
FreshBlk([aeb_fate_code:abort(?i(<<"Incomplete patterns">>))], none);
|
FreshBlk([aeb_fate_ops:abort(?i(<<"Incomplete patterns">>))], none);
|
||||||
missing -> {Catchall, []};
|
missing -> {Catchall, []};
|
||||||
_ -> FreshBlk(Default ++ [{jump, RestRef}], Catchall)
|
_ -> FreshBlk(Default ++ [{jump, RestRef}], Catchall)
|
||||||
%% ^ fall-through to the outer catchall
|
%% ^ fall-through to the outer catchall
|
||||||
@@ -1335,18 +1355,23 @@ chase_labels([L | Ls], Map, Live) ->
|
|||||||
tweak_returns(['RETURN', {'PUSH', A} | Code]) -> [{'RETURNR', A} | Code];
|
tweak_returns(['RETURN', {'PUSH', A} | Code]) -> [{'RETURNR', A} | Code];
|
||||||
tweak_returns(['RETURN' | Code = [{'CALL_T', _} | _]]) -> Code;
|
tweak_returns(['RETURN' | Code = [{'CALL_T', _} | _]]) -> Code;
|
||||||
tweak_returns(['RETURN' | Code = [{'CALL_TR', _, _} | _]]) -> Code;
|
tweak_returns(['RETURN' | Code = [{'CALL_TR', _, _} | _]]) -> Code;
|
||||||
|
tweak_returns(['RETURN' | Code = [{'CALL_GT', _} | _]]) -> Code;
|
||||||
|
tweak_returns(['RETURN' | Code = [{'CALL_GTR', _, _} | _]])-> Code;
|
||||||
tweak_returns(['RETURN' | Code = [{'ABORT', _} | _]]) -> Code;
|
tweak_returns(['RETURN' | Code = [{'ABORT', _} | _]]) -> Code;
|
||||||
tweak_returns(Code) -> Code.
|
tweak_returns(Code) -> Code.
|
||||||
|
|
||||||
%% -- Split basic blocks at CALL instructions --
|
%% -- Split basic blocks at CALL instructions --
|
||||||
%% Calls can only return to a new basic block.
|
%% Calls can only return to a new basic block. Also splits at JUMPIF instructions.
|
||||||
|
|
||||||
split_calls({Ref, Code}) ->
|
split_calls({Ref, Code}) ->
|
||||||
split_calls(Ref, Code, [], []).
|
split_calls(Ref, Code, [], []).
|
||||||
|
|
||||||
split_calls(Ref, [], Acc, Blocks) ->
|
split_calls(Ref, [], Acc, Blocks) ->
|
||||||
lists:reverse([{Ref, lists:reverse(Acc)} | Blocks]);
|
lists:reverse([{Ref, lists:reverse(Acc)} | Blocks]);
|
||||||
split_calls(Ref, [I | Code], Acc, Blocks) when element(1, I) == 'CALL'; element(1, I) == 'CALL_R' ->
|
split_calls(Ref, [I | Code], Acc, Blocks) when element(1, I) == 'CALL';
|
||||||
|
element(1, I) == 'CALL_R';
|
||||||
|
element(1, I) == 'CALL_GR';
|
||||||
|
element(1, I) == 'jumpif' ->
|
||||||
split_calls(make_ref(), Code, [], [{Ref, lists:reverse([I | Acc])} | Blocks]);
|
split_calls(make_ref(), Code, [], [{Ref, lists:reverse([I | Acc])} | Blocks]);
|
||||||
split_calls(Ref, [I | Code], Acc, Blocks) ->
|
split_calls(Ref, [I | Code], Acc, Blocks) ->
|
||||||
split_calls(Ref, Code, [I | Acc], Blocks).
|
split_calls(Ref, Code, [I | Acc], Blocks).
|
||||||
@@ -1355,13 +1380,13 @@ split_calls(Ref, [I | Code], Acc, Blocks) ->
|
|||||||
|
|
||||||
set_labels(Labels, {Ref, Code}) when is_reference(Ref) ->
|
set_labels(Labels, {Ref, Code}) when is_reference(Ref) ->
|
||||||
{maps:get(Ref, Labels), [ set_labels(Labels, I) || I <- Code ]};
|
{maps:get(Ref, Labels), [ set_labels(Labels, I) || I <- Code ]};
|
||||||
set_labels(Labels, {jump, Ref}) -> aeb_fate_code:jump(maps:get(Ref, Labels));
|
set_labels(Labels, {jump, Ref}) -> aeb_fate_ops:jump(maps:get(Ref, Labels));
|
||||||
set_labels(Labels, {jumpif, Arg, Ref}) -> aeb_fate_code:jumpif(Arg, maps:get(Ref, Labels));
|
set_labels(Labels, {jumpif, Arg, Ref}) -> aeb_fate_ops:jumpif(Arg, maps:get(Ref, Labels));
|
||||||
set_labels(Labels, {switch, Arg, Refs}) ->
|
set_labels(Labels, {switch, Arg, Refs}) ->
|
||||||
case [ maps:get(Ref, Labels) || Ref <- Refs ] of
|
case [ maps:get(Ref, Labels) || Ref <- Refs ] of
|
||||||
[R1, R2] -> aeb_fate_code:switch(Arg, R1, R2);
|
[R1, R2] -> aeb_fate_ops:switch(Arg, R1, R2);
|
||||||
[R1, R2, R3] -> aeb_fate_code:switch(Arg, R1, R2, R3);
|
[R1, R2, R3] -> aeb_fate_ops:switch(Arg, R1, R2, R3);
|
||||||
Rs -> aeb_fate_code:switch(Arg, Rs)
|
Rs -> aeb_fate_ops:switch(Arg, Rs)
|
||||||
end;
|
end;
|
||||||
set_labels(_, I) -> I.
|
set_labels(_, I) -> I.
|
||||||
|
|
||||||
|
|||||||
+14
-8
@@ -211,7 +211,7 @@ exprAtom() ->
|
|||||||
, ?RULE(token(hex), set_ann(format, hex, setelement(1, _1, int)))
|
, ?RULE(token(hex), set_ann(format, hex, setelement(1, _1, int)))
|
||||||
, {bool, keyword(true), true}
|
, {bool, keyword(true), true}
|
||||||
, {bool, keyword(false), false}
|
, {bool, keyword(false), false}
|
||||||
, ?RULE(brace_list(?LAZY_P(field_assignment())), record(_1))
|
, ?LET_P(Fs, brace_list(?LAZY_P(field_assignment())), record(Fs))
|
||||||
, {list, [], bracket_list(Expr)}
|
, {list, [], bracket_list(Expr)}
|
||||||
, ?RULE(tok('['), Expr, binop('..'), Expr, tok(']'), _3(_2, _4))
|
, ?RULE(tok('['), Expr, binop('..'), Expr, tok(']'), _3(_2, _4))
|
||||||
, ?RULE(keyword('('), comma_sep(Expr), tok(')'), tuple_e(_1, _2))
|
, ?RULE(keyword('('), comma_sep(Expr), tok(')'), tuple_e(_1, _2))
|
||||||
@@ -254,14 +254,20 @@ record_update(Ann, E, Flds) ->
|
|||||||
record([]) -> {map, [], []};
|
record([]) -> {map, [], []};
|
||||||
record(Fs) ->
|
record(Fs) ->
|
||||||
case record_or_map(Fs) of
|
case record_or_map(Fs) of
|
||||||
record -> {record, get_ann(hd(Fs)), Fs};
|
record ->
|
||||||
|
Fld = fun({field, _, [_], _} = F) -> F;
|
||||||
|
({field, Ann, LV, Id, _}) ->
|
||||||
|
bad_expr_err("Cannot use '@' in record construction", infix({lvalue, Ann, LV}, {'@', Ann}, Id));
|
||||||
|
({field, Ann, LV, _}) ->
|
||||||
|
bad_expr_err("Cannot use nested fields or keys in record construction", {lvalue, Ann, LV}) end,
|
||||||
|
{record, get_ann(hd(Fs)), lists:map(Fld, Fs)};
|
||||||
map ->
|
map ->
|
||||||
Ann = get_ann(hd(Fs ++ [{empty, []}])), %% TODO: source location for empty maps
|
Ann = get_ann(hd(Fs ++ [{empty, []}])), %% TODO: source location for empty maps
|
||||||
KV = fun({field, _, [{map_get, _, Key}], Val}) -> {Key, Val};
|
KV = fun({field, _, [{map_get, _, Key}], Val}) -> {Key, Val};
|
||||||
({field, _, LV, Id, _}) ->
|
({field, FAnn, LV, Id, _}) ->
|
||||||
bad_expr_err("Cannot use '@' in map construction", infix(LV, {op, Ann, '@'}, Id));
|
bad_expr_err("Cannot use '@' in map construction", infix({lvalue, FAnn, LV}, {'@', Ann}, Id));
|
||||||
({field, _, LV, _}) ->
|
({field, FAnn, LV, _}) ->
|
||||||
bad_expr_err("Cannot use nested fields or keys in map construction", LV) end,
|
bad_expr_err("Cannot use nested fields or keys in map construction", {lvalue, FAnn, LV}) end,
|
||||||
{map, Ann, lists:map(KV, Fs)}
|
{map, Ann, lists:map(KV, Fs)}
|
||||||
end.
|
end.
|
||||||
|
|
||||||
@@ -491,11 +497,11 @@ return_error({no_file, L, C}, Err) ->
|
|||||||
return_error({F, L, C}, Err) ->
|
return_error({F, L, C}, Err) ->
|
||||||
fail(io_lib:format("In ~s at ~p:~p:\n~s", [F, L, C, Err])).
|
fail(io_lib:format("In ~s at ~p:~p:\n~s", [F, L, C, Err])).
|
||||||
|
|
||||||
-spec ret_doc_err(ann(), prettypr:document()) -> no_return().
|
-spec ret_doc_err(ann(), prettypr:document()) -> aeso_parse_lib:parser(none()).
|
||||||
ret_doc_err(Ann, Doc) ->
|
ret_doc_err(Ann, Doc) ->
|
||||||
return_error(ann_pos(Ann), prettypr:format(Doc)).
|
return_error(ann_pos(Ann), prettypr:format(Doc)).
|
||||||
|
|
||||||
-spec bad_expr_err(string(), aeso_syntax:expr()) -> no_return().
|
-spec bad_expr_err(string(), aeso_syntax:expr()) -> aeso_parse_lib:parser(none()).
|
||||||
bad_expr_err(Reason, E) ->
|
bad_expr_err(Reason, E) ->
|
||||||
ret_doc_err(get_ann(E),
|
ret_doc_err(get_ann(E),
|
||||||
prettypr:sep([prettypr:text(Reason ++ ":"),
|
prettypr:sep([prettypr:text(Reason ++ ":"),
|
||||||
|
|||||||
@@ -361,6 +361,7 @@ stmt_p({else, Else}) ->
|
|||||||
-spec bin_prec(aeso_syntax:bin_op()) -> {integer(), integer(), integer()}.
|
-spec bin_prec(aeso_syntax:bin_op()) -> {integer(), integer(), integer()}.
|
||||||
bin_prec('..') -> { 0, 0, 0}; %% Always printed inside '[ ]'
|
bin_prec('..') -> { 0, 0, 0}; %% Always printed inside '[ ]'
|
||||||
bin_prec('=') -> { 0, 0, 0}; %% Always printed inside '[ ]'
|
bin_prec('=') -> { 0, 0, 0}; %% Always printed inside '[ ]'
|
||||||
|
bin_prec('@') -> { 0, 0, 0}; %% Only in error messages
|
||||||
bin_prec('||') -> {200, 300, 200};
|
bin_prec('||') -> {200, 300, 200};
|
||||||
bin_prec('&&') -> {300, 400, 300};
|
bin_prec('&&') -> {300, 400, 300};
|
||||||
bin_prec('<') -> {400, 500, 500};
|
bin_prec('<') -> {400, 500, 500};
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
%%%-------------------------------------------------------------------
|
%%%-------------------------------------------------------------------
|
||||||
-module(aeso_syntax_utils).
|
-module(aeso_syntax_utils).
|
||||||
|
|
||||||
-export([used_ids/1, used_types/1, used/1]).
|
-export([used_ids/1, used_types/2, used/1]).
|
||||||
|
|
||||||
-record(alg, {zero, plus, scoped}).
|
-record(alg, {zero, plus, scoped}).
|
||||||
|
|
||||||
@@ -100,8 +100,12 @@ fold(Alg = #alg{zero = Zero, plus = Plus, scoped = Scoped}, Fun, K, X) ->
|
|||||||
used_ids(E) ->
|
used_ids(E) ->
|
||||||
[ X || {{term, [X]}, _} <- used(E) ].
|
[ X || {{term, [X]}, _} <- used(E) ].
|
||||||
|
|
||||||
used_types(T) ->
|
used_types([Top] = _CurrentNS, T) ->
|
||||||
[ X || {{type, [X]}, _} <- used(T) ].
|
F = fun({{type, [X]}, _}) -> [X];
|
||||||
|
({{type, [Top1, X]}, _}) when Top1 == Top -> [X];
|
||||||
|
(_) -> []
|
||||||
|
end,
|
||||||
|
lists:flatmap(F, used(T)).
|
||||||
|
|
||||||
-type entity() :: {term, [string()]}
|
-type entity() :: {term, [string()]}
|
||||||
| {type, [string()]}
|
| {type, [string()]}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{application, aesophia,
|
{application, aesophia,
|
||||||
[{description, "Contract Language for aeternity"},
|
[{description, "Contract Language for aeternity"},
|
||||||
{vsn, "3.0.0"},
|
{vsn, "3.1.0"},
|
||||||
{registered, []},
|
{registered, []},
|
||||||
{applications,
|
{applications,
|
||||||
[kernel,
|
[kernel,
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
-module(aeso_abi_tests).
|
-module(aeso_abi_tests).
|
||||||
|
|
||||||
-include_lib("eunit/include/eunit.hrl").
|
-include_lib("eunit/include/eunit.hrl").
|
||||||
-compile(export_all).
|
-compile([export_all, nowarn_export_all]).
|
||||||
|
|
||||||
-define(SANDBOX(Code), sandbox(fun() -> Code end)).
|
-define(SANDBOX(Code), sandbox(fun() -> Code end)).
|
||||||
-define(DUMMY_HASH_WORD, 16#123).
|
-define(DUMMY_HASH_WORD, 16#123).
|
||||||
@@ -62,6 +62,7 @@ encode_decode_sophia_test() ->
|
|||||||
Other -> Other
|
Other -> Other
|
||||||
end end,
|
end end,
|
||||||
ok = Check("int", "42"),
|
ok = Check("int", "42"),
|
||||||
|
ok = Check("int", "-42"),
|
||||||
ok = Check("bool", "true"),
|
ok = Check("bool", "true"),
|
||||||
ok = Check("bool", "false"),
|
ok = Check("bool", "false"),
|
||||||
ok = Check("string", "\"Hello\""),
|
ok = Check("string", "\"Hello\""),
|
||||||
|
|||||||
+92
-46
@@ -2,31 +2,30 @@
|
|||||||
|
|
||||||
-include_lib("eunit/include/eunit.hrl").
|
-include_lib("eunit/include/eunit.hrl").
|
||||||
|
|
||||||
|
simple_aci_test_() ->
|
||||||
do_test() ->
|
[{"Test contract " ++ integer_to_list(N),
|
||||||
test_contract(1),
|
fun() -> test_contract(N) end}
|
||||||
test_contract(2),
|
|| N <- [1, 2, 3]].
|
||||||
test_contract(3).
|
|
||||||
|
|
||||||
test_contract(N) ->
|
test_contract(N) ->
|
||||||
{Contract,MapACI,DecACI} = test_cases(N),
|
{Contract,MapACI,DecACI} = test_cases(N),
|
||||||
{ok,JSON} = aeso_aci:encode(Contract),
|
{ok,JSON} = aeso_aci:contract_interface(json, Contract),
|
||||||
?assertEqual(MapACI, jsx:decode(JSON, [return_maps])),
|
?assertEqual([MapACI], JSON),
|
||||||
?assertEqual(DecACI, aeso_aci:decode(JSON)).
|
?assertEqual({ok, DecACI}, aeso_aci:render_aci_json(JSON)).
|
||||||
|
|
||||||
test_cases(1) ->
|
test_cases(1) ->
|
||||||
Contract = <<"contract C =\n"
|
Contract = <<"contract C =\n"
|
||||||
" function a(i : int) = i+1\n">>,
|
" function a(i : int) = i+1\n">>,
|
||||||
MapACI = #{<<"contract">> =>
|
MapACI = #{contract =>
|
||||||
#{<<"name">> => <<"C">>,
|
#{name => <<"C">>,
|
||||||
<<"type_defs">> => [],
|
type_defs => [],
|
||||||
<<"functions">> =>
|
functions =>
|
||||||
[#{<<"name">> => <<"a">>,
|
[#{name => <<"a">>,
|
||||||
<<"arguments">> =>
|
arguments =>
|
||||||
[#{<<"name">> => <<"i">>,
|
[#{name => <<"i">>,
|
||||||
<<"type">> => [<<"int">>]}],
|
type => <<"int">>}],
|
||||||
<<"returns">> => <<"int">>,
|
returns => <<"int">>,
|
||||||
<<"stateful">> => false}]}},
|
stateful => false}]}},
|
||||||
DecACI = <<"contract C =\n"
|
DecACI = <<"contract C =\n"
|
||||||
" function a : (int) => int\n">>,
|
" function a : (int) => int\n">>,
|
||||||
{Contract,MapACI,DecACI};
|
{Contract,MapACI,DecACI};
|
||||||
@@ -35,42 +34,89 @@ test_cases(2) ->
|
|||||||
Contract = <<"contract C =\n"
|
Contract = <<"contract C =\n"
|
||||||
" type allan = int\n"
|
" type allan = int\n"
|
||||||
" function a(i : allan) = i+1\n">>,
|
" function a(i : allan) = i+1\n">>,
|
||||||
MapACI = #{<<"contract">> =>
|
MapACI = #{contract =>
|
||||||
#{<<"name">> => <<"C">>,
|
#{name => <<"C">>,
|
||||||
<<"type_defs">> =>
|
type_defs =>
|
||||||
[#{<<"name">> => <<"allan">>,
|
[#{name => <<"allan">>,
|
||||||
<<"typedef">> => <<"int">>,
|
typedef => <<"int">>,
|
||||||
<<"vars">> => []}],
|
vars => []}],
|
||||||
<<"functions">> =>
|
functions =>
|
||||||
[#{<<"arguments">> =>
|
[#{arguments =>
|
||||||
[#{<<"name">> => <<"i">>,
|
[#{name => <<"i">>,
|
||||||
<<"type">> => [<<"int">>]}],
|
type => <<"C.allan">>}],
|
||||||
<<"name">> => <<"a">>,
|
name => <<"a">>,
|
||||||
<<"returns">> => <<"int">>,
|
returns => <<"int">>,
|
||||||
<<"stateful">> => false}]}},
|
stateful => false}]}},
|
||||||
DecACI = <<"contract C =\n"
|
DecACI = <<"contract C =\n"
|
||||||
" function a : (int) => int\n">>,
|
" type allan = int\n"
|
||||||
|
" function a : (C.allan) => int\n">>,
|
||||||
{Contract,MapACI,DecACI};
|
{Contract,MapACI,DecACI};
|
||||||
test_cases(3) ->
|
test_cases(3) ->
|
||||||
Contract = <<"contract C =\n"
|
Contract = <<"contract C =\n"
|
||||||
|
" type state = ()\n"
|
||||||
|
" datatype event = SingleEventDefined\n"
|
||||||
" datatype bert('a) = Bin('a)\n"
|
" datatype bert('a) = Bin('a)\n"
|
||||||
" function a(i : bert(string)) = 1\n">>,
|
" function a(i : bert(string)) = 1\n">>,
|
||||||
MapACI = #{<<"contract">> =>
|
MapACI = #{contract =>
|
||||||
#{<<"functions">> =>
|
#{functions =>
|
||||||
[#{<<"arguments">> =>
|
[#{arguments =>
|
||||||
[#{<<"name">> => <<"i">>,
|
[#{name => <<"i">>,
|
||||||
<<"type">> =>
|
type =>
|
||||||
[#{<<"C.bert">> => [<<"string">>]}]}],
|
#{<<"C.bert">> => [<<"string">>]}}],
|
||||||
<<"name">> => <<"a">>,<<"returns">> => <<"int">>,
|
name => <<"a">>,returns => <<"int">>,
|
||||||
<<"stateful">> => false}],
|
stateful => false}],
|
||||||
<<"name">> => <<"C">>,
|
name => <<"C">>,
|
||||||
<<"type_defs">> =>
|
event => #{variant => [#{<<"SingleEventDefined">> => []}]},
|
||||||
[#{<<"name">> => <<"bert">>,
|
state => #{tuple => []},
|
||||||
<<"typedef">> =>
|
type_defs =>
|
||||||
#{<<"variant">> =>
|
[#{name => <<"bert">>,
|
||||||
|
typedef =>
|
||||||
|
#{variant =>
|
||||||
[#{<<"Bin">> => [<<"'a">>]}]},
|
[#{<<"Bin">> => [<<"'a">>]}]},
|
||||||
<<"vars">> => [#{<<"name">> => <<"'a">>}]}]}},
|
vars => [#{name => <<"'a">>}]}]}},
|
||||||
DecACI = <<"contract C =\n"
|
DecACI = <<"contract C =\n"
|
||||||
|
" type state = ()\n"
|
||||||
|
" datatype event = SingleEventDefined\n"
|
||||||
" datatype bert('a) = Bin('a)\n"
|
" datatype bert('a) = Bin('a)\n"
|
||||||
" function a : (C.bert(string)) => int\n">>,
|
" function a : (C.bert(string)) => int\n">>,
|
||||||
{Contract,MapACI,DecACI}.
|
{Contract,MapACI,DecACI}.
|
||||||
|
|
||||||
|
%% Rounttrip
|
||||||
|
aci_test_() ->
|
||||||
|
[{"Testing ACI generation for " ++ ContractName,
|
||||||
|
fun() -> aci_test_contract(ContractName) end}
|
||||||
|
|| ContractName <- all_contracts()].
|
||||||
|
|
||||||
|
all_contracts() -> aeso_compiler_tests:compilable_contracts().
|
||||||
|
|
||||||
|
aci_test_contract(Name) ->
|
||||||
|
String = aeso_test_utils:read_contract(Name),
|
||||||
|
Opts = [{include, {file_system, [aeso_test_utils:contract_path()]}}],
|
||||||
|
{ok, JSON} = aeso_aci:contract_interface(json, String, Opts),
|
||||||
|
|
||||||
|
io:format("JSON:\n~p\n", [JSON]),
|
||||||
|
{ok, ContractStub} = aeso_aci:render_aci_json(JSON),
|
||||||
|
|
||||||
|
io:format("STUB:\n~s\n", [ContractStub]),
|
||||||
|
check_stub(ContractStub, [{src_file, Name}]),
|
||||||
|
|
||||||
|
ok.
|
||||||
|
|
||||||
|
check_stub(Stub, Options) ->
|
||||||
|
case aeso_parser:string(binary_to_list(Stub), Options) of
|
||||||
|
{ok, Ast} ->
|
||||||
|
try
|
||||||
|
%% io:format("AST: ~120p\n", [Ast]),
|
||||||
|
aeso_ast_infer_types:infer(Ast, [])
|
||||||
|
catch _:{type_errors, TE} ->
|
||||||
|
io:format("Type error:\n~s\n", [TE]),
|
||||||
|
error(TE);
|
||||||
|
_:R ->
|
||||||
|
io:format("Error: ~p\n", [R]),
|
||||||
|
error(R)
|
||||||
|
end;
|
||||||
|
{error, E} ->
|
||||||
|
io:format("Error: ~p\n", [E]),
|
||||||
|
error({parse_error, E})
|
||||||
|
end.
|
||||||
|
|
||||||
|
|||||||
@@ -16,20 +16,24 @@
|
|||||||
%% are made on the output, just that it is a binary which indicates
|
%% are made on the output, just that it is a binary which indicates
|
||||||
%% that the compilation worked.
|
%% that the compilation worked.
|
||||||
simple_compile_test_() ->
|
simple_compile_test_() ->
|
||||||
[ {"Testing the " ++ ContractName ++ " contract",
|
[ {"Testing the " ++ ContractName ++ " contract with the " ++ atom_to_list(Backend) ++ " backend",
|
||||||
fun() ->
|
fun() ->
|
||||||
case compile(ContractName) of
|
case compile(Backend, ContractName) of
|
||||||
#{byte_code := ByteCode,
|
#{byte_code := ByteCode,
|
||||||
contract_source := _,
|
contract_source := _,
|
||||||
type_info := _} -> ?assertMatch(Code when is_binary(Code), ByteCode);
|
type_info := _} when Backend == aevm ->
|
||||||
|
?assertMatch(Code when is_binary(Code), ByteCode);
|
||||||
|
Code when Backend == fate, is_tuple(Code) ->
|
||||||
|
?assertMatch(#{}, aeb_fate_code:functions(Code));
|
||||||
ErrBin ->
|
ErrBin ->
|
||||||
io:format("\n~s", [ErrBin]),
|
io:format("\n~s", [ErrBin]),
|
||||||
error(ErrBin)
|
error(ErrBin)
|
||||||
end
|
end
|
||||||
end} || ContractName <- compilable_contracts() ] ++
|
end} || ContractName <- compilable_contracts(), Backend <- [aevm, fate],
|
||||||
|
not lists:member(ContractName, not_yet_compilable(Backend))] ++
|
||||||
[ {"Testing error messages of " ++ ContractName,
|
[ {"Testing error messages of " ++ ContractName,
|
||||||
fun() ->
|
fun() ->
|
||||||
case compile(ContractName) of
|
case compile(aevm, ContractName) of
|
||||||
<<"Type errors\n", ErrorString/binary>> ->
|
<<"Type errors\n", ErrorString/binary>> ->
|
||||||
check_errors(lists:sort(ExpectedErrors), ErrorString);
|
check_errors(lists:sort(ExpectedErrors), ErrorString);
|
||||||
<<"Parse errors\n", ErrorString/binary>> ->
|
<<"Parse errors\n", ErrorString/binary>> ->
|
||||||
@@ -44,14 +48,14 @@ simple_compile_test_() ->
|
|||||||
{ok, Bin} = file:read_file(filename:join([aeso_test_utils:contract_path(), File])),
|
{ok, Bin} = file:read_file(filename:join([aeso_test_utils:contract_path(), File])),
|
||||||
{File, Bin}
|
{File, Bin}
|
||||||
end || File <- ["included.aes", "../contracts/included2.aes"] ]),
|
end || File <- ["included.aes", "../contracts/included2.aes"] ]),
|
||||||
#{byte_code := Code1} = compile("include", [{include, {explicit_files, FileSystem}}]),
|
#{byte_code := Code1} = compile(aevm, "include", [{include, {explicit_files, FileSystem}}]),
|
||||||
#{byte_code := Code2} = compile("include"),
|
#{byte_code := Code2} = compile(aevm, "include"),
|
||||||
?assertMatch(true, Code1 == Code2)
|
?assertMatch(true, Code1 == Code2)
|
||||||
end} ] ++
|
end} ] ++
|
||||||
[ {"Testing deadcode elimination",
|
[ {"Testing deadcode elimination",
|
||||||
fun() ->
|
fun() ->
|
||||||
#{ byte_code := NoDeadCode } = compile("nodeadcode"),
|
#{ byte_code := NoDeadCode } = compile(aevm, "nodeadcode"),
|
||||||
#{ byte_code := DeadCode } = compile("deadcode"),
|
#{ byte_code := DeadCode } = compile(aevm, "deadcode"),
|
||||||
SizeNoDeadCode = byte_size(NoDeadCode),
|
SizeNoDeadCode = byte_size(NoDeadCode),
|
||||||
SizeDeadCode = byte_size(DeadCode),
|
SizeDeadCode = byte_size(DeadCode),
|
||||||
?assertMatch({_, _, true}, {SizeDeadCode, SizeNoDeadCode, SizeDeadCode + 40 < SizeNoDeadCode}),
|
?assertMatch({_, _, true}, {SizeDeadCode, SizeNoDeadCode, SizeDeadCode + 40 < SizeNoDeadCode}),
|
||||||
@@ -67,12 +71,12 @@ check_errors(Expect, ErrorString) ->
|
|||||||
{Missing, Extra} -> ?assertEqual(Missing, Extra)
|
{Missing, Extra} -> ?assertEqual(Missing, Extra)
|
||||||
end.
|
end.
|
||||||
|
|
||||||
compile(Name) ->
|
compile(Backend, Name) ->
|
||||||
compile(Name, [{include, {file_system, [aeso_test_utils:contract_path()]}}]).
|
compile(Backend, Name, [{include, {file_system, [aeso_test_utils:contract_path()]}}]).
|
||||||
|
|
||||||
compile(Name, Options) ->
|
compile(Backend, Name, Options) ->
|
||||||
String = aeso_test_utils:read_contract(Name),
|
String = aeso_test_utils:read_contract(Name),
|
||||||
case aeso_compiler:from_string(String, [{src_file, Name} | Options]) of
|
case aeso_compiler:from_string(String, [{src_file, Name}, {backend, Backend} | Options]) of
|
||||||
{ok, Map} -> Map;
|
{ok, Map} -> Map;
|
||||||
{error, ErrorString} -> ErrorString
|
{error, ErrorString} -> ErrorString
|
||||||
end.
|
end.
|
||||||
@@ -112,6 +116,16 @@ compilable_contracts() ->
|
|||||||
"address_chain"
|
"address_chain"
|
||||||
].
|
].
|
||||||
|
|
||||||
|
not_yet_compilable(fate) ->
|
||||||
|
["oracles", %% Oracle.register
|
||||||
|
"events", %% events
|
||||||
|
"basic_auth", %% auth_tx_hash instruction
|
||||||
|
"bitcoin_auth", %% auth_tx_hash instruction
|
||||||
|
"address_literals", %% oracle_query_id literals
|
||||||
|
"address_chain" %% Oracle.check_query
|
||||||
|
];
|
||||||
|
not_yet_compilable(aevm) -> [].
|
||||||
|
|
||||||
%% Contracts that should produce type errors
|
%% Contracts that should produce type errors
|
||||||
|
|
||||||
failing_contracts() ->
|
failing_contracts() ->
|
||||||
@@ -207,20 +221,15 @@ failing_contracts() ->
|
|||||||
, {"missing_fields_in_record_expression",
|
, {"missing_fields_in_record_expression",
|
||||||
[<<"The field x is missing when constructing an element of type r('a) (at line 7, column 40)">>,
|
[<<"The field x is missing when constructing an element of type r('a) (at line 7, column 40)">>,
|
||||||
<<"The field y is missing when constructing an element of type r(int) (at line 8, column 40)">>,
|
<<"The field y is missing when constructing an element of type r(int) (at line 8, column 40)">>,
|
||||||
<<"The fields y, z are missing when constructing an element of type r('1) (at line 6, column 40)">>]}
|
<<"The fields y, z are missing when constructing an element of type r('a) (at line 6, column 40)">>]}
|
||||||
, {"namespace_clash",
|
, {"namespace_clash",
|
||||||
[<<"The contract Call (at line 4, column 10) has the same name as a namespace at (builtin location)">>]}
|
[<<"The contract Call (at line 4, column 10) has the same name as a namespace at (builtin location)">>]}
|
||||||
, {"bad_events",
|
, {"bad_events",
|
||||||
[<<"The payload type int (at line 10, column 30) should be string">>,
|
[<<"The indexed type string (at line 9, column 25) is not a word type">>,
|
||||||
<<"The payload type alias_address (at line 12, column 30) equals address but it should be string">>,
|
<<"The indexed type alias_string (at line 10, column 25) equals string which is not a word type">>]}
|
||||||
<<"The indexed type string (at line 9, column 25) is not a word type">>,
|
|
||||||
<<"The indexed type alias_string (at line 11, column 25) equals string which is not a word type">>]}
|
|
||||||
, {"bad_events2",
|
, {"bad_events2",
|
||||||
[<<"The event constructor BadEvent1 (at line 9, column 7) has too many non-indexed values (max 1)">>,
|
[<<"The event constructor BadEvent1 (at line 9, column 7) has too many non-indexed values (max 1)">>,
|
||||||
<<"The event constructor BadEvent2 (at line 10, column 7) has too many indexed values (max 3)">>,
|
<<"The event constructor BadEvent2 (at line 10, column 7) has too many indexed values (max 3)">>]}
|
||||||
<<"The event constructor BadEvent3 (at line 11, column 7) has too many non-indexed values (max 1)">>,
|
|
||||||
<<"The payload type address (at line 11, column 17) should be string">>,
|
|
||||||
<<"The payload type int (at line 11, column 26) should be string">>]}
|
|
||||||
, {"type_clash",
|
, {"type_clash",
|
||||||
[<<"Cannot unify int\n"
|
[<<"Cannot unify int\n"
|
||||||
" and string\n"
|
" and string\n"
|
||||||
@@ -247,46 +256,46 @@ failing_contracts() ->
|
|||||||
" ct_Ez6MyeTMm17YnTnDdHTSrzMEBKmy7Uz2sXu347bTDPgVH2ifJ\n"
|
" ct_Ez6MyeTMm17YnTnDdHTSrzMEBKmy7Uz2sXu347bTDPgVH2ifJ\n"
|
||||||
"has the type\n"
|
"has the type\n"
|
||||||
" address">>,
|
" address">>,
|
||||||
<<"Cannot unify oracle_query('1, '2)\n"
|
<<"Cannot unify oracle_query('a, 'b)\n"
|
||||||
" and Remote\n"
|
" and Remote\n"
|
||||||
"when checking the type of the expression at line 25, column 5\n"
|
"when checking the type of the expression at line 25, column 5\n"
|
||||||
" oq_2oRvyowJuJnEkxy58Ckkw77XfWJrmRgmGaLzhdqb67SKEL1gPY :\n"
|
" oq_2oRvyowJuJnEkxy58Ckkw77XfWJrmRgmGaLzhdqb67SKEL1gPY :\n"
|
||||||
" oracle_query('1, '2)\n"
|
" oracle_query('a, 'b)\n"
|
||||||
"against the expected type\n"
|
"against the expected type\n"
|
||||||
" Remote">>,
|
" Remote">>,
|
||||||
<<"Cannot unify oracle_query('3, '4)\n"
|
<<"Cannot unify oracle_query('c, 'd)\n"
|
||||||
" and bytes(32)\n"
|
" and bytes(32)\n"
|
||||||
"when checking the type of the expression at line 23, column 5\n"
|
"when checking the type of the expression at line 23, column 5\n"
|
||||||
" oq_2oRvyowJuJnEkxy58Ckkw77XfWJrmRgmGaLzhdqb67SKEL1gPY :\n"
|
" oq_2oRvyowJuJnEkxy58Ckkw77XfWJrmRgmGaLzhdqb67SKEL1gPY :\n"
|
||||||
" oracle_query('3, '4)\n"
|
" oracle_query('c, 'd)\n"
|
||||||
"against the expected type\n"
|
"against the expected type\n"
|
||||||
" bytes(32)">>,
|
" bytes(32)">>,
|
||||||
<<"Cannot unify oracle_query('5, '6)\n"
|
<<"Cannot unify oracle_query('e, 'f)\n"
|
||||||
" and oracle(int, bool)\n"
|
" and oracle(int, bool)\n"
|
||||||
"when checking the type of the expression at line 21, column 5\n"
|
"when checking the type of the expression at line 21, column 5\n"
|
||||||
" oq_2oRvyowJuJnEkxy58Ckkw77XfWJrmRgmGaLzhdqb67SKEL1gPY :\n"
|
" oq_2oRvyowJuJnEkxy58Ckkw77XfWJrmRgmGaLzhdqb67SKEL1gPY :\n"
|
||||||
" oracle_query('5, '6)\n"
|
" oracle_query('e, 'f)\n"
|
||||||
"against the expected type\n"
|
"against the expected type\n"
|
||||||
" oracle(int, bool)">>,
|
" oracle(int, bool)">>,
|
||||||
<<"Cannot unify oracle('7, '8)\n"
|
<<"Cannot unify oracle('g, 'h)\n"
|
||||||
" and Remote\n"
|
" and Remote\n"
|
||||||
"when checking the type of the expression at line 18, column 5\n"
|
"when checking the type of the expression at line 18, column 5\n"
|
||||||
" ok_2YNyxd6TRJPNrTcEDCe9ra59SVUdp9FR9qWC5msKZWYD9bP9z5 :\n"
|
" ok_2YNyxd6TRJPNrTcEDCe9ra59SVUdp9FR9qWC5msKZWYD9bP9z5 :\n"
|
||||||
" oracle('7, '8)\n"
|
" oracle('g, 'h)\n"
|
||||||
"against the expected type\n"
|
"against the expected type\n"
|
||||||
" Remote">>,
|
" Remote">>,
|
||||||
<<"Cannot unify oracle('9, '10)\n"
|
<<"Cannot unify oracle('i, 'j)\n"
|
||||||
" and bytes(32)\n"
|
" and bytes(32)\n"
|
||||||
"when checking the type of the expression at line 16, column 5\n"
|
"when checking the type of the expression at line 16, column 5\n"
|
||||||
" ok_2YNyxd6TRJPNrTcEDCe9ra59SVUdp9FR9qWC5msKZWYD9bP9z5 :\n"
|
" ok_2YNyxd6TRJPNrTcEDCe9ra59SVUdp9FR9qWC5msKZWYD9bP9z5 :\n"
|
||||||
" oracle('9, '10)\n"
|
" oracle('i, 'j)\n"
|
||||||
"against the expected type\n"
|
"against the expected type\n"
|
||||||
" bytes(32)">>,
|
" bytes(32)">>,
|
||||||
<<"Cannot unify oracle('11, '12)\n"
|
<<"Cannot unify oracle('k, 'l)\n"
|
||||||
" and oracle_query(int, bool)\n"
|
" and oracle_query(int, bool)\n"
|
||||||
"when checking the type of the expression at line 14, column 5\n"
|
"when checking the type of the expression at line 14, column 5\n"
|
||||||
" ok_2YNyxd6TRJPNrTcEDCe9ra59SVUdp9FR9qWC5msKZWYD9bP9z5 :\n"
|
" ok_2YNyxd6TRJPNrTcEDCe9ra59SVUdp9FR9qWC5msKZWYD9bP9z5 :\n"
|
||||||
" oracle('11, '12)\n"
|
" oracle('k, 'l)\n"
|
||||||
"against the expected type\n"
|
"against the expected type\n"
|
||||||
" oracle_query(int, bool)">>,
|
" oracle_query(int, bool)">>,
|
||||||
<<"Cannot unify address\n"
|
<<"Cannot unify address\n"
|
||||||
@@ -329,4 +338,7 @@ failing_contracts() ->
|
|||||||
<<"The init function should return the initial state as its result and cannot read the state,\n"
|
<<"The init function should return the initial state as its result and cannot read the state,\n"
|
||||||
"but it calls\n"
|
"but it calls\n"
|
||||||
" - state (at line 13, column 13)">>]}
|
" - state (at line 13, column 13)">>]}
|
||||||
|
, {"field_parse_error",
|
||||||
|
[<<"line 6, column 1: In field_parse_error at 5:26:\n"
|
||||||
|
"Cannot use nested fields or keys in record construction: p.x\n">>]}
|
||||||
].
|
].
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ simple_contracts_test_() ->
|
|||||||
%% Parse tests of example contracts
|
%% Parse tests of example contracts
|
||||||
[ {lists:concat(["Parse the ", Contract, " contract."]),
|
[ {lists:concat(["Parse the ", Contract, " contract."]),
|
||||||
fun() -> roundtrip_contract(Contract) end}
|
fun() -> roundtrip_contract(Contract) end}
|
||||||
|| Contract <- [counter, voting, all_syntax, '05_greeter', aeproof, multi_sig, simple_storage, withdrawal, fundme, dutch_auction] ]
|
|| Contract <- [counter, voting, all_syntax, '05_greeter', aeproof, multi_sig, simple_storage, fundme, dutch_auction] ]
|
||||||
}.
|
}.
|
||||||
|
|
||||||
parse_contract(Name) ->
|
parse_contract(Name) ->
|
||||||
|
|||||||
@@ -6,10 +6,8 @@ contract Events =
|
|||||||
datatype event =
|
datatype event =
|
||||||
Event1(indexed alias_int, indexed int, string)
|
Event1(indexed alias_int, indexed int, string)
|
||||||
| Event2(alias_string, indexed alias_address)
|
| Event2(alias_string, indexed alias_address)
|
||||||
| BadEvent1(indexed string, string)
|
| BadEvent1(indexed string)
|
||||||
| BadEvent2(indexed int, int)
|
| BadEvent2(indexed alias_string)
|
||||||
| BadEvent3(indexed alias_string, string)
|
|
||||||
| BadEvent4(indexed int, alias_address)
|
|
||||||
|
|
||||||
function f1(x : int, y : string) =
|
function f1(x : int, y : string) =
|
||||||
Chain.event(Event1(x, x+1, y))
|
Chain.event(Event1(x, x+1, y))
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ contract Events =
|
|||||||
| Event2(alias_string, indexed alias_address)
|
| Event2(alias_string, indexed alias_address)
|
||||||
| BadEvent1(string, string)
|
| BadEvent1(string, string)
|
||||||
| BadEvent2(indexed int, indexed int, indexed int, indexed address)
|
| BadEvent2(indexed int, indexed int, indexed int, indexed address)
|
||||||
| BadEvent3(address, int)
|
|
||||||
|
|
||||||
function f1(x : int, y : string) =
|
function f1(x : int, y : string) =
|
||||||
Chain.event(Event1(x, x+1, y))
|
Chain.event(Event1(x, x+1, y))
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
|
||||||
|
contract Fail =
|
||||||
|
record pt = {x : int, y : int}
|
||||||
|
record r = {p : pt}
|
||||||
|
function fail() = {p.x = 0, p.y = 0}
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
/* Example from Solidity by Example
|
|
||||||
http://solidity.readthedocs.io/en/develop/common-patterns.html
|
|
||||||
|
|
||||||
contract WithdrawalContract {
|
|
||||||
address public richest
|
|
||||||
uint public mostSent
|
|
||||||
|
|
||||||
mapping (address => uint) pendingWithdrawals
|
|
||||||
|
|
||||||
function WithdrawalContract() payable {
|
|
||||||
richest = msg.sender
|
|
||||||
mostSent = msg.value
|
|
||||||
}
|
|
||||||
|
|
||||||
function becomeRichest() payable returns (bool) {
|
|
||||||
if (msg.value > mostSent) {
|
|
||||||
pendingWithdrawals[richest] += msg.value
|
|
||||||
richest = msg.sender
|
|
||||||
mostSent = msg.value
|
|
||||||
return true
|
|
||||||
} else {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function withdraw() {
|
|
||||||
uint amount = pendingWithdrawals[msg.sender]
|
|
||||||
// Remember to zero the pending refund before
|
|
||||||
// sending to prevent re-entrancy attacks
|
|
||||||
pendingWithdrawals[msg.sender] = 0
|
|
||||||
msg.sender.transfer(amount)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
*/
|
|
||||||
|
|
||||||
contract WithdrawalContract =
|
|
||||||
|
|
||||||
record state = { richest : address,
|
|
||||||
mostSent : uint,
|
|
||||||
pendingWithdrawals : map(address, uint) }
|
|
||||||
|
|
||||||
function becomeRichest() : result(bool) =
|
|
||||||
if (call().value > state.mostSent)
|
|
||||||
let totalAmount : uint = Map.get_(state.richest, pendingWithdrawals) + call().value
|
|
||||||
{state = state{ pendingWithdrawals = Map.insert(state.richest, call().value, state.pendingWithdrawals),
|
|
||||||
richest = call().sender,
|
|
||||||
mostSent = call().value },
|
|
||||||
result = true}
|
|
||||||
else
|
|
||||||
{result = false}
|
|
||||||
|
|
||||||
function withdraw() =
|
|
||||||
let amount : uint = Map.get_(call().sender, state.pendingWithdrawals)
|
|
||||||
{ state.pendingWithdrawals = Map.insert(call().sender, 0, state.pendingWithdrawals),
|
|
||||||
transactions = spend_tx(amount, call().sender) }
|
|
||||||
Reference in New Issue
Block a user