/src/org/ooc/backend/cdirty/LiteralWriter.java

http://github.com/nddrylliog/ooc · Java · 50 lines · 39 code · 10 blank · 1 comment · 1 complexity · 2357afe814d0c9fb53902475939894a2 MD5 · raw file

  1. package org.ooc.backend.cdirty;
  2. import java.io.IOException;
  3. import java.math.BigInteger;
  4. import org.ooc.frontend.model.FloatLiteral;
  5. import org.ooc.frontend.model.IntLiteral;
  6. import org.ooc.frontend.model.StringLiteral;
  7. import org.ubi.SourceReader;
  8. public class LiteralWriter {
  9. private static BigInteger INT_MAX = new BigInteger("2").pow(32);
  10. public static void writeFloat(FloatLiteral floatLiteral, CGenerator cgen) throws IOException {
  11. cgen.current.app(Double.toString(floatLiteral.getValue()));
  12. }
  13. public static void writeString(StringLiteral stringLiteral, CGenerator cgen) throws IOException {
  14. cgen.current.app('"');
  15. SourceReader.spelled(stringLiteral.getValue(), cgen.current);
  16. cgen.current.app('"');
  17. }
  18. public static void writeInt(IntLiteral numberLiteral, CGenerator cgen) throws IOException {
  19. switch(numberLiteral.getFormat()) {
  20. case HEX:
  21. case BIN: // C has no binary literals, write it as hex
  22. cgen.current.app("0x");
  23. cgen.current.app(numberLiteral.getValue().toString(16));
  24. break;
  25. case OCT:
  26. cgen.current.app('0');
  27. cgen.current.app(numberLiteral.getValue().toString(8));
  28. break;
  29. default:
  30. cgen.current.app(numberLiteral.getValue().toString());
  31. }
  32. // if it's greater than an int's max, then it's a Long
  33. if(numberLiteral.getValue().compareTo(INT_MAX) > -1) {
  34. cgen.current.app("L");
  35. }
  36. }
  37. public static void writeNull(CGenerator cgen) throws IOException {
  38. cgen.current.app("NULL");
  39. }
  40. }