Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Lexer.g4
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ STAR: '*';
PLUS: '+';
MINUS: '-';
DIV: '/';
RESTRICT: '\\';

PERCENTAGE_PORTION_LITERAL: [0-9]+ ('.' [0-9]+)? '%';

Expand Down
8 changes: 5 additions & 3 deletions Numscript.g4
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,13 @@ allotment:
valueExpr # portionedAllotment
| REMAINING # remainingAllotment;

colorConstraint: RESTRICT valueExpr;

source:
address = valueExpr ALLOWING UNBOUNDED OVERDRAFT # srcAccountUnboundedOverdraft
| address = valueExpr ALLOWING OVERDRAFT UP TO maxOvedraft = valueExpr #
address = valueExpr colorConstraint? ALLOWING UNBOUNDED OVERDRAFT # srcAccountUnboundedOverdraft
| address = valueExpr colorConstraint? ALLOWING OVERDRAFT UP TO maxOvedraft = valueExpr #
srcAccountBoundedOverdraft
| valueExpr # srcAccount
| valueExpr colorConstraint? # srcAccount
| LBRACE allotmentClauseSrc+ RBRACE # srcAllotment
| LBRACE source* RBRACE # srcInorder
| ONEOF LBRACE source+ RBRACE # srcOneof
Expand Down
16 changes: 14 additions & 2 deletions internal/analysis/check.go
Original file line number Diff line number Diff line change
Expand Up @@ -476,18 +476,29 @@ func (res *CheckResult) checkSource(source parser.Source) {
switch source := source.(type) {
case *parser.SourceAccount:
res.checkExpression(source.ValueExpr, TypeAccount)
res.checkExpression(source.Color, TypeString)
if account, ok := source.ValueExpr.(*parser.AccountInterpLiteral); ok {
if account.IsWorld() && res.unboundedSend {
res.pushDiagnostic(source.GetRange(), InvalidUnboundedAccount{})
} else if account.IsWorld() {
res.unboundedAccountInSend = account
}

if _, emptied := res.emptiedAccount[account.String()]; emptied && !account.IsWorld() {
coloredAccountName := account.String()
switch col := source.Color.(type) {
case *parser.Variable:
coloredAccountName += "\\$" + col.Name
case *parser.StringLiteral:
if col.String != "" {
coloredAccountName += "\\\"" + col.String + "\""
}
}

if _, emptied := res.emptiedAccount[coloredAccountName]; emptied && !account.IsWorld() {
res.pushDiagnostic(account.Range, EmptiedAccount{Name: account.String()})
}

res.emptiedAccount[account.String()] = struct{}{}
res.emptiedAccount[coloredAccountName] = struct{}{}
Comment on lines +497 to +501
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Inconsistent error message for emptied colored accounts.

While the code correctly tracks emptied accounts using the colored account name, the error message still only shows the base account name without the color information.

Consider updating the error message to include color information:

 if _, emptied := res.emptiedAccount[coloredAccountName]; emptied && !account.IsWorld() {
-    res.pushDiagnostic(account.Range, EmptiedAccount{Name: account.String()})
+    res.pushDiagnostic(account.Range, EmptiedAccount{Name: coloredAccountName})
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if _, emptied := res.emptiedAccount[coloredAccountName]; emptied && !account.IsWorld() {
res.pushDiagnostic(account.Range, EmptiedAccount{Name: account.String()})
}
res.emptiedAccount[account.String()] = struct{}{}
res.emptiedAccount[coloredAccountName] = struct{}{}
if _, emptied := res.emptiedAccount[coloredAccountName]; emptied && !account.IsWorld() {
- res.pushDiagnostic(account.Range, EmptiedAccount{Name: account.String()})
+ res.pushDiagnostic(account.Range, EmptiedAccount{Name: coloredAccountName})
}
res.emptiedAccount[coloredAccountName] = struct{}{}

}

case *parser.SourceOverdraft:
Expand All @@ -507,6 +518,7 @@ func (res *CheckResult) checkSource(source parser.Source) {
}

res.checkExpression(source.Address, TypeAccount)
res.checkExpression(source.Color, TypeString)
if source.Bounded != nil {
res.checkExpression(*source.Bounded, TypeMonetary)
}
Expand Down
66 changes: 66 additions & 0 deletions internal/analysis/check_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -861,3 +861,69 @@ send $m ( source = @world destination = @dest)
checkSource(input),
)
}

func TestCheckColorVar(t *testing.T) {
t.Parallel()

input := `
send [COIN 100] (
source = {
@a \ $col1
@b \ $col2 allowing unbounded overdraft
}
destination = @dest
)`

require.Equal(t,
[]analysis.Diagnostic{
{
Range: parser.RangeOfIndexed(input, "$col1", 0),
Kind: analysis.UnboundVariable{Name: "col1", Type: "string"},
},
{
Range: parser.RangeOfIndexed(input, "$col2", 0),
Kind: analysis.UnboundVariable{Name: "col2", Type: "string"},
},
},
checkSource(input),
)
}

func TestInorderRedundantWhenColored(t *testing.T) {
t.Parallel()

input := `send [COIN 100] (
source = {
@a
@a \ "x"
}
destination = @dest
)`

require.Equal(t,
[]analysis.Diagnostic(nil),
checkSource(input),
)
}

func TestInorderRedundantWhenEmptyColored(t *testing.T) {
t.Parallel()

input := `send [COIN 100] (
source = {
@a
@a \ "" // <- empty color behaves as no color
}
destination = @dest
)`

require.Equal(t,
[]analysis.Diagnostic{
{
Range: parser.RangeOfIndexed(input, "@a", 1),
Kind: analysis.EmptiedAccount{Name: "a"},
},
},
checkSource(input),
)
}
2 changes: 2 additions & 0 deletions internal/flags/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const (
ExperimentalOneofFeatureFlag FeatureFlag = "experimental-oneof"
ExperimentalAccountInterpolationFlag FeatureFlag = "experimental-account-interpolation"
ExperimentalMidScriptFunctionCall FeatureFlag = "experimental-mid-script-function-call"
ExperimentalAssetColors FeatureFlag = "experimental-asset-colors"
)

var AllFlags []string = []string{
Expand All @@ -18,4 +19,5 @@ var AllFlags []string = []string{
ExperimentalOneofFeatureFlag,
ExperimentalAccountInterpolationFlag,
ExperimentalMidScriptFunctionCall,
ExperimentalAssetColors,
}
16 changes: 16 additions & 0 deletions internal/interpreter/balances.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package interpreter

import (
"math/big"
"strings"

"github.com/formancehq/numscript/internal/utils"
)
Expand All @@ -12,6 +13,21 @@ func (b Balances) fetchAccountBalances(account string) AccountBalance {
})
}

func coloredAsset(asset string, color *string) string {
if color == nil || *color == "" {
return asset
}

// note: 1 <= len(parts) <= 2
parts := strings.Split(asset, "/")

coloredAsset := parts[0] + "_" + *color
if len(parts) > 1 {
coloredAsset += "/" + parts[1]
}
return coloredAsset
}

// Get the (account, asset) tuple from the Balances
// if the tuple is not present, it will write a big.NewInt(0) in it and return it
func (b Balances) fetchBalance(account string, asset string) *big.Int {
Expand Down
19 changes: 15 additions & 4 deletions internal/interpreter/batch_balances_query.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
if err != nil {
return err
}
st.batchQuery(*account, *asset)
st.batchQuery(*account, *asset, nil)
return nil

case *parser.SendStatement:
Expand All @@ -50,10 +50,11 @@
}
}

