titan-lang / titan

The Titan programming language
http://titan-lang.org
MIT License
406 stars 13 forks source link

Option types #239

Closed mascarenhas closed 6 years ago

mascarenhas commented 6 years ago

The idea of this first version of option types (t?) is to be "gradually typed", that is, Titan has a distinction between t and t?, but will implicitly cast between those two types (of course, casting from t? to t will fail at runtime if the value is not there). The rationale is to not bother the programmer with having to prove that the value is always there, as that is very finnicky in an imperative language, but fail fast if he thinks he is handling a real value but the value is not actually there, so "nulls" do not propagate.

A key piece of this is to never infer an option type, the programmer has to explicitly "opt-in" to having an expression be nullable. So even though reading from an array always gives back an option type, initializing a variable from an array will always check if the value exists and type it accordingly, unless the programmer explicitly tells Titan he wants to propagate the option with something like local x: integer? = arr[i].

Explicitly keeping a value optional is some thing that we expect to be common, so there is syntax to infer option types: local x? = <exp>.

Option types play well with the usual Lua idioms for and and or. The type of x and y is an option type constructed from the type of y, and the type of x or y is t if x has type t? and y has type t, so the "ternary operator" <cond> and <exptrue> or <expfalse> works as expected.

codecov-io commented 6 years ago

Codecov Report

Merging #239 into master will decrease coverage by 0.55%. The diff coverage is 85.09%.

Impacted Files Coverage Δ
titan-compiler/lexer.lua 100% <100%> (ø) :arrow_up:
titan-compiler/ast.lua 100% <100%> (ø) :arrow_up:
titan-compiler/parser.lua 96.62% <100%> (+0.29%) :arrow_up:
titan-compiler/coder.lua 94.03% <77.58%> (-1.46%) :arrow_down:
titan-compiler/checker.lua 90.2% <88.72%> (ø) :arrow_up:
titan-compiler/types.lua 87.58% <89.18%> (+0.86%) :arrow_up:

Continue to review full report at Codecov.

Legend - Click here to learn more Δ = absolute <relative> (impact), ø = not affected, ? = missing data Powered by Codecov. Last update bc612d3...6f9b781. Read the comment docs.