1   // Copyright 2013 Bill Campbell, Swami Iyer and Bahar Akbal-Delibas
2   
3   package jminusminus;
4   
5   import static jminusminus.CLConstants.*;
6   
7   /**
8    * The AST node for an int literal.
9    */
10  
11  class JLiteralInt extends JExpression {
12  
13      /** String representation of the int. */
14      private String text;
15  
16      /**
17       * Construct an AST node for an int literal given its line number and string
18       * representation.
19       * 
20       * @param line
21       *            line in which the literal occurs in the source file.
22       * @param text
23       *            string representation of the literal.
24       */
25  
26      public JLiteralInt(int line, String text) {
27          super(line);
28          this.text = text;
29      }
30  
31      /**
32       * Analyzing an int literal is trivial.
33       * 
34       * @param context
35       *            context in which names are resolved (ignored here).
36       * @return the analyzed (and possibly rewritten) AST subtree.
37       */
38  
39      public JExpression analyze(Context context) {
40          type = Type.INT;
41          return this;
42      }
43  
44      /**
45       * Generating code for an int literal means generating code to push it onto
46       * the stack.
47       * 
48       * @param output
49       *            the code emitter (basically an abstraction for producing the
50       *            .class file).
51       */
52  
53      public void codegen(CLEmitter output) {
54          int i = Integer.parseInt(text);
55          switch (i) {
56          case 0:
57              output.addNoArgInstruction(ICONST_0);
58              break;
59          case 1:
60              output.addNoArgInstruction(ICONST_1);
61              break;
62          case 2:
63              output.addNoArgInstruction(ICONST_2);
64              break;
65          case 3:
66              output.addNoArgInstruction(ICONST_3);
67              break;
68          case 4:
69              output.addNoArgInstruction(ICONST_4);
70              break;
71          case 5:
72              output.addNoArgInstruction(ICONST_5);
73              break;
74          default:
75              if (i >= 6 && i <= 127) {
76                  output.addOneArgInstruction(BIPUSH, i);
77              } else if (i >= 128 && i <= 32767) {
78                  output.addOneArgInstruction(SIPUSH, i);
79              } else {
80                  output.addLDCInstruction(i);
81              }
82          }
83      }
84  
85      /**
86       * @inheritDoc
87       */
88  
89      public void writeToStdOut(PrettyPrinter p) {
90          p.printf("<JLiteralInt line=\"%d\" type=\"%s\" " + "value=\"%s\"/>\n",
91                  line(), ((type == null) ? "" : type.toString()), text);
92      }
93  
94  }
95