Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Added if() built-in function in Jenny #2259

Merged
merged 5 commits into from
Jan 9, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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 doc/_sphinx/extensions/yarn_lexer.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ class YarnLexer(RegexLexer):
'decimal',
'dice',
'floor',
'if',
'inc',
'int',
'number',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ There are around 20 built-in functions in Jenny, listed below; and it is also po
- [`string(x)`](type.md#stringx)

- **Other functions**
- [`if(condition, then, else)`](misc.md#ifcondition-then-else)
- [`plural(x, ...)`](misc.md#pluralx-words)
- [`visit_count(node)`](misc.md#visit_countnode)
- [`visited(node)`](misc.md#visitednode)
Expand Down
19 changes: 19 additions & 0 deletions doc/other_modules/jenny/language/expressions/functions/misc.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,25 @@
# Miscellaneous functions


## if(condition, then, else)

This function implements the ternary-if condition, it is equivalent to the `?:` operator in C/C++.
st-pasha marked this conversation as resolved.
Show resolved Hide resolved

The function evaluates its `condition` (which must be a boolean), and then returns either the value
of `then` if the condition was `true`, or the value of `else` if the condition was `false`. The
types of arguments `then` and `else` must be the same.

Note: Only one of the `then`/`else` values will be evaluated, depending on the `condition`. This
may be important in cases when evaluating those expressions may produce a side-effect.

```yarn
title: Birth
---
Doctor: Congratulations, you have a { if($gender == "m", "boy", "girl") }!
===
```


## plural(x, words...)

Returns the correct plural form depending on the value of variable `x`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import 'package:jenny/src/structure/expressions/functions/dec.dart';
import 'package:jenny/src/structure/expressions/functions/decimal.dart';
import 'package:jenny/src/structure/expressions/functions/dice.dart';
import 'package:jenny/src/structure/expressions/functions/floor.dart';
import 'package:jenny/src/structure/expressions/functions/if.dart';
import 'package:jenny/src/structure/expressions/functions/inc.dart';
import 'package:jenny/src/structure/expressions/functions/int.dart';
import 'package:jenny/src/structure/expressions/functions/number.dart';
Expand Down Expand Up @@ -33,13 +34,18 @@ typedef FunctionBuilder = Expression Function(
ErrorFn,
);

/// This is a complete list of all builtin functions in Jenny.
///
/// When adding a new function, make sure to also update the list in
/// /doc/_sphinx/extensions/yarn_lexer.py.
const Map<String, FunctionBuilder> builtinFunctions = {
'bool': BoolFn.make,
'ceil': CeilFn.make,
'dec': DecFn.make,
'decimal': DecimalFn.make,
'dice': DiceFn.make,
'floor': FloorFn.make,
'if': makeIfFn,
'inc': IncFn.make,
'int': IntFn.make,
'number': NumberFn.make,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import 'package:jenny/src/structure/expressions/expression.dart';
import 'package:jenny/src/structure/expressions/functions/_common.dart';
import 'package:jenny/src/yarn_project.dart';

Expression makeIfFn(
List<FunctionArgument> args,
YarnProject yarnProject,
ErrorFn errorFn,
) {
if (args.length != 3) {
errorFn(
'function if() requires three arguments',
args.length < 3 ? null : args[3].position,
);
}
if (!args[0].expression.isBoolean) {
errorFn(
'first argument in if() should be a boolean condition',
args[0].position,
);
}
final type1 = args[1].expression.type;
final type2 = args[2].expression.type;
if (type1 != type2) {
errorFn(
'the types of the second and the third arguments in if() must be the '
'same, instead they were ${type1.name} and ${type2.name}',
args[2].position,
);
}
if (args[1].expression.isBoolean) {
return _IfFnBoolean(
args[0].expression as BoolExpression,
args[1].expression as BoolExpression,
args[2].expression as BoolExpression,
);
} else if (args[1].expression.isNumeric) {
return _IfFnNumeric(
args[0].expression as BoolExpression,
args[1].expression as NumExpression,
args[2].expression as NumExpression,
);
} else {
assert(args[1].expression.isString);
return _IfFnString(
args[0].expression as BoolExpression,
args[1].expression as StringExpression,
args[2].expression as StringExpression,
);
}
}

class _IfFnBoolean extends BoolExpression {
_IfFnBoolean(this._condition, this._then, this._else);

final BoolExpression _condition;
final BoolExpression _then;
final BoolExpression _else;

@override
bool get value => _condition.value ? _then.value : _else.value;
}

class _IfFnNumeric extends NumExpression {
_IfFnNumeric(this._condition, this._then, this._else);

final BoolExpression _condition;
final NumExpression _then;
final NumExpression _else;

@override
num get value => _condition.value ? _then.value : _else.value;
}

class _IfFnString extends StringExpression {
_IfFnString(this._condition, this._then, this._else);

final BoolExpression _condition;
final StringExpression _then;
final StringExpression _else;

@override
String get value => _condition.value ? _then.value : _else.value;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import 'package:jenny/src/yarn_project.dart';
import 'package:test/test.dart';

import '../../../test_scenario.dart';
import '../../../utils.dart';

void main() {
group('if()', () {
test('if() normal case', () async {
await testScenario(
input: '''
title: Start
---
{ if(true, 17, -1) }
{ if(false, 17, -1) }
{ if(true, false, true) }
{ if(true, "orange", "magenta") }
{ if(false, "orange", "magenta") }
===
''',
testPlan: '''
line: 17
line: -1
line: false
line: orange
line: magenta
''',
);
});

test('then/else evaluate only if necessary', () async {
var invocationCount = 0;
num t() => invocationCount++;

await testScenario(
yarn: YarnProject()..functions.addFunction0('t', t),
input: '''
title: Start
---
{ if(true, t() + 1, t() + 5) }
{ if(false, t() + 1, t() + 5) }
===
''',
testPlan: '''
line: 1
line: 6
''',
);
expect(invocationCount, 2);
});

group('errors', () {
test('too few arguments', () {
expect(
() => YarnProject()
..parse(
'title:A\n---\n{if(true, 1)}\n===\n',
),
hasTypeError(
'TypeError: function if() requires three arguments\n'
'> at line 3 column 12:\n'
'> {if(true, 1)}\n'
'> ^\n',
),
);
});

test('too many arguments', () {
expect(
() => YarnProject()
..parse(
'title:A\n---\n{if(true, 1, 3, 6)}\n===\n',
),
hasTypeError(
'TypeError: function if() requires three arguments\n'
'> at line 3 column 17:\n'
'> {if(true, 1, 3, 6)}\n'
'> ^\n',
),
);
});

test('first argument is not boolean', () {
expect(
() => YarnProject()
..parse(
'title:A\n---\n{if(1, 3, 6)}\n===\n',
),
hasTypeError(
'TypeError: first argument in if() should be a boolean condition\n'
'> at line 3 column 5:\n'
'> {if(1, 3, 6)}\n'
'> ^\n',
),
);
});

test('incompatible argument types', () {
expect(
() => YarnProject()
..parse(
'title:A\n---\n{if(true, 3, "no")}\n===\n',
),
hasTypeError(
'TypeError: the types of the second and the third arguments in '
'if() must be the same, instead they were numeric and string\n'
'> at line 3 column 14:\n'
'> {if(true, 3, "no")}\n'
'> ^\n',
),
);
});
});
});
}