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

fix(compiler): no error when trying to reassign to a let variable #1196

Merged
merged 13 commits into from
Jan 22, 2023
Merged
Show file tree
Hide file tree
Changes from 6 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
13 changes: 13 additions & 0 deletions docs/04-reference/winglang-spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,19 @@ Examples in the class section below.
Assigning `var` to immutables of the same type is allowed. That is similar
to assigning non `readonly`s to `readonly`s in TypeScript.

By default function closure arguments are non-reassignable. By prefixing `var`
to an argument definition you can make a re-assignable function argument:

```ts
// wing
let f = (arg1: num, var arg2: num) => {
if (arg2 > 100) {
// We can reassign a value to arg2 since it's marked `var`
args2 = 100;
}
}
```

[`▲ top`][top]

---
Expand Down
23 changes: 21 additions & 2 deletions examples/tests/invalid/reassing_to_nonreassignable.w
Original file line number Diff line number Diff line change
@@ -1,2 +1,21 @@
let x = 9;
x = 10;
// Assign to non-reassignable var
let x = 5;
x = x + 1;

// Assign to non-reassignable field
resource R {
f: num;
init() {
this.f = 1;
}

inc() {
this.f = this.f + 1;
}
}

// Assign to non-reassignable arg
let f = (arg: num):num => {
arg = 0;
return arg;
}
22 changes: 22 additions & 0 deletions examples/tests/valid/reassignment.w
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,25 @@ assert(x == 5);

x = x + 1;
assert(x == 6);

resource R {
var f: num;
init() {
this.f = 1;
}

inc() {
this.f = this.f + 1;
}
}

let r = new R();
r.inc();
assert(r.f == 2);

let f = (var arg: num):num => {
arg = 0;
return arg;
}

