Skip to content

Implicit casting: booleans

E. Rivas requested to merge er433/typer/subtype-bool into dev

Motivation and Context

Related Issue(s): #1778 (closed)

Description

This MR adds support for implicit casting to booleans.

We extend subtype to account for such casting. To make implicit casts in if conditions, we tweak the nanopass to add a bool annotation on the condition, so it triggers the check of the expression to bool, and later subtype.

On while loops this is not necessary, as the condition is checked against bool directly.

We use C_COERCE to wrap a coerced value in the typer. A new pass in Self_ast_aggregated replaces C_COERCE by the corresponding coercion.

Other changes in this MR: land now gets mapped to a new operation C_LAND (and similar for lor and lxor).

Component

  • compiler
  • website
  • webide
  • vscode-plugin
  • debugger

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Performance improvement (non-breaking change that improves performance)
  • None (change with no changelog)

Changelog

When checking an expression for a boolean, certain values are "casted" implicitly:

  • n : nat is true iff 0 < n
  • n : int is true iff 0 <> n
  • n : tez is true iff 0 < n
  • s : string is true iff "" < s
  • b : bytes is true iff empty-bytes < b
  • xs : 'a list is true iff xs = []
  • xs : 'a set is true iff 0 < Set.cardinal xs
  • m : ('a, 'b) map is true iff 0 < Map.size m

Now values of types such as nat, int, tez, string, bytes, lists, maps and sets can be used in conditions, and are casted automatically to bool:

const f = (s : list<int>) => {
  let _s = s;
  let k = 0;
  while (_s && k < 3) {
    _s = Option.unopt(List.tail_opt(_s));
    k++;
  };
  return k;
};

Checklist:

  • If a new syntax has been introduced, put a message on slack ligo-lsp
  • Changes follow the existing coding style (use dune @fmt to check).
  • Tests for the changes have been added (for bug fixes / feature).
  • Documentation has been updated.
  • Changelog description has been added (if appropriate).
  • Start titles under ## Changelog section with #### (if appropriate).
  • There is no image or uploaded file in changelog
  • Examples in changed behaviour have been added to the changelog (for breaking change / feature).
Edited by E. Rivas

Merge request reports