Skip to content

Commit

Permalink
feat(compiler): addition and subtraction assignment operators impleme…
Browse files Browse the repository at this point in the history
…ntation (#4018)

Fixes #4005

Implemented a `+=` and `-=` operators, as a new type of `StmtKind::Assignment`.
- [Type Check](https://github.com/winglang/wing/compare/main...wzslr321:feature/compiler/add-and-sub-assignment-ops?expand=1#diff-fe246e49d57ca72d41851e8dacc3d2ccee194881769083dd8ca508058cff13b4R1829) allows only for numbers to be used on both sides of the operator.



## Checklist

- [x] Title matches [Winglang's style guide](https://www.winglang.io/contributing/start-here/pull_requests#how-are-pull-request-titles-formatted)
- [x] Description explains motivation and solution
- [x] Tests added (always)
- [x] Docs updated (only required for features)
- [ ] Added `pr/e2e-full` label if this feature requires end-to-end testing

*By submitting this pull request, I confirm that my contribution is made under the terms of the [Wing Cloud Contribution License](https://github.com/winglang/wing/blob/main/CONTRIBUTION_LICENSE.md)*.
  • Loading branch information
wzslr321 authored Sep 5, 2023
1 parent bed2384 commit f1446e7
Show file tree
Hide file tree
Showing 14 changed files with 118 additions and 25 deletions.
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
5 changes: 4 additions & 1 deletion libs/tree-sitter-wing/grammar.js
Original file line number Diff line number Diff line change
Expand Up @@ -152,14 +152,17 @@ module.exports = grammar({
throw_statement: ($) =>
seq("throw", optional(field("expression", $.expression)), $._semicolon),

assignment_operator: ($) => choice("=", "+=", "-="),

variable_assignment_statement: ($) =>
seq(
field("name", alias($.reference, $.lvalue)),
"=",
field("operator", $.assignment_operator),
field("value", $.expression),
$._semicolon
),


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

reassignable: ($) => "var",
Expand Down
19 changes: 19 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 @@ -84,6 +88,21 @@ let var y = "hello";
(variable_assignment_statement
name: (lvalue
(reference_identifier))
operator: (assignment_operator)
value: (number))
(variable_definition_statement
reassignable: (reassignable)
name: (identifier)
value: (number))
(variable_assignment_statement
name: (lvalue
(reference_identifier))
operator: (assignment_operator)
value: (number))
(variable_assignment_statement
name: (lvalue
(reference_identifier))
operator: (assignment_operator)
value: (number))
(variable_definition_statement
reassignable: (reassignable)
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,8 +438,16 @@ 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" => {
let kind = match self.node_text(&statement_node.child_by_field_name("operator").unwrap()) {
"=" => AssignmentKind::Assign,
"+=" => AssignmentKind::AssignIncr,
"-=" => AssignmentKind::AssignDecr,
other => return self.report_unimplemented_grammar(other, "assignment operator", statement_node),
};

self.build_assignment_statement(statement_node, phase, kind)?
}
"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);
}
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

0 comments on commit f1446e7

Please sign in to comment.