func (st *programState) batchQuery(account string, asset string) {
func (st *programState) batchQuery(account string, asset string, color *string) {
if account == "world" {
return
}
asset = coloredAsset(asset, color)

previousValues := st.CurrentBalanceQuery[account]
if !slices.Contains(previousValues, asset) {
Expand Down Expand Up @@ -89,7 +90,12 @@
return err
}

st.batchQuery(*account, st.CurrentAsset)
color, err := evaluateOptExprAs(st, source.Color, expectString)
if err != nil {
return err
}

Check warning on line 96 in internal/interpreter/batch_balances_query.go

View check run for this annotation

Codecov / codecov/patch

internal/interpreter/batch_balances_query.go#L95-L96

Added lines #L95 - L96 were not covered by tests

st.batchQuery(*account, st.CurrentAsset, color)
return nil

case *parser.SourceOverdraft:
Expand All @@ -102,7 +108,12 @@
if err != nil {
return err
}
st.batchQuery(*account, st.CurrentAsset)
color, err := evaluateOptExprAs(st, source.Color, expectString)
if err != nil {
return err
}

Check warning on line 114 in internal/interpreter/batch_balances_query.go

View check run for this annotation

Codecov / codecov/patch

internal/interpreter/batch_balances_query.go#L113-L114

Added lines #L113 - L114 were not covered by tests

st.batchQuery(*account, st.CurrentAsset, color)
return nil

case *parser.SourceInorder:
Expand Down
27 changes: 27 additions & 0 deletions internal/interpreter/evaluate_expr.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,13 @@
}
}

func evaluateOptExprAs[T any](st *programState, expr parser.ValueExpr, expect func(Value, parser.Range) (*T, InterpreterError)) (*T, InterpreterError) {
if expr == nil {
return nil, nil
}
return evaluateExprAs(st, expr, expect)
}

func evaluateExprAs[T any](st *programState, expr parser.ValueExpr, expect func(Value, parser.Range) (*T, InterpreterError)) (*T, InterpreterError) {
value, err := st.evaluateExpr(expr)
if err != nil {
Expand All @@ -127,6 +134,26 @@
return values, nil
}

func (s *programState) evaluateColor(colorExpr parser.ValueExpr) (*string, InterpreterError) {
color, err := evaluateOptExprAs(s, colorExpr, expectString)
if err != nil {
return nil, err
}

Check warning on line 141 in internal/interpreter/evaluate_expr.go

View check run for this annotation

Codecov / codecov/patch

internal/interpreter/evaluate_expr.go#L140-L141

Added lines #L140 - L141 were not covered by tests
if color == nil {
return nil, nil
}

isValidColor := colorRe.Match([]byte(*color))
if !isValidColor {
return nil, InvalidColor{
Range: colorExpr.GetRange(),
Color: *color,
}
}

return color, nil
}

func (st *programState) plusOp(left parser.ValueExpr, right parser.ValueExpr) (Value, InterpreterError) {
leftValue, err := evaluateExprAs(st, left, expectOneOf(
expectMapped(expectMonetary, func(m Monetary) opAdd {
Expand Down
Loading