Browse Source

Implement If command

Lucas de Souza 6 years ago
parent
commit
4e7d4f196c
4 changed files with 40 additions and 4 deletions
  1. 1 1
      grammar/pt-br/ivprog.g4
  2. 8 0
      js/ast/commands/if.js
  3. 2 1
      js/ast/commands/index.js
  4. 29 2
      js/ast/ivprogParser.js

+ 1 - 1
grammar/pt-br/ivprog.g4

@@ -1,11 +1,11 @@
 lexer grammar ivprog;
-// BEGIN i18n Lexical rules
 
 @lexer::members{
   //Translate to fit your language
   ivprog.MAIN_FUNCTION_NAME = "inicio";
 }
 
+// BEGIN i18n Lexical rules
 RK_PROGRAM
   : 'programa'
   ;

+ 8 - 0
js/ast/commands/if.js

@@ -0,0 +1,8 @@
+export class If {
+
+  constructor (condition, ifTrue, ifFalse) {
+    this.condition = condition;
+    this.ifTrue = ifTrue;
+    this.ifFalse = ifFalse;
+  }
+}

+ 2 - 1
js/ast/commands/index.js

@@ -6,7 +6,8 @@ import { ArrayDeclaration } from './arrayDeclaration';
 import { While } from './while';
 import { For } from './for';
 import { Function } from './function';
+import { If } from './if';
 
 export {
-  Break, Return, Assign, Declaration, ArrayDeclaration, While, For, Function
+  Break, Return, Assign, Declaration, ArrayDeclaration, While, For, Function, If
 };

+ 29 - 2
js/ast/ivprogParser.js

@@ -377,7 +377,7 @@ export class IVProgParser {
     }
     this.consumeNewLines();
     const commandsBlock = this.parseCommandBlock();
-    return {returnType: returnType, id: functionID, formalParams: formalParams, block: commandsBlock};
+    return new Commands.Function(functionID, returnType, formalParams, commandsBlock);
   }
 
   /*
@@ -490,7 +490,7 @@ export class IVProgParser {
       } else if (token.type === this.lexerClass.RK_DO) {
         
       } else if (token.type === this.lexerClass.RK_IF) {
-        
+        cmd = this.parseIf();
       }
 
       if (cmd === null)
@@ -505,6 +505,33 @@ export class IVProgParser {
     return {variables: variablesDecl, commands: commands};
   }
 
+  parseIf () {
+    this.pos++;
+    this.checkOpenParenthesis();
+    this.pos++;
+    this.consumeNewLines();
+    const logicalExpression = this.parseExpressionOR();
+    this.consumeNewLines();
+    this.checkCloseParenthesis();
+    this.pos++;
+    this.consumeNewLines();
+    const cmdBlocks = this.parseCommandBlock(IVProgParser.COMMAND);
+
+    const maybeElse = this.getToken();
+    if(maybeElse.type === this.lexerClass.RK_ELSE) {
+      this.pos++;
+      this.consumeNewLines();
+      let elseBlock = null;
+      if(this.checkOpenCurly(true)) {
+        elseBlock = this.parseCommandBlock(IVProgParser.COMMAND);
+      } else {
+        elseBlock = this.parseIf();
+      }
+      return new Commands.If(logicalExpression, cmdBlocks, elseBlock);
+    }
+    return new Commands.If(logicalExpression, cmdBlocks, null);
+  }
+
   parseFor () {
     this.pos++;
     this.checkOpenParenthesis();