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(compiler): addition and subtraction assignment operators implementation #4018

Merged
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
8e591ee
add and subtract assignment operators implementation
wzslr321 Aug 30, 2023
db95724
add forgotten subtract assignment to expressions.txt
wzslr321 Aug 30, 2023
b0b826b
add subtract assignment test to examples
wzslr321 Aug 30, 2023
5460ec2
modify test in order to pnpm build to pass; requires change of behavior
wzslr321 Aug 30, 2023
d6636ec
change incr/decr assignment type from binary operator to assignment s…
wzslr321 Sep 2, 2023
0bbadee
Merge branch 'main' into feature/compiler/add-and-sub-assignment-ops
monadabot Sep 2, 2023
b41f764
chore: self mutation (e2e-1of2.diff)
monadabot Sep 2, 2023
489a0f1
valid assignment grammar;incorect logic fails tests
wzslr321 Sep 2, 2023
badee4f
Merge branch 'feature/compiler/add-and-sub-assignment-ops' of https:/…
wzslr321 Sep 2, 2023
252458a
Merge branch 'main' into feature/compiler/add-and-sub-assignment-ops
monadabot Sep 2, 2023
0616dc6
chore: self mutation (build.diff)
monadabot Sep 2, 2023
d3e8fdb
fix typo in tests
wzslr321 Sep 2, 2023
a1cb096
Merge branch 'feature/compiler/add-and-sub-assignment-ops' of https:/…
wzslr321 Sep 2, 2023
189a97b
Update docs/docs/03-language-reference.md
wzslr321 Sep 4, 2023
78a95b3
address PR comments - improve type_check
wzslr321 Sep 4, 2023
6c47990
Merge branch 'feature/compiler/add-and-sub-assignment-ops' of https:/…
wzslr321 Sep 4, 2023
05368f1
Merge branch 'main' into feature/compiler/add-and-sub-assignment-ops
monadabot Sep 4, 2023
7d70879
chore: self mutation (build.diff)
monadabot Sep 4, 2023
241d99f
remove duplication from grammar by modyfing it and adjusting parser
wzslr321 Sep 5, 2023
92edbf2
Merge branch 'feature/compiler/add-and-sub-assignment-ops' of https:/…
wzslr321 Sep 5, 2023
8937c34
Merge branch 'main' into feature/compiler/add-and-sub-assignment-ops
monadabot Sep 5, 2023
9eca4b0
chore: self mutation (build.diff)
monadabot Sep 5, 2023
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
8 changes: 8 additions & 0 deletions docs/docs/03-language-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -657,6 +657,14 @@ for item in [1,2,3] {
}
```

To modify a numeric value, it is also possible to use `+=` and `-=` operators.
```TS
// wing
let var x = 0;
x += 5; // x == 5
x -= 10; // x == -5
```

Re-assignment to class fields is allowed if field is marked with `var`.
Examples in the class section below.

Expand Down
3 changes: 2 additions & 1 deletion examples/tests/valid/expressions_binary_operators.w
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ assert(xyznf == -5);
let xyznfj = 501.9 \ (-99.1 - 0.91);
assert(xyznfj == -5);
let xynfj = -501.9 \ (-99.1 - 0.91);
assert(xynfj == 5);
assert(xynfj == 5);

7 changes: 7 additions & 0 deletions examples/tests/valid/reassignment.w
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@ assert(x == 5);
x = x + 1;
assert(x == 6);

let var z = 1;
z += 2;
assert(z == 3);

z -= 1;
assert(z == 2);

class R {
var f: num;
f1: num;
Expand Down
18 changes: 18 additions & 0 deletions libs/tree-sitter-wing/grammar.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ module.exports = grammar({
$.expression_statement,
$.variable_definition_statement,
$.variable_assignment_statement,
$.variable_assignment_incr_statement,
$.variable_assignment_decr_statement,
$.return_statement,
$.class_definition,
$.resource_definition,
Expand Down Expand Up @@ -160,6 +162,22 @@ module.exports = grammar({
$._semicolon
),

variable_assignment_incr_statement: ($) =>
seq(
field("name", alias($.reference, $.lvalue)),
"+=",
field("value", $.expression),
Chriscbr marked this conversation as resolved.
Show resolved Hide resolved
$._semicolon
),

variable_assignment_decr_statement: ($) =>
seq(
field("name", alias($.reference, $.lvalue)),
"-=",
field("value", $.expression),
$._semicolon
),

expression_statement: ($) => seq($.expression, $._semicolon),

reassignable: ($) => "var",
Expand Down
16 changes: 16 additions & 0 deletions libs/tree-sitter-wing/test/corpus/statements/statements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@ Variable assignment
let x: num = 1;
x = 2;

let var z = 1;
z += 2;
z -= 1;

let var y = "hello";

--------------------------------------------------------------------------------
Expand All @@ -85,6 +89,18 @@ let var y = "hello";
name: (lvalue
(reference_identifier))
value: (number))
(variable_definition_statement
reassignable: (reassignable)
name: (identifier)
value: (number))
(variable_assignment_incr_statement
name: (lvalue
(reference_identifier))
value: (number))
(variable_assignment_decr_statement
name: (lvalue
(reference_identifier))
value: (number))
(variable_definition_statement
reassignable: (reassignable)
name: (identifier)
Expand Down
8 changes: 8 additions & 0 deletions libs/wingc/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,13 @@ pub enum BringSource {
WingFile(Symbol),
}

#[derive(Debug)]
pub enum AssignmentKind {
Assign,
AssignIncr,
AssignDecr,
}

#[derive(Debug)]
pub enum StmtKind {
Bring {
Expand Down Expand Up @@ -469,6 +476,7 @@ pub enum StmtKind {
Throw(Expr),
Expression(Expr),
Assignment {
kind: AssignmentKind,
variable: Reference,
value: Expr,
},
Expand Down
7 changes: 4 additions & 3 deletions libs/wingc/src/closure_transform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ use indexmap::IndexMap;

use crate::{
ast::{
ArgList, CalleeKind, Class, ClassField, Expr, ExprKind, FunctionBody, FunctionDefinition, FunctionParameter,
FunctionSignature, Literal, NewExpr, Phase, Reference, Scope, Stmt, StmtKind, Symbol, TypeAnnotation,
TypeAnnotationKind, UserDefinedType,
ArgList, AssignmentKind, CalleeKind, Class, ClassField, Expr, ExprKind, FunctionBody, FunctionDefinition,
FunctionParameter, FunctionSignature, Literal, NewExpr, Phase, Reference, Scope, Stmt, StmtKind, Symbol,
TypeAnnotation, TypeAnnotationKind, UserDefinedType,
},
diagnostic::WingSpan,
fold::{self, Fold},
Expand Down Expand Up @@ -213,6 +213,7 @@ impl Fold for ClosureTransformer {
let class_init_body = vec![Stmt {
idx: 0,
kind: StmtKind::Assignment {
kind: AssignmentKind::Assign,
variable: Reference::InstanceMember {
object: Box::new(std_display_of_this),
property: Symbol::new("hidden", WingSpan::for_file(file_id)),
Expand Down
3 changes: 2 additions & 1 deletion libs/wingc/src/fold.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,8 @@ where
StmtKind::Return(value) => StmtKind::Return(value.map(|value| f.fold_expr(value))),
StmtKind::Throw(value) => StmtKind::Throw(f.fold_expr(value)),
StmtKind::Expression(expr) => StmtKind::Expression(f.fold_expr(expr)),
StmtKind::Assignment { variable, value } => StmtKind::Assignment {
StmtKind::Assignment { kind, variable, value } => StmtKind::Assignment {
kind,
variable: f.fold_reference(variable),
value: f.fold_expr(value),
},
Expand Down
26 changes: 18 additions & 8 deletions libs/wingc/src/jsify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ use std::{borrow::Borrow, cell::RefCell, cmp::Ordering, vec};

use crate::{
ast::{
ArgList, BinaryOperator, BringSource, CalleeKind, Class as AstClass, ElifLetBlock, Expr, ExprKind, FunctionBody,
FunctionDefinition, InterpolatedStringPart, Literal, NewExpr, Phase, Reference, Scope, Stmt, StmtKind, StructField,
Symbol, TypeAnnotationKind, UnaryOperator, UserDefinedType,
ArgList, AssignmentKind, BinaryOperator, BringSource, CalleeKind, Class as AstClass, ElifLetBlock, Expr, ExprKind,
FunctionBody, FunctionDefinition, InterpolatedStringPart, Literal, NewExpr, Phase, Reference, Scope, Stmt,
StmtKind, StructField, Symbol, TypeAnnotationKind, UnaryOperator, UserDefinedType,
},
comp_ctx::{CompilationContext, CompilationPhase},
dbg_panic, debug,
Expand Down Expand Up @@ -1012,11 +1012,21 @@ impl<'a> JSifier<'a> {
code
}
StmtKind::Expression(e) => CodeMaker::one_line(format!("{};", self.jsify_expression(e, ctx))),
StmtKind::Assignment { variable, value } => CodeMaker::one_line(format!(
"{} = {};",
self.jsify_reference(variable, ctx),
self.jsify_expression(value, ctx)
)),

StmtKind::Assignment { kind, variable, value } => {
let operator = match kind {
AssignmentKind::Assign => "=",
AssignmentKind::AssignIncr => "+=",
AssignmentKind::AssignDecr => "-=",
};

CodeMaker::one_line(format!(
"{} {} {};",
self.jsify_reference(variable, ctx),
operator,
self.jsify_expression(value, ctx)
))
}
StmtKind::Scope(scope) => {
let mut code = CodeMaker::default();
if !scope.statements.is_empty() {
Expand Down
27 changes: 21 additions & 6 deletions libs/wingc/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ use tree_sitter::Node;
use tree_sitter_traversal::{traverse, Order};

use crate::ast::{
ArgList, BinaryOperator, BringSource, CalleeKind, CatchBlock, Class, ClassField, ElifBlock, ElifLetBlock, Expr,
ExprKind, FunctionBody, FunctionDefinition, FunctionParameter, FunctionSignature, Interface, InterpolatedString,
InterpolatedStringPart, Literal, NewExpr, Phase, Reference, Scope, Stmt, StmtKind, StructField, Symbol,
TypeAnnotation, TypeAnnotationKind, UnaryOperator, UserDefinedType,
ArgList, AssignmentKind, BinaryOperator, BringSource, CalleeKind, CatchBlock, Class, ClassField, ElifBlock,
ElifLetBlock, Expr, ExprKind, FunctionBody, FunctionDefinition, FunctionParameter, FunctionSignature, Interface,
InterpolatedString, InterpolatedStringPart, Literal, NewExpr, Phase, Reference, Scope, Stmt, StmtKind, StructField,
Symbol, TypeAnnotation, TypeAnnotationKind, UnaryOperator, UserDefinedType,
};
use crate::comp_ctx::{CompilationContext, CompilationPhase};
use crate::diagnostic::{report_diagnostic, Diagnostic, DiagnosticResult, WingSpan};
Expand Down Expand Up @@ -438,7 +438,15 @@ impl<'s> Parser<'s> {
"import_statement" => self.build_bring_statement(statement_node)?,

"variable_definition_statement" => self.build_variable_def_statement(statement_node, phase)?,
"variable_assignment_statement" => self.build_assignment_statement(statement_node, phase)?,
"variable_assignment_statement" => {
self.build_assignment_statement(statement_node, phase, AssignmentKind::Assign)?
}
"variable_assignment_incr_statement" => {
self.build_assignment_statement(statement_node, phase, AssignmentKind::AssignIncr)?
}
"variable_assignment_decr_statement" => {
self.build_assignment_statement(statement_node, phase, AssignmentKind::AssignDecr)?
}

"expression_statement" => {
StmtKind::Expression(self.build_expression(&statement_node.named_child(0).unwrap(), phase)?)
Expand Down Expand Up @@ -631,10 +639,17 @@ impl<'s> Parser<'s> {
})
}

fn build_assignment_statement(&self, statement_node: &Node, phase: Phase) -> DiagnosticResult<StmtKind> {
fn build_assignment_statement(
&self,
statement_node: &Node,
phase: Phase,
kind: AssignmentKind,
) -> DiagnosticResult<StmtKind> {
let reference = self.build_reference(&statement_node.child_by_field_name("name").unwrap(), phase)?;

if let ExprKind::Reference(r) = reference.kind {
Ok(StmtKind::Assignment {
kind: kind,
variable: r,
value: self.build_expression(&statement_node.child_by_field_name("value").unwrap(), phase)?,
})
Expand Down
11 changes: 9 additions & 2 deletions libs/wingc/src/type_check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ pub(crate) mod jsii_importer;
pub mod lifts;
pub mod symbol_env;

use crate::ast::{self, BringSource, CalleeKind, ClassField, ExprId, FunctionDefinition, NewExpr, TypeAnnotationKind};
use crate::ast::{
self, AssignmentKind, BringSource, CalleeKind, ClassField, ExprId, FunctionDefinition, NewExpr, TypeAnnotationKind,
};
use crate::ast::{
ArgList, BinaryOperator, Class as AstClass, Expr, ExprKind, FunctionBody, FunctionParameter as AstFunctionParameter,
Interface as AstInterface, InterpolatedStringPart, Literal, Phase, Reference, Scope, Spanned, Stmt, StmtKind, Symbol,
Expand Down Expand Up @@ -3131,7 +3133,7 @@ impl<'a> TypeChecker<'a> {
StmtKind::Expression(e) => {
self.type_check_exp(e, env);
}
StmtKind::Assignment { variable, value } => {
StmtKind::Assignment { kind, variable, value } => {
let (exp_type, _) = self.type_check_exp(value, env);

// TODO: we need to verify that if this variable is defined in a parent environment (i.e.
Expand All @@ -3145,6 +3147,11 @@ impl<'a> TypeChecker<'a> {
self.spanned_error(stmt, "Variable cannot be reassigned from inflight".to_string());
}

if matches!(&kind, AssignmentKind::AssignIncr | AssignmentKind::AssignDecr) {
self.validate_type(exp_type, self.types.number(), value);
self.validate_type(var.type_, self.types.number(), variable);
}

self.validate_type(exp_type, var.type_, value);
wzslr321 marked this conversation as resolved.
Show resolved Hide resolved
}
StmtKind::Bring { source, identifier } => {
Expand Down
8 changes: 6 additions & 2 deletions libs/wingc/src/type_check/class_fields_init.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::{
ast::{Reference, Stmt, StmtKind, Symbol},
ast::{AssignmentKind, Reference, Stmt, StmtKind, Symbol},
visit::{self, Visit},
};

Expand All @@ -20,7 +20,11 @@ impl VisitClassInit {
impl Visit<'_> for VisitClassInit {
fn visit_stmt(&mut self, node: &Stmt) {
match &node.kind {
StmtKind::Assignment { variable, value: _ } => match variable {
StmtKind::Assignment {
kind: AssignmentKind::Assign,
variable,
value: _,
} => match variable {
Reference::InstanceMember {
property,
object: _,
Expand Down
6 changes: 5 additions & 1 deletion libs/wingc/src/visit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,11 @@ where
StmtKind::Expression(expr) => {
v.visit_expr(&expr);
}
StmtKind::Assignment { variable, value } => {
StmtKind::Assignment {
kind: _,
variable,
value,
} => {
v.visit_reference(variable);
v.visit_expr(value);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,11 @@ class $Root extends $stdlib.std.Resource {
{((cond) => {if (!cond) throw new Error("assertion failed: x == 5")})((((a,b) => { try { return require('assert').deepStrictEqual(a,b) === undefined; } catch { return false; } })(x,5)))};
x = (x + 1);
{((cond) => {if (!cond) throw new Error("assertion failed: x == 6")})((((a,b) => { try { return require('assert').deepStrictEqual(a,b) === undefined; } catch { return false; } })(x,6)))};
let z = 1;
z += 2;
{((cond) => {if (!cond) throw new Error("assertion failed: z == 3")})((((a,b) => { try { return require('assert').deepStrictEqual(a,b) === undefined; } catch { return false; } })(z,3)))};
z -= 1;
{((cond) => {if (!cond) throw new Error("assertion failed: z == 2")})((((a,b) => { try { return require('assert').deepStrictEqual(a,b) === undefined; } catch { return false; } })(z,2)))};
const r = new R(this,"R");
(r.inc());
{((cond) => {if (!cond) throw new Error("assertion failed: r.f == 2")})((((a,b) => { try { return require('assert').deepStrictEqual(a,b) === undefined; } catch { return false; } })(r.f,2)))};
Expand Down
Loading