io_utils.carbon 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. library "io_utils";
  5. import Core library "io";
  6. // If non-zero, this is the most recently read character plus 2.
  7. // The +2 is necessary to distinguish the case of no unread character
  8. // from the case of unreading an EOF.
  9. var unread_char: i32 = 0;
  10. fn ReadChar() -> i32 {
  11. if (unread_char != 0) {
  12. var result: i32 = unread_char - 2;
  13. unread_char = 0;
  14. return result;
  15. }
  16. return Core.ReadChar();
  17. }
  18. fn UnreadChar(c: i32) {
  19. // TODO: assert(unread_char == 0);
  20. unread_char = c + 2;
  21. }
  22. fn ReadInt(p: i32*) -> bool {
  23. var read_any_digits: bool = false;
  24. *p = 0;
  25. while (true) {
  26. var c: i32 = ReadChar();
  27. if (c < 0x30 or c > 0x39) {
  28. UnreadChar(c);
  29. break;
  30. }
  31. // TODO: Check for overflow.
  32. *p *= 10;
  33. *p += c - 0x30;
  34. read_any_digits = true;
  35. }
  36. return read_any_digits;
  37. }
  38. fn PeekChar() -> i32 {
  39. var next: i32 = ReadChar();
  40. UnreadChar(next);
  41. return next;
  42. }
  43. fn ConsumeChar(c: i32) -> bool {
  44. var next: i32 = ReadChar();
  45. if (next != c) {
  46. UnreadChar(next);
  47. return false;
  48. }
  49. return true;
  50. }
  51. fn SkipSpaces() -> bool {
  52. var skipped_any_spaces: bool = false;
  53. while (ConsumeChar(0x20)) {
  54. skipped_any_spaces = true;
  55. }
  56. return skipped_any_spaces;
  57. }
  58. fn SkipNewline() -> bool {
  59. // Optional carriage return.
  60. ConsumeChar(0x0D);
  61. // Newline.
  62. // TODO: Unread the CR if it was present?
  63. return ConsumeChar(0x0A);
  64. }