JLiteralString.java |
1 // Copyright 2013 Bill Campbell, Swami Iyer and Bahar Akbal-Delibas 2 3 package jminusminus; 4 5 /** 6 * The AST node for a string literal. 7 */ 8 9 class JLiteralString extends JExpression { 10 11 /** Representation of the string. */ 12 private String text; 13 14 /** 15 * Construct an AST node for a string literal given its line number and 16 * string representation. 17 * 18 * @param line 19 * line in which the literal occurs in the source file. 20 * @param text 21 * representation of the literal. 22 */ 23 24 public JLiteralString(int line, String text) { 25 super(line); 26 this.text = text; 27 } 28 29 /** 30 * Analyzing a String literal is trivial. 31 * 32 * @param context 33 * context in which names are resolved (ignored here). 34 * @return the analyzed (and possibly rewritten) AST subtree. 35 */ 36 37 public JExpression analyze(Context context) { 38 type = Type.STRING; 39 return this; 40 } 41 42 /** 43 * Generating code for a string literal means generating code to push it 44 * onto the stack. 45 * 46 * @param output 47 * the code emitter (basically an abstraction for producing the 48 * .class file). 49 */ 50 51 public void codegen(CLEmitter output) { 52 // Unescape the escaped escapes 53 String s = Util.unescape(text); 54 55 // The string representation is padded (by hand-written 56 // and JavaCC scanner) with double quotes, so we substring 57 String literal = s.substring(1, s.length() - 1); 58 output.addLDCInstruction(literal); 59 } 60 61 /** 62 * @inheritDoc 63 */ 64 65 public void writeToStdOut(PrettyPrinter p) { 66 p.printf("<JLiteralString line=\"%d\" type=\"%s\" " 67 + "value=\"%s\"/>\n", line(), ((type == null) ? "" : type 68 .toString()), Util.escapeSpecialXMLChars(text)); 69 } 70 71 } 72