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 2 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
2 changes: 2 additions & 0 deletions examples/tests/invalid/reassing_to_nonreassignable.w
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
let x = 9;
x = 10;
2 changes: 1 addition & 1 deletion examples/tests/valid/anon_function.w
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Define a function and assign it to a variable
let myfunc = (x: num) => {
let myfunc = (var x: num) => {
print("${x}");
x = x + 1;
if (x > 3.14) {
Expand Down
8 changes: 6 additions & 2 deletions libs/tree-sitter-wing/grammar.js
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ module.exports = grammar({
class_member: ($) =>
seq(
optional(field("access_modifier", $.access_modifier)),
optional($.reassignable),
optional(field("reassignable", $.reassignable)),
field("name", $.identifier),
$._type_annotation,
";"
Expand Down Expand Up @@ -373,7 +373,11 @@ module.exports = grammar({
access_modifier: ($) => choice("public", "private", "protected"),

parameter_definition: ($) =>
seq(field("name", $.identifier), $._type_annotation),
seq(
optional(field("reassignable", $.reassignable)),
field("name", $.identifier),
$._type_annotation
),

parameter_list: ($) => seq("(", commaSep($.parameter_definition), ")"),

Expand Down
3 changes: 2 additions & 1 deletion libs/tree-sitter-wing/test/corpus/statements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ return 1;
Inflight closure
====================

inflight (a: num, b: str?, c: bool) => {};
inflight (a: num, b: str?, var c: bool) => {};

---

Expand All @@ -95,6 +95,7 @@ inflight (a: num, b: str?, c: bool) => {};
)
)
(parameter_definition
reassignable: (reassignable)
name: (identifier)
type: (builtin_type)
)
Expand Down
4 changes: 2 additions & 2 deletions libs/wingc/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ pub struct FunctionSignature {
#[derive(Derivative)]
#[derivative(Debug)]
pub struct FunctionDefinition {
pub parameter_names: Vec<Symbol>, // TODO: move into FunctionSignature and make optional
pub parameters: Vec<(Symbol, VariableKind)>, // TODO: move into FunctionSignature and make optional
pub statements: Scope,
pub signature: FunctionSignature,
#[derivative(Debug = "ignore")]
Expand All @@ -143,7 +143,7 @@ pub struct FunctionDefinition {

#[derive(Debug)]
pub struct Constructor {
pub parameters: Vec<Symbol>,
pub parameters: Vec<(Symbol, VariableKind)>,
pub statements: Scope,
pub signature: FunctionSignature,
}
Expand Down
5 changes: 3 additions & 2 deletions libs/wingc/src/capture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,8 @@ fn scan_captures_in_call(
Ok((prop_type, phase)) => (
prop_type
.as_variable()
.expect("Expected resource property to be a variable"),
.expect("Expected resource property to be a variable")
._type,
phase,
),
Err(type_error) => {
Expand Down Expand Up @@ -263,7 +264,7 @@ fn scan_captures_in_expression(
span: Some(symbol.span.clone()),
});
} else {
let t = var.as_variable().unwrap();
let t = var.as_variable().unwrap()._type;

// if the identifier represents a preflight value, then capture it
if f == Phase::Preflight {
Expand Down
18 changes: 12 additions & 6 deletions libs/wingc/src/jsify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -438,7 +438,7 @@ impl JSifier {
ExprKind::FunctionClosure(func_def) => match func_def.signature.flight {
Phase::Inflight => self.jsify_inflight_function(func_def),
Phase::Independent => unimplemented!(),
Phase::Preflight => self.jsify_function(None, &func_def.parameter_names, &func_def.statements, phase),
Phase::Preflight => self.jsify_function(None, &func_def.parameters, &func_def.statements, phase),
},
}
}
Expand Down Expand Up @@ -567,7 +567,7 @@ impl JSifier {
.map(|(n, m)| format!(
"{} = {}",
n.name,
self.jsify_function(None, &m.parameter_names, &m.statements, phase)
self.jsify_function(None, &m.parameters, &m.statements, phase)
))
.collect::<Vec<String>>()
.join("\n")
Expand Down Expand Up @@ -623,8 +623,8 @@ impl JSifier {

fn jsify_inflight_function(&self, func_def: &FunctionDefinition) -> String {
let mut parameter_list = vec![];
for p in func_def.parameter_names.iter() {
parameter_list.push(p.name.clone());
for p in func_def.parameters.iter() {
parameter_list.push(p.0.name.clone());
}
let block = self.jsify_scope(&func_def.statements, Phase::Inflight);
let procid = base16ct::lower::encode_string(&Sha256::new().chain_update(&block).finalize());
Expand Down Expand Up @@ -696,10 +696,16 @@ impl JSifier {
)
}

fn jsify_function(&self, name: Option<&str>, parameters: &[Symbol], body: &Scope, phase: Phase) -> String {
fn jsify_function(
&self,
name: Option<&str>,
parameters: &[(Symbol, VariableKind)],
body: &Scope,
phase: Phase,
) -> String {
let mut parameter_list = vec![];
for p in parameters.iter() {
parameter_list.push(self.jsify_symbol(p));
parameter_list.push(self.jsify_symbol(&p.0));
}

let (name, arrow) = match name {
Expand Down
7 changes: 5 additions & 2 deletions libs/wingc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use ast::{Scope, Stmt, Symbol, UtilityFunctions, VariableKind};
use diagnostic::{print_diagnostics, Diagnostic, DiagnosticLevel, Diagnostics, WingSpan};
use jsify::JSifier;
use type_check::symbol_env::StatementIdx;
use type_check::{FunctionSignature, SymbolKind, Type};
use type_check::{FunctionSignature, SymbolKind, Type, VariableInfo};

use crate::parser::Parser;
use std::cell::RefCell;
Expand Down Expand Up @@ -158,7 +158,10 @@ fn add_builtin(name: &str, typ: Type, scope: &mut Scope, types: &mut Types) {
.unwrap()
.define(
&sym,
SymbolKind::Variable(types.add_type(typ), VariableKind::Let),
SymbolKind::Variable(VariableInfo {
_type: types.add_type(typ),
kind: VariableKind::Let,
}),
StatementIdx::Top,
)
.expect("Failed to add builtin");
Expand Down
14 changes: 11 additions & 3 deletions libs/wingc/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ impl Parser<'_> {
}
let parameters = self.build_parameter_list(&class_element.child_by_field_name("parameter_list").unwrap())?;
constructor = Some(Constructor {
parameters: parameters.iter().map(|p| p.0.clone()).collect(),
parameters: parameters.iter().map(|p| (p.0.clone(), p.2)).collect(),
statements: self.build_scope(&class_element.child_by_field_name("block").unwrap()),
signature: FunctionSignature {
parameters: parameters.iter().map(|p| p.1.clone()).collect(),
Expand Down Expand Up @@ -394,7 +394,7 @@ impl Parser<'_> {
fn build_function_definition(&self, func_def_node: &Node, flight: Phase) -> DiagnosticResult<FunctionDefinition> {
let parameters = self.build_parameter_list(&func_def_node.child_by_field_name("parameter_list").unwrap())?;
Ok(FunctionDefinition {
parameter_names: parameters.iter().map(|p| p.0.clone()).collect(),
parameters: parameters.iter().map(|p| (p.0.clone(), p.2)).collect(),
statements: self.build_scope(&func_def_node.child_by_field_name("block").unwrap()),
signature: FunctionSignature {
parameters: parameters.iter().map(|p| p.1.clone()).collect(),
Expand All @@ -409,16 +409,24 @@ impl Parser<'_> {
})
}

fn build_parameter_list(&self, parameter_list_node: &Node) -> DiagnosticResult<Vec<(Symbol, Type)>> {
fn build_parameter_list(&self, parameter_list_node: &Node) -> DiagnosticResult<Vec<(Symbol, Type, VariableKind)>> {
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,
))
}

Expand Down
Loading