Bläddra i källkod

destructuring

kj863257 3 år sedan
förälder
incheckning
b1c470b84e
2 ändrade filer med 33 tillägg och 3 borttagningar
  1. 28 1
      src/scripts/parsing/ast.js
  2. 5 2
      src/scripts/parsing/parser.js

+ 28 - 1
src/scripts/parsing/ast.js

@@ -467,6 +467,32 @@ class VarDefine extends Node {
 	}
 }
 
+class VarDestructuringDefine extends VarDefine {
+	constructor(span, tokens, expression, defineType) {
+		super(span, null, expression, defineType)
+		this.expression = expression
+		this.tokens = tokens
+		this.defineType = defineType !== 'var' && defineType !== 'const' && defineType !== 'let' && defineType
+	}
+
+	expressions() {
+		return this.expression == null ? [] : [this.expression]
+	}
+
+	async getJavaType(env) {
+		let type = 'java.lang.Object'
+		if (this.defineType) {
+			type = env[this.defineType] || type
+		} else if (this.expression) {
+			type = await this.expression.getJavaType(env);
+		}
+		for (const token of this.tokens) {
+			env[token.getVarName()] = type
+		}
+		return type
+	}
+}
+
 class TernaryOperation extends Node {
 	constructor(condition, trueExpression, falseExpression) {
 		super(new Span(condition.getSpan(), falseExpression.getSpan()));
@@ -718,6 +744,7 @@ export {
 	WhileStatement,
 	Import,
 	VarDefine,
+	VarDestructuringDefine,
 	TernaryOperation,
 	BinaryOperation,
 	Spread,
@@ -732,4 +759,4 @@ export {
 	ClassConverter,
 	LanguageExpression,
 	Throw
-}
+}

+ 5 - 2
src/scripts/parsing/parser.js

@@ -32,6 +32,7 @@ import {
 	TryStatement,
 	UnaryOperation,
 	VarDefine,
+	VarDestructuringDefine,
 	VariableAccess,
 	WhileStatement,
 	WholeLiteral,
@@ -349,8 +350,10 @@ export class Parser {
 		let isMapAccess;
 		if ( (isMapAccess = this.stream.match(TokenType.LeftCurly, false)) || this.stream.match(TokenType.LeftBracket, false) ) {
 			this.stream.expect(TokenType.LeftCurly, TokenType.LeftBracket);
+			let tokens = [];
 			do {
-				this.stream.expect(TokenType.Identifier);
+				let token = this.stream.expect(TokenType.Identifier);
+				tokens.push(token);
 			} while (this.stream.match(TokenType.Comma, true));
 			if (isMapAccess) {
 				this.stream.match(TokenType.RightCurly);
@@ -358,7 +361,7 @@ export class Parser {
 				this.stream.match(TokenType.RightBracket);
 			}
 			this.stream.match(TokenType.Assignment, true);
-			return new VarDefine(new Span(opening, this.stream.getPrev().getSpan()), 'destructuring', this.parseExpression(), opening.getText())
+			return new VarDestructuringDefine(new Span(opening, this.stream.getPrev().getSpan()), tokens, this.parseExpression(), opening.getText())
 		}
 		let token = this.stream.expect(TokenType.Identifier);
 		this.checkKeyword(token.getSpan());