SlideShare a Scribd company logo
1 of 3
Download to read offline
Universidad Tecnológica Centroamericana
        Ingeniería en Sistemas Computacionales
        Compiladores I
        Prof. Egdares Futch H.

                       CUP - Ejemplo complejo de uso, incluyendo JFlex y AST
Operator.java                             Pam.jlex
                                          %%
// Operator is an auxiliary class         %{
to define lexical token values for           private void echo () { System . out . print (yytext ()); }
// operators.
                                               private java_cup . runtime . Symbol token (int token_class,
class Operator {                                   Object token_value) {
                                                 return new java_cup . runtime . Symbol (token_class, yychar,
  // adding operators                              yychar + yylength (), token_value);
  public final static Integer PLUS             }
= new Integer ('+');                           private java_cup . runtime . Symbol token (int token_class) {
  public final static Integer MINUS              return new java_cup . runtime . Symbol (token_class, yychar,
= new Integer ('-');                               yychar + yylength (), null);
                                               }
  // multiplying operators                %}
  public final static Integer TIMES
= new Integer ('*');                      %function nextToken
  public final static Integer SLASH       %type     java_cup . runtime . Symbol
= new Integer ('/');                      %char
                                          %eofval{
  // relational operators                   { return token (Symbol . EOF); }
  public final static int   LT   =   0;   %eofval}
  public final static int   LE   =   1;
  public final static int   GT   =   2;   d = [0-9]
  public final static int   GE   =   3;   l = [A-Za-z]
  public final static int   EQ   =   4;
  public final static int   NE   =   5;   %%
                                          [ tn]        {    echo   ();   }
  // I/O operators                        ";"             {    echo   ();   return   token   (Symbol   .   SEMICOLON); }
  public final static Integer READ        ","             {    echo   ();   return   token   (Symbol   .   COMMA); }
= new Integer (10);                       "."             {    echo   ();   return   token   (Symbol   .   DOT); }
  public final static Integer WRITE       "<"             {    echo   ();   return   token   (Symbol   .   RELOP, new Integer
= new Integer (11);                       (Operator . LT));    }
}                                         "<="            {    echo   (); return token (Symbol . RELOP, new Integer
                                          (Operator . LE));    }
                                          ">"             {    echo   (); return token (Symbol . RELOP, new Integer
                                          (Operator . GT));    }
                                          ">="            {    echo   (); return token (Symbol . RELOP, new Integer
                                          (Operator . GE));    }
                                          "="             {    echo   (); return token (Symbol . RELOP, new Integer
                                          (Operator . EQ));    }
                                          "<>"            {    echo   (); return token (Symbol . RELOP, new Integer
                                          (Operator . NE));    }
                                          "("             {    echo   (); return token (Symbol . LEFTPAREN); }
                                          ")"             {    echo   (); return token (Symbol . RIGHTPAREN); }
                                          "+"             {    echo   (); return token (Symbol . ADDOP, Operator .
                                          PLUS); }
                                          "-"             {    echo (); return token (Symbol . ADDOP,              Operator .
                                          MINUS); }
                                          "*"             {    echo (); return token (Symbol . MULTOP, Operator .
                                          TIMES); }
                                          "/"             {    echo (); return token (Symbol . MULTOP, Operator .
                                          SLASH); }
                                          ":="            {    echo   ();   return   token   (Symbol   .   ASSIGN); }
                                          do              {    echo   ();   return   token   (Symbol   .   DO); }
                                          else            {    echo   ();   return   token   (Symbol   .   ELSE); }
                                          end             {    echo   ();   return   token   (Symbol   .   END); }
                                          fi              {    echo   ();   return   token   (Symbol   .   FI); }
                                          if              {    echo   ();   return   token   (Symbol   .   IF); }
                                          read            {    echo   ();   return   token   (Symbol   .   IO, Operator . READ); }
                                          then            {    echo   ();   return   token   (Symbol   .   THEN); }
                                          to              {    echo   ();   return   token   (Symbol   .   TO); }
                                          while           {    echo   ();   return   token   (Symbol   .   WHILE); }
                                          write           {    echo   ();   return   token   (Symbol   .   IO, Operator . WRITE); }
                                          {d}+            {    echo   ();   return   token   (Symbol   .   INTEGER, new Integer
                                          (yytext ())); }
                                          {l}({l}|{d})*   {    echo (); return token (Symbol . ID, yytext ()); }
// SyntaxTree.java                      parser code {:
                                          Yylex lexer;
// SyntaxTree is a class to
represent a node of a ternary             // Error handling function.
syntax tree.
                                          public void report_fatal_error (String message, Object info) {
class SyntaxTree {                          done_parsing ();
                                            System . out . println (message);
  private   String node;                    System . exit (1);
  private   SyntaxTree left;              }
  private   SyntaxTree middle;
  private   SyntaxTree right;             // This constructor assumes that the parser is named PamParser.

  // constructor functions                public PamParser (Yylex l) {
                                            this ();
  public SyntaxTree (String                 lexer = l;
node_value, SyntaxTree left_tree,         }
      SyntaxTree middle_tree,
SyntaxTree right_tree) {                :};
    node   = new String
(node_value);                           action code {:
    left   = left_tree;
    middle = middle_tree;                 java.util.Dictionary dict = new java.util.Hashtable();
    right = right_tree;
  }                                       Integer get(String id) {
                                                return((Integer)dict.get(id.intern()));
  public SyntaxTree () {                  }
    this ("", null, null, null);          void put(String id, int v) {
    node = null;                                dict.put(id.intern(), new Integer(v));
  }                                       }

  public SyntaxTree (String             :};
node_value) {
    this (node_value, null, null,       scan with {: return lexer . nextToken (); :};
null);
  }                                     terminal Integer INTEGER, RELOP, ADDOP, MULTOP, IO;
                                        terminal String ID;
  // selector functions                 terminal SEMICOLON, LEFTPAREN, RIGHTPAREN, COMMA, DOT, ASSIGN,
                                          DO, ELSE, END, FI, IF, THEN, TO, WHILE;
  public String root ()          {
return node; }                          non terminal SyntaxTree program, series, statement, else_option, id,
  public SyntaxTree left ()      {      id_list,
return left; }                            comparison, expression, term, factor;
  public SyntaxTree middle ()    {
return middle; }                        start with program;
  public SyntaxTree right ()     {
return right; }                         program ::= series:ser DOT {: RESULT = ser; :};

  // print prints the tree in           series ::= statement:st {: RESULT = st; :}