assert(f(1) == 0);
yoav-steinberg marked this conversation as resolved.
Show resolved Hide resolved
17 changes: 8 additions & 9 deletions libs/wingc/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,9 @@ pub struct FunctionSignature {
#[derive(Derivative)]
#[derivative(Debug)]
pub struct FunctionDefinition {
pub parameters: Vec<(Symbol, VariableKind)>, // TODO: move into FunctionSignature and make optional
// List of names of function parameters and whether they are reassignable (`var`) or not.
pub parameters: Vec<(Symbol, bool)>, // TODO: move into FunctionSignature and make optional

pub statements: Scope,
pub signature: FunctionSignature,
#[derivative(Debug = "ignore")]
Expand All @@ -143,7 +145,9 @@ pub struct FunctionDefinition {

#[derive(Debug)]
pub struct Constructor {
pub parameters: Vec<(Symbol, VariableKind)>,
// List of names of constructor parameters and whether they are reassignable (`var`) or not.
pub parameters: Vec<(Symbol, bool)>,

pub statements: Scope,
pub signature: FunctionSignature,
}
Expand Down Expand Up @@ -181,7 +185,7 @@ pub enum StmtKind {
identifier: Option<Symbol>,
},
VariableDef {
kind: VariableKind,
reassignable: bool,
var_name: Symbol,
initial_value: Expr,
type_: Option<Type>,
Expand Down Expand Up @@ -226,16 +230,11 @@ pub enum StmtKind {
},
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum VariableKind {
Let,
Var,
}

#[derive(Debug)]
pub struct ClassMember {
pub name: Symbol,
pub member_type: Type,
pub reassignable: bool,
pub flight: Phase,
}

Expand Down
16 changes: 4 additions & 12 deletions libs/wingc/src/capture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,12 +86,7 @@ pub fn scan_for_inflights_in_scope(scope: &Scope, diagnostics: &mut Diagnostics)
}
}
}
StmtKind::VariableDef {
kind: _,
var_name: _,
initial_value,
type_: _,
} => {
StmtKind::VariableDef { initial_value, .. } => {
scan_for_inflights_in_expression(initial_value, diagnostics);
}
StmtKind::Expression(exp) => {
Expand Down Expand Up @@ -406,12 +401,9 @@ fn scan_captures_in_inflight_scope(scope: &Scope, diagnostics: &mut Diagnostics)

for s in scope.statements.iter() {
match &s.kind {
StmtKind::VariableDef {
kind: _,
var_name: _,
initial_value,
type_: _,
} => res.extend(scan_captures_in_expression(initial_value, env, s.idx, diagnostics)),
StmtKind::VariableDef { initial_value, .. } => {
res.extend(scan_captures_in_expression(initial_value, env, s.idx, diagnostics))
}
StmtKind::ForLoop {
iterator: _,
iterable,
Expand Down
19 changes: 7 additions & 12 deletions libs/wingc/src/jsify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use sha2::{Digest, Sha256};
use crate::{
ast::{
ArgList, BinaryOperator, ClassMember, Expr, ExprKind, FunctionDefinition, InterpolatedStringPart, Literal, Phase,
Reference, Scope, Stmt, StmtKind, Symbol, Type, UnaryOperator, UtilityFunctions, VariableKind,
Reference, Scope, Stmt, StmtKind, Symbol, Type, UnaryOperator, UtilityFunctions,
},
capture::CaptureKind,
utilities::snake_case_to_camel_case,
Expand Down Expand Up @@ -466,15 +466,16 @@ impl JSifier {
)
}
StmtKind::VariableDef {
kind,
reassignable,
var_name,
initial_value,
type_: _,
} => {
let initial_value = self.jsify_expression(initial_value, phase);
return match kind {
VariableKind::Let => format!("const {} = {};", self.jsify_symbol(var_name), initial_value),
VariableKind::Var => format!("let {} = {};", self.jsify_symbol(var_name), initial_value),
return if *reassignable {
format!("let {} = {};", self.jsify_symbol(var_name), initial_value)
} else {
format!("const {} = {};", self.jsify_symbol(var_name), initial_value)
};
}
StmtKind::ForLoop {
Expand Down Expand Up @@ -696,13 +697,7 @@ impl JSifier {
)
}

fn jsify_function(
&self,
name: Option<&str>,
parameters: &[(Symbol, VariableKind)],
body: &Scope,
phase: Phase,
) -> String {
fn jsify_function(&self, name: Option<&str>, parameters: &[(Symbol, bool)], body: &Scope, phase: Phase) -> String {
let mut parameter_list = vec![];
for p in parameters.iter() {
parameter_list.push(self.jsify_symbol(&p.0));
Expand Down
11 changes: 4 additions & 7 deletions libs/wingc/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
#[macro_use]
extern crate lazy_static;

use ast::{Scope, Stmt, Symbol, UtilityFunctions, VariableKind};
use ast::{Scope, Stmt, Symbol, UtilityFunctions};
use diagnostic::{print_diagnostics, Diagnostic, DiagnosticLevel, Diagnostics, WingSpan};
use jsify::JSifier;
use type_check::symbol_env::StatementIdx;
use type_check::{FunctionSignature, SymbolKind, Type, VariableInfo};
use type_check::{FunctionSignature, SymbolKind, Type};

use crate::parser::Parser;
use std::cell::RefCell;
Expand Down Expand Up @@ -93,7 +93,7 @@ pub fn parse(source_file: &str) -> (Scope, Diagnostics) {
}

pub fn type_check(scope: &mut Scope, types: &mut Types) -> Diagnostics {
let env = SymbolEnv::new(None, types.void(), false, Phase::Preflight, 0);
let env = SymbolEnv::new(None, types.void(), false, false, Phase::Preflight, 0);
scope.set_env(env);

add_builtin(
Expand Down Expand Up @@ -158,10 +158,7 @@ fn add_builtin(name: &str, typ: Type, scope: &mut Scope, types: &mut Types) {
.unwrap()
.define(
&sym,
SymbolKind::Variable(VariableInfo {
_type: types.add_type(typ),
kind: VariableKind::Let,
}),
SymbolKind::make_variable(types.add_type(typ), false),
StatementIdx::Top,
)
.expect("Failed to add builtin");
Expand Down
27 changes: 11 additions & 16 deletions libs/wingc/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use tree_sitter_traversal::{traverse, Order};
use crate::ast::{
ArgList, BinaryOperator, ClassMember, Constructor, Expr, ExprKind, FunctionDefinition, FunctionSignature,
InterpolatedString, InterpolatedStringPart, Literal, Phase, Reference, Scope, Stmt, StmtKind, Symbol, Type,
UnaryOperator, VariableKind,
UnaryOperator,
};
use crate::diagnostic::{Diagnostic, DiagnosticLevel, DiagnosticResult, Diagnostics, WingSpan};

Expand Down Expand Up @@ -183,14 +183,8 @@ impl Parser<'_> {
None
};

let kind = if let Some(_) = statement_node.child_by_field_name("reassignable") {
VariableKind::Var
} else {
VariableKind::Let
};

StmtKind::VariableDef {
kind,
reassignable: statement_node.child_by_field_name("reassignable").is_some(),
var_name: self.node_symbol(&statement_node.child_by_field_name("name").unwrap())?,
initial_value: self.build_expression(&statement_node.child_by_field_name("value").unwrap())?,
type_,
Expand Down Expand Up @@ -316,11 +310,13 @@ impl Parser<'_> {
("class_member", _) => members.push(ClassMember {
name: self.node_symbol(&class_element.child_by_field_name("name").unwrap())?,
member_type: self.build_type(&class_element.child_by_field_name("type").unwrap())?,
reassignable: class_element.child_by_field_name("reassignable").is_some(),
flight: Phase::Preflight,
}),
("inflight_class_member", _) => members.push(ClassMember {
name: self.node_symbol(&class_element.child_by_field_name("name").unwrap())?,
member_type: self.build_type(&class_element.child_by_field_name("type").unwrap())?,
reassignable: class_element.child_by_field_name("reassignable").is_some(),
flight: Phase::Inflight,
}),
("constructor", _) => {
Expand Down Expand Up @@ -409,24 +405,23 @@ impl Parser<'_> {
})
}

fn build_parameter_list(&self, parameter_list_node: &Node) -> DiagnosticResult<Vec<(Symbol, Type, VariableKind)>> {
/// Builds a vector of all parameters defined in `parameter_list_node`.
///
/// # Returns
/// A vector of tuples for each parameter in the list. The tuples are the name, type and a bool letting
/// us know whether the parameter is reassignable or not respectively.
fn build_parameter_list(&self, parameter_list_node: &Node) -> DiagnosticResult<Vec<(Symbol, Type, bool)>> {
let mut res = vec![];
let mut cursor = parameter_list_node.walk();
for parameter_definition_node in parameter_list_node.named_children(&mut cursor) {
if parameter_definition_node.is_extra() {
continue;
}

let kind = if let Some(_) = parameter_definition_node.child_by_field_name("reassignable") {
VariableKind::Var
} else {
VariableKind::Let
};

res.push((
self.node_symbol(&parameter_definition_node.child_by_field_name("name").unwrap())?,
self.build_type(&parameter_definition_node.child_by_field_name("type").unwrap())?,
kind,
parameter_definition_node.child_by_field_name("reassignable").is_some(),
))
}

Expand Down
Loading