Cambridge Polish prefix notation.           | series:ser SEMICOLON statement:st {: RESULT = new SyntaxTree (";",
                                        ser, st); :};
  public void print () {
    System . out . println   ("");      statement ::= IO:io id_list:il
    System . out . println   ("Syntax           {: if (io == Operator . READ)
Tree");                                              RESULT = new SyntaxTree ("read", il);
    System . out . println   ("------              else
-----");                                             RESULT = new SyntaxTree ("write", il); :}
    System . out . println   ("");          | id:var ASSIGN expression:exp {: RESULT = new SyntaxTree (":=", var,
    printTree ();                       exp); :}
    System . out . println   ("");          | IF comparison:comp THEN series:then_ser else_option:else_ser FI
  }                                             {: RESULT = new SyntaxTree ("if", comp, then_ser, else_ser); :}
                                            | TO expression:exp DO series:ser END
                                                {: RESULT = new SyntaxTree ("to", exp, ser); :}
                                            | WHILE comparison:comp DO series:ser END
                                                {: RESULT = new SyntaxTree ("while", comp, ser); :}
                                            ;

                                        id ::= ID:id {: RESULT = new SyntaxTree ("id", new SyntaxTree (id)); :};

                                        id_list ::= id:i {: RESULT = i; :}
                                            | id_list:il COMMA id:i {: RESULT = new SyntaxTree (",", il, i); :};

                                        else_option ::= ELSE series:ser {: RESULT = ser; :}
                                            | {: RESULT = null; :};

                                        comparison ::= expression:exp1 RELOP:relop expression:exp2
                                                {: switch (relop . intValue ()) {
class Pam {                                        case Operator   . LT : RESULT = new SyntaxTree ("<",   exp1,
                                      exp2); break;
  public static void main (String                  case Operator   . LE : RESULT = new SyntaxTree ("<=", exp1,
args []) {                            exp2); break;
    PamParser parser;                              case Operator   . GT : RESULT = new SyntaxTree (">",   exp1,
    SyntaxTree syntax_tree;           exp2); break;
                                                   case Operator   . GE : RESULT = new SyntaxTree (">=", exp1,
    System . out . println ("Source   exp2); break;
Program");                                         case Operator   . EQ : RESULT = new SyntaxTree ("=",   exp1,
    System . out . println ("------   exp2); break;
--------");                                        case Operator   . NE : RESULT = new SyntaxTree ("<>", exp1,
    System . out . println ("");      exp2); break; } :};

    parser = new PamParser (new       expression ::= expression:exp ADDOP:addop term:t
Yylex (System . in));                         {: if (addop == Operator . PLUS)
    try {                                          RESULT = new SyntaxTree ("+", exp, t);
      syntax_tree = (SyntaxTree)                 else
parser . parse () . value;                         RESULT = new SyntaxTree ("-", exp, t); :}
      syntax_tree . print ();             | term:t {: RESULT = t; :};
      System . out . println ("");
      System . out . println          term ::= term:t MULTOP:multop factor:f
("Parse successful");                         {: if (multop == Operator . TIMES)
    }                                              RESULT = new SyntaxTree ("*", t, f);
    catch (Throwable e) {                        else
      e . printStackTrace ();                      RESULT = new SyntaxTree ("/", t, f); :}
      System . out . println (e);         | factor:f {: RESULT = f; :};
    }
  }                                   factor ::= LEFTPAREN expression:exp RIGHTPAREN {: RESULT = exp; :}
                                          | INTEGER:n
}                                             {: RESULT = new SyntaxTree ("integer", new SyntaxTree (n . toString
                                      ())); :}
                                          | id:i {: put(id, e.intValue()); RESULT = i; :};

More Related Content

What's hot

Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesGanesh Samarthyam
 
How Functions Work
How Functions WorkHow Functions Work
How Functions WorkSaumil Shah
 
Java if and else
Java if and elseJava if and else
Java if and elsepratik8897
 
C# for-java-developers
C# for-java-developersC# for-java-developers
C# for-java-developersDhaval Dalal
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and UtilitiesPramod Kumar
 
Swift Programming
Swift ProgrammingSwift Programming
Swift ProgrammingCodemotion
 
35787646 system-software-lab-manual
35787646 system-software-lab-manual35787646 system-software-lab-manual
35787646 system-software-lab-manualNaveen Kumar
 
Preprocessor directives in c language
Preprocessor directives in c languagePreprocessor directives in c language
Preprocessor directives in c languagetanmaymodi4
 
Kotlin으로 안드로이드 개발하기
Kotlin으로 안드로이드 개발하기Kotlin으로 안드로이드 개발하기
Kotlin으로 안드로이드 개발하기Taehwan kwon
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio Zoppi
 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasGanesh Samarthyam
 

What's hot (20)

PHP7 is coming
PHP7 is comingPHP7 is coming
PHP7 is coming
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
C++ programming
C++ programmingC++ programming
C++ programming
 
How Functions Work
How Functions WorkHow Functions Work
How Functions Work
 
Java if and else
Java if and elseJava if and else
Java if and else
 
C# for-java-developers
C# for-java-developersC# for-java-developers
C# for-java-developers
 
Python Session - 4
Python Session - 4Python Session - 4
Python Session - 4
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
What's new in Swift 3
What's new in Swift 3What's new in Swift 3
What's new in Swift 3
 
Log4 J
Log4 JLog4 J
Log4 J
 
Swift Programming
Swift ProgrammingSwift Programming
Swift Programming
 
35787646 system-software-lab-manual
35787646 system-software-lab-manual35787646 system-software-lab-manual
35787646 system-software-lab-manual
 
Preprocessor directives in c language
Preprocessor directives in c languagePreprocessor directives in c language
Preprocessor directives in c language
 
Kotlin으로 안드로이드 개발하기
Kotlin으로 안드로이드 개발하기Kotlin으로 안드로이드 개발하기
Kotlin으로 안드로이드 개발하기
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrency
 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting Lambdas
 

Viewers also liked

Raving fans hofstra 11 30-10
Raving fans hofstra 11 30-10Raving fans hofstra 11 30-10
Raving fans hofstra 11 30-10John Doyle
 
Bethany Home What's New (June 2013)
Bethany Home What's New (June 2013)Bethany Home What's New (June 2013)
Bethany Home What's New (June 2013)Sarah Halstead
 
Anunturi De Pomina
Anunturi De PominaAnunturi De Pomina
Anunturi De Pominanbmro
 
Orange Israel iPhone startAPP contest winners at MoMoTLV
Orange Israel iPhone startAPP contest winners at MoMoTLVOrange Israel iPhone startAPP contest winners at MoMoTLV
Orange Israel iPhone startAPP contest winners at MoMoTLVMobileMonday Tel-Aviv
 
Pluto Project Greg And Victor 1
Pluto Project Greg And Victor 1Pluto Project Greg And Victor 1
Pluto Project Greg And Victor 1Gregorio
 
Talk at 2012 Notre Dame Collab Computing Lab workshop
Talk at 2012 Notre Dame Collab Computing Lab workshopTalk at 2012 Notre Dame Collab Computing Lab workshop
Talk at 2012 Notre Dame Collab Computing Lab workshopc.titus.brown
 
Tutor Inservice (Health Literacy), May 2009
Tutor Inservice (Health Literacy), May 2009Tutor Inservice (Health Literacy), May 2009
Tutor Inservice (Health Literacy), May 2009Sarah Halstead
 
Kansen zien kansen benutten okw woerden
Kansen zien kansen benutten okw woerdenKansen zien kansen benutten okw woerden
Kansen zien kansen benutten okw woerdenPiet van Vugt
 
The song of the birds
The song of the birdsThe song of the birds
The song of the birdsDaniel Chua
 
Growth Hacking with SEO
Growth Hacking with SEOGrowth Hacking with SEO
Growth Hacking with SEOAlex Rascanu
 
Intellisoft ipad iphone Info March13
Intellisoft ipad iphone Info March13Intellisoft ipad iphone Info March13
Intellisoft ipad iphone Info March13Sham Yemul
 
Katalog pos promotions
Katalog pos promotionsKatalog pos promotions
Katalog pos promotionsHanum Sujana
 
2013 talk at TGAC, November 4
2013 talk at TGAC, November 42013 talk at TGAC, November 4
2013 talk at TGAC, November 4c.titus.brown
 
用寧靜心擁抱世界
用寧靜心擁抱世界用寧靜心擁抱世界
用寧靜心擁抱世界tina59520
 
Enlightenment
EnlightenmentEnlightenment
EnlightenmentGregorio
 

Viewers also liked (20)

h-ubu : CDI in JavaScript
h-ubu : CDI in JavaScripth-ubu : CDI in JavaScript
h-ubu : CDI in JavaScript
 
Raving fans hofstra 11 30-10
Raving fans hofstra 11 30-10Raving fans hofstra 11 30-10
Raving fans hofstra 11 30-10
 
Bethany Home What's New (June 2013)
Bethany Home What's New (June 2013)Bethany Home What's New (June 2013)
Bethany Home What's New (June 2013)
 
2013 alumni-webinar
2013 alumni-webinar2013 alumni-webinar
2013 alumni-webinar
 
Anunturi De Pomina
Anunturi De PominaAnunturi De Pomina
Anunturi De Pomina
 
Orange Israel iPhone startAPP contest winners at MoMoTLV
Orange Israel iPhone startAPP contest winners at MoMoTLVOrange Israel iPhone startAPP contest winners at MoMoTLV
Orange Israel iPhone startAPP contest winners at MoMoTLV
 
Vizerra 2010
Vizerra 2010Vizerra 2010
Vizerra 2010
 
Pluto Project Greg And Victor 1
Pluto Project Greg And Victor 1Pluto Project Greg And Victor 1
Pluto Project Greg And Victor 1
 
Talk at 2012 Notre Dame Collab Computing Lab workshop
Talk at 2012 Notre Dame Collab Computing Lab workshopTalk at 2012 Notre Dame Collab Computing Lab workshop
Talk at 2012 Notre Dame Collab Computing Lab workshop
 
PROCESS elementary
PROCESS elementaryPROCESS elementary
PROCESS elementary
 
Future Developments + Regulations
Future Developments + RegulationsFuture Developments + Regulations
Future Developments + Regulations
 
Tutor Inservice (Health Literacy), May 2009
Tutor Inservice (Health Literacy), May 2009Tutor Inservice (Health Literacy), May 2009
Tutor Inservice (Health Literacy), May 2009
 
Kansen zien kansen benutten okw woerden
Kansen zien kansen benutten okw woerdenKansen zien kansen benutten okw woerden
Kansen zien kansen benutten okw woerden
 
The song of the birds
The song of the birdsThe song of the birds
The song of the birds
 
Growth Hacking with SEO
Growth Hacking with SEOGrowth Hacking with SEO
Growth Hacking with SEO
 
Intellisoft ipad iphone Info March13
Intellisoft ipad iphone Info March13Intellisoft ipad iphone Info March13
Intellisoft ipad iphone Info March13
 
Katalog pos promotions
Katalog pos promotionsKatalog pos promotions
Katalog pos promotions
 
2013 talk at TGAC, November 4
2013 talk at TGAC, November 42013 talk at TGAC, November 4
2013 talk at TGAC, November 4
 
用寧靜心擁抱世界
用寧靜心擁抱世界用寧靜心擁抱世界
用寧靜心擁抱世界
 
Enlightenment
EnlightenmentEnlightenment
Enlightenment
 

Similar to Ejemplo completo de integración JLex y CUP

java write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdfjava write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdfarjuntelecom26
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
Java Programming Below are the lexer token and shank file.pdf
Java Programming Below are the lexer token and shank file.pdfJava Programming Below are the lexer token and shank file.pdf
Java Programming Below are the lexer token and shank file.pdfabdulkadar1977
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 
Java Programming Below are the lexerjava tokenjava and .pdf
Java Programming Below are the lexerjava tokenjava and .pdfJava Programming Below are the lexerjava tokenjava and .pdf
Java Programming Below are the lexerjava tokenjava and .pdfadinathassociates
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
Durable functions
Durable functionsDurable functions
Durable functions명신 김
 
Java Programming Below are the lexer token and shank file.pdf
Java Programming Below are the lexer token and shank file.pdfJava Programming Below are the lexer token and shank file.pdf
Java Programming Below are the lexer token and shank file.pdfadinathassociates
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
More on Lex
More on LexMore on Lex
More on LexTech_MX
 
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docxjava compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docxpriestmanmable
 
Expression trees in c#
Expression trees in c#Expression trees in c#
Expression trees in c#Oleksii Holub
 
Ast transformations
Ast transformationsAst transformations
Ast transformationsHamletDRC
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016Manoj Kumar
 
JavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingJavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingHenri Tremblay
 
C++ code, please help! RESPOND W COMPLETED CODE PLEASE, am using V.pdf
C++ code, please help! RESPOND W COMPLETED CODE PLEASE,  am using V.pdfC++ code, please help! RESPOND W COMPLETED CODE PLEASE,  am using V.pdf
C++ code, please help! RESPOND W COMPLETED CODE PLEASE, am using V.pdfrahulfancycorner21
 
Introduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineMovel
 
Expression trees in c#, Алексей Голубь (Svitla Systems)
Expression trees in c#, Алексей Голубь (Svitla Systems)Expression trees in c#, Алексей Голубь (Svitla Systems)
Expression trees in c#, Алексей Голубь (Svitla Systems)Alina Vilk
 

Similar to Ejemplo completo de integración JLex y CUP (20)

java write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdfjava write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdf
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
Java Programming Below are the lexer token and shank file.pdf
Java Programming Below are the lexer token and shank file.pdfJava Programming Below are the lexer token and shank file.pdf
Java Programming Below are the lexer token and shank file.pdf
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Java Programming Below are the lexerjava tokenjava and .pdf
Java Programming Below are the lexerjava tokenjava and .pdfJava Programming Below are the lexerjava tokenjava and .pdf
Java Programming Below are the lexerjava tokenjava and .pdf
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Durable functions
Durable functionsDurable functions
Durable functions
 
Java Programming Below are the lexer token and shank file.pdf
Java Programming Below are the lexer token and shank file.pdfJava Programming Below are the lexer token and shank file.pdf
Java Programming Below are the lexer token and shank file.pdf
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
More on Lex
More on LexMore on Lex
More on Lex
 
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docxjava compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
 
Expression trees in c#
Expression trees in c#Expression trees in c#
Expression trees in c#
 
Rcpp11
Rcpp11Rcpp11
Rcpp11
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
Interpreter Case Study - Design Patterns
Interpreter Case Study - Design PatternsInterpreter Case Study - Design Patterns
Interpreter Case Study - Design Patterns
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
JavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingJavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programming
 
C++ code, please help! RESPOND W COMPLETED CODE PLEASE, am using V.pdf
C++ code, please help! RESPOND W COMPLETED CODE PLEASE,  am using V.pdfC++ code, please help! RESPOND W COMPLETED CODE PLEASE,  am using V.pdf
C++ code, please help! RESPOND W COMPLETED CODE PLEASE, am using V.pdf
 
Introduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy Cresine
 
Expression trees in c#, Алексей Голубь (Svitla Systems)
Expression trees in c#, Алексей Голубь (Svitla Systems)Expression trees in c#, Алексей Голубь (Svitla Systems)
Expression trees in c#, Алексей Голубь (Svitla Systems)
 

More from Egdares Futch H.

FIT 2018 - Malware Avanzado y Respuesta a Incidentes
FIT 2018 - Malware Avanzado y Respuesta a IncidentesFIT 2018 - Malware Avanzado y Respuesta a Incidentes
FIT 2018 - Malware Avanzado y Respuesta a IncidentesEgdares Futch H.
 
FIT 2020 - Artificial Life
FIT 2020 - Artificial LifeFIT 2020 - Artificial Life
FIT 2020 - Artificial LifeEgdares Futch H.
 
Blockchain - Una mirada técnica y aplicaciones
Blockchain - Una mirada técnica y aplicacionesBlockchain - Una mirada técnica y aplicaciones
Blockchain - Una mirada técnica y aplicacionesEgdares Futch H.
 
Digital forensics SIFT como herramienta
Digital forensics  SIFT como herramientaDigital forensics  SIFT como herramienta
Digital forensics SIFT como herramientaEgdares Futch H.
 
Machine Learning: ¿Caminos? A donde vamos, no necesitamos caminos
Machine Learning: ¿Caminos? A donde vamos, no necesitamos caminosMachine Learning: ¿Caminos? A donde vamos, no necesitamos caminos
Machine Learning: ¿Caminos? A donde vamos, no necesitamos caminosEgdares Futch H.
 
Herramientas de Pen Testing de redes y aplicaciones web
Herramientas de Pen Testing de redes y aplicaciones webHerramientas de Pen Testing de redes y aplicaciones web
Herramientas de Pen Testing de redes y aplicaciones webEgdares Futch H.
 
El "Internet de Todo" (IoT)
El "Internet de Todo" (IoT)El "Internet de Todo" (IoT)
El "Internet de Todo" (IoT)Egdares Futch H.
 
El “Internet de Todo” (IoT) y lo que lo hace posible
El “Internet de Todo” (IoT) y lo que lo hace posible El “Internet de Todo” (IoT) y lo que lo hace posible
El “Internet de Todo” (IoT) y lo que lo hace posible Egdares Futch H.
 
MGTI: Tendencias de Tecnología 2015 - Campus Tegucigalpa
MGTI: Tendencias de Tecnología 2015 - Campus TegucigalpaMGTI: Tendencias de Tecnología 2015 - Campus Tegucigalpa
MGTI: Tendencias de Tecnología 2015 - Campus TegucigalpaEgdares Futch H.
 
MGTI: Tendencias de Tecnología 2015 y su aplicación en el país Campus La Ceiba
MGTI: Tendencias de Tecnología 2015 y su aplicación en el país Campus La CeibaMGTI: Tendencias de Tecnología 2015 y su aplicación en el país Campus La Ceiba
MGTI: Tendencias de Tecnología 2015 y su aplicación en el país Campus La CeibaEgdares Futch H.
 
Introducción a la Teoría de Juegos con aplicación a las Ciencias de la Comput...
Introducción a la Teoría de Juegos con aplicación a las Ciencias de la Comput...Introducción a la Teoría de Juegos con aplicación a las Ciencias de la Comput...
Introducción a la Teoría de Juegos con aplicación a las Ciencias de la Comput...Egdares Futch H.
 
The Hour of Code - Presentación Diciembre 2014
The Hour of Code - Presentación Diciembre 2014The Hour of Code - Presentación Diciembre 2014
The Hour of Code - Presentación Diciembre 2014Egdares Futch H.
 
Criptografía para las masas
Criptografía para las masasCriptografía para las masas
Criptografía para las masasEgdares Futch H.
 
Más sobre el Algoritmo de Peterson
Más sobre el Algoritmo de PetersonMás sobre el Algoritmo de Peterson
Más sobre el Algoritmo de PetersonEgdares Futch H.
 
Análisis de ataques a un sistema de correo electrónico por medio de mensajes ...
Análisis de ataques a un sistema de correo electrónico por medio de mensajes ...Análisis de ataques a un sistema de correo electrónico por medio de mensajes ...
Análisis de ataques a un sistema de correo electrónico por medio de mensajes ...Egdares Futch H.
 
Apuntes de clase Sistemas Operativos: Administración de Memoria
Apuntes de clase Sistemas Operativos: Administración de MemoriaApuntes de clase Sistemas Operativos: Administración de Memoria
Apuntes de clase Sistemas Operativos: Administración de MemoriaEgdares Futch H.
 

More from Egdares Futch H. (20)

FIT 2018 - Malware Avanzado y Respuesta a Incidentes
FIT 2018 - Malware Avanzado y Respuesta a IncidentesFIT 2018 - Malware Avanzado y Respuesta a Incidentes
FIT 2018 - Malware Avanzado y Respuesta a Incidentes
 
FIT 2020 - Artificial Life
FIT 2020 - Artificial LifeFIT 2020 - Artificial Life
FIT 2020 - Artificial Life
 
Blockchain - Una mirada técnica y aplicaciones
Blockchain - Una mirada técnica y aplicacionesBlockchain - Una mirada técnica y aplicaciones
Blockchain - Una mirada técnica y aplicaciones
 
Digital forensics SIFT como herramienta
Digital forensics  SIFT como herramientaDigital forensics  SIFT como herramienta
Digital forensics SIFT como herramienta
 
Machine Learning: ¿Caminos? A donde vamos, no necesitamos caminos
Machine Learning: ¿Caminos? A donde vamos, no necesitamos caminosMachine Learning: ¿Caminos? A donde vamos, no necesitamos caminos
Machine Learning: ¿Caminos? A donde vamos, no necesitamos caminos
 
Herramientas de Pen Testing de redes y aplicaciones web
Herramientas de Pen Testing de redes y aplicaciones webHerramientas de Pen Testing de redes y aplicaciones web
Herramientas de Pen Testing de redes y aplicaciones web
 
El "Internet de Todo" (IoT)
El "Internet de Todo" (IoT)El "Internet de Todo" (IoT)
El "Internet de Todo" (IoT)
 
BPMS vs. workflow
BPMS vs. workflowBPMS vs. workflow
BPMS vs. workflow
 
El “Internet de Todo” (IoT) y lo que lo hace posible
El “Internet de Todo” (IoT) y lo que lo hace posible El “Internet de Todo” (IoT) y lo que lo hace posible
El “Internet de Todo” (IoT) y lo que lo hace posible
 
MGTI: Tendencias de Tecnología 2015 - Campus Tegucigalpa
MGTI: Tendencias de Tecnología 2015 - Campus TegucigalpaMGTI: Tendencias de Tecnología 2015 - Campus Tegucigalpa
MGTI: Tendencias de Tecnología 2015 - Campus Tegucigalpa
 
MGTI: Tendencias de Tecnología 2015 y su aplicación en el país Campus La Ceiba
MGTI: Tendencias de Tecnología 2015 y su aplicación en el país Campus La CeibaMGTI: Tendencias de Tecnología 2015 y su aplicación en el país Campus La Ceiba
MGTI: Tendencias de Tecnología 2015 y su aplicación en el país Campus La Ceiba
 
Introducción a la Teoría de Juegos con aplicación a las Ciencias de la Comput...
Introducción a la Teoría de Juegos con aplicación a las Ciencias de la Comput...Introducción a la Teoría de Juegos con aplicación a las Ciencias de la Comput...
Introducción a la Teoría de Juegos con aplicación a las Ciencias de la Comput...
 
The Hour of Code - Presentación Diciembre 2014
The Hour of Code - Presentación Diciembre 2014The Hour of Code - Presentación Diciembre 2014
The Hour of Code - Presentación Diciembre 2014
 
Unitec virtualización
Unitec   virtualizaciónUnitec   virtualización
Unitec virtualización
 
Criptografía para las masas
Criptografía para las masasCriptografía para las masas
Criptografía para las masas
 
Más sobre el Algoritmo de Peterson
Más sobre el Algoritmo de PetersonMás sobre el Algoritmo de Peterson
Más sobre el Algoritmo de Peterson
 
Análisis de ataques a un sistema de correo electrónico por medio de mensajes ...
Análisis de ataques a un sistema de correo electrónico por medio de mensajes ...Análisis de ataques a un sistema de correo electrónico por medio de mensajes ...
Análisis de ataques a un sistema de correo electrónico por medio de mensajes ...
 
Apuntes de clase Sistemas Operativos: Administración de Memoria
Apuntes de clase Sistemas Operativos: Administración de MemoriaApuntes de clase Sistemas Operativos: Administración de Memoria
Apuntes de clase Sistemas Operativos: Administración de Memoria
 
Memoria virtual
Memoria virtualMemoria virtual
Memoria virtual
 
Deadlocks
DeadlocksDeadlocks
Deadlocks
 

Ejemplo completo de integración JLex y CUP

  • 1. Universidad Tecnológica Centroamericana Ingeniería en Sistemas Computacionales Compiladores I Prof. Egdares Futch H. CUP - Ejemplo complejo de uso, incluyendo JFlex y AST Operator.java Pam.jlex %% // Operator is an auxiliary class %{ to define lexical token values for private void echo () { System . out . print (yytext ()); } // operators. private java_cup . runtime . Symbol token (int token_class, class Operator { Object token_value) { return new java_cup . runtime . Symbol (token_class, yychar, // adding operators yychar + yylength (), token_value); public final static Integer PLUS } = new Integer ('+'); private java_cup . runtime . Symbol token (int token_class) { public final static Integer MINUS return new java_cup . runtime . Symbol (token_class, yychar, = new Integer ('-'); yychar + yylength (), null); } // multiplying operators %} public final static Integer TIMES = new Integer ('*'); %function nextToken public final static Integer SLASH %type java_cup . runtime . Symbol = new Integer ('/'); %char %eofval{ // relational operators { return token (Symbol . EOF); } public final static int LT = 0; %eofval} public final static int LE = 1; public final static int GT = 2; d = [0-9] public final static int GE = 3; l = [A-Za-z] public final static int EQ = 4; public final static int NE = 5; %% [ tn] { echo (); } // I/O operators ";" { echo (); return token (Symbol . SEMICOLON); } public final static Integer READ "," { echo (); return token (Symbol . COMMA); } = new Integer (10); "." { echo (); return token (Symbol . DOT); } public final static Integer WRITE "<" { echo (); return token (Symbol . RELOP, new Integer = new Integer (11); (Operator . LT)); } } "<=" { echo (); return token (Symbol . RELOP, new Integer (Operator . LE)); } ">" { echo (); return token (Symbol . RELOP, new Integer (Operator . GT)); } ">=" { echo (); return token (Symbol . RELOP, new Integer (Operator . GE)); } "=" { echo (); return token (Symbol . RELOP, new Integer (Operator . EQ)); } "<>" { echo (); return token (Symbol . RELOP, new Integer (Operator . NE)); } "(" { echo (); return token (Symbol . LEFTPAREN); } ")" { echo (); return token (Symbol . RIGHTPAREN); } "+" { echo (); return token (Symbol . ADDOP, Operator . PLUS); } "-" { echo (); return token (Symbol . ADDOP, Operator . MINUS); } "*" { echo (); return token (Symbol . MULTOP, Operator . TIMES); } "/" { echo (); return token (Symbol . MULTOP, Operator . SLASH); } ":=" { echo (); return token (Symbol . ASSIGN); } do { echo (); return token (Symbol . DO); } else { echo (); return token (Symbol . ELSE); } end { echo (); return token (Symbol . END); } fi { echo (); return token (Symbol . FI); } if { echo (); return token (Symbol . IF); } read { echo (); return token (Symbol . IO, Operator . READ); } then { echo (); return token (Symbol . THEN); } to { echo (); return token (Symbol . TO); } while { echo (); return token (Symbol . WHILE); } write { echo (); return token (Symbol . IO, Operator . WRITE); } {d}+ { echo (); return token (Symbol . INTEGER, new Integer (yytext ())); } {l}({l}|{d})* { echo (); return token (Symbol . ID, yytext ()); }
  • 2. // SyntaxTree.java parser code {: Yylex lexer; // SyntaxTree is a class to represent a node of a ternary // Error handling function. syntax tree. public void report_fatal_error (String message, Object info) { class SyntaxTree { done_parsing (); System . out . println (message); private String node; System . exit (1); private SyntaxTree left; } private SyntaxTree middle; private SyntaxTree right; // This constructor assumes that the parser is named PamParser. // constructor functions public PamParser (Yylex l) { this (); public SyntaxTree (String lexer = l; node_value, SyntaxTree left_tree, } SyntaxTree middle_tree, SyntaxTree right_tree) { :}; node = new String (node_value); action code {: left = left_tree; middle = middle_tree; java.util.Dictionary dict = new java.util.Hashtable(); right = right_tree; } Integer get(String id) { return((Integer)dict.get(id.intern())); public SyntaxTree () { } this ("", null, null, null); void put(String id, int v) { node = null; dict.put(id.intern(), new Integer(v)); } } public SyntaxTree (String :}; node_value) { this (node_value, null, null, scan with {: return lexer . nextToken (); :}; null); } terminal Integer INTEGER, RELOP, ADDOP, MULTOP, IO; terminal String ID; // selector functions terminal SEMICOLON, LEFTPAREN, RIGHTPAREN, COMMA, DOT, ASSIGN, DO, ELSE, END, FI, IF, THEN, TO, WHILE; public String root () { return node; } non terminal SyntaxTree program, series, statement, else_option, id, public SyntaxTree left () { id_list, return left; } comparison, expression, term, factor; public SyntaxTree middle () { return middle; } start with program; public SyntaxTree right () { return right; } program ::= series:ser DOT {: RESULT = ser; :}; // print prints the tree in series ::= statement:st {: RESULT = st; :} Cambridge Polish prefix notation. | series:ser SEMICOLON statement:st {: RESULT = new SyntaxTree (";", ser, st); :}; public void print () { System . out . println (""); statement ::= IO:io id_list:il System . out . println ("Syntax {: if (io == Operator . READ) Tree"); RESULT = new SyntaxTree ("read", il); System . out . println ("------ else -----"); RESULT = new SyntaxTree ("write", il); :} System . out . println (""); | id:var ASSIGN expression:exp {: RESULT = new SyntaxTree (":=", var, printTree (); exp); :} System . out . println (""); | IF comparison:comp THEN series:then_ser else_option:else_ser FI } {: RESULT = new SyntaxTree ("if", comp, then_ser, else_ser); :} | TO expression:exp DO series:ser END {: RESULT = new SyntaxTree ("to", exp, ser); :} | WHILE comparison:comp DO series:ser END {: RESULT = new SyntaxTree ("while", comp, ser); :} ; id ::= ID:id {: RESULT = new SyntaxTree ("id", new SyntaxTree (id)); :}; id_list ::= id:i {: RESULT = i; :} | id_list:il COMMA id:i {: RESULT = new SyntaxTree (",", il, i); :}; else_option ::= ELSE series:ser {: RESULT = ser; :} | {: RESULT = null; :}; comparison ::= expression:exp1 RELOP:relop expression:exp2 {: switch (relop . intValue ()) {
  • 3. class Pam { case Operator . LT : RESULT = new SyntaxTree ("<", exp1, exp2); break; public static void main (String case Operator . LE : RESULT = new SyntaxTree ("<=", exp1, args []) { exp2); break; PamParser parser; case Operator . GT : RESULT = new SyntaxTree (">", exp1, SyntaxTree syntax_tree; exp2); break; case Operator . GE : RESULT = new SyntaxTree (">=", exp1, System . out . println ("Source exp2); break; Program"); case Operator . EQ : RESULT = new SyntaxTree ("=", exp1, System . out . println ("------ exp2); break; --------"); case Operator . NE : RESULT = new SyntaxTree ("<>", exp1, System . out . println (""); exp2); break; } :}; parser = new PamParser (new expression ::= expression:exp ADDOP:addop term:t Yylex (System . in)); {: if (addop == Operator . PLUS) try { RESULT = new SyntaxTree ("+", exp, t); syntax_tree = (SyntaxTree) else parser . parse () . value; RESULT = new SyntaxTree ("-", exp, t); :} syntax_tree . print (); | term:t {: RESULT = t; :}; System . out . println (""); System . out . println term ::= term:t MULTOP:multop factor:f ("Parse successful"); {: if (multop == Operator . TIMES) } RESULT = new SyntaxTree ("*", t, f); catch (Throwable e) { else e . printStackTrace (); RESULT = new SyntaxTree ("/", t, f); :} System . out . println (e); | factor:f {: RESULT = f; :}; } } factor ::= LEFTPAREN expression:exp RIGHTPAREN {: RESULT = exp; :} | INTEGER:n } {: RESULT = new SyntaxTree ("integer", new SyntaxTree (n . toString ())); :} | id:i {: put(id, e.intValue()); RESULT = i; :};