mi.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. /** Minimal GDB/MI output parser (plain Node, no dependencies).
  2. *
  3. * Handles result records (`TOKEN^done,...`), out-of-band records
  4. * (`*stopped,...`, `=notify,...`), stream records (`~`, `&`, `@`),
  5. * the `(gdb)` prompt and anything else (treated as inferior output).
  6. * Tolerant by design: unparseable lines surface as output, never throw.
  7. */
  8. export type MIFields = { [name: string]: MIValue };
  9. export type MIValue = string | MIFields | MIValue[];
  10. export interface MIRecord {
  11. token: string;
  12. /** `^` result, `*` exec-async, `+` status-async, `=` notify, `~` console, `&` log, `@` target. */
  13. marker: string;
  14. /** Class after the marker (`done`, `error`, `stopped`, ...) or '' for streams. */
  15. cls: string;
  16. /** Raw remainder after `marker + cls` (for streams: the payload). */
  17. rest: string;
  18. fields: MIFields;
  19. }
  20. export function classifyLine(line: string): MIRecord | { prompt: true } | { output: string } {
  21. const trimmed = line.replace(/\r$/, '');
  22. if (trimmed === '(gdb)') return { prompt: true };
  23. const m = /^([0-9]*)([\^*+=~&@])(.*)$/.exec(trimmed);
  24. if (!m) return { output: line };
  25. const [, token, marker, rest] = m;
  26. if (marker === '~' || marker === '&') {
  27. return { token, marker, cls: '', rest, fields: { text: unescapeMIString(rest.trim()) } };
  28. }
  29. if (marker === '@') {
  30. return { token, marker, cls: '', rest, fields: { text: rest } };
  31. }
  32. const comma = rest.indexOf(',');
  33. const cls = comma < 0 ? rest : rest.slice(0, comma);
  34. const body = comma < 0 ? '' : rest.slice(comma + 1);
  35. let fields: MIFields = {};
  36. try {
  37. fields = body ? parseResultList(body) : {};
  38. } catch {
  39. fields = {};
  40. }
  41. return { token, marker, cls, rest, fields };
  42. }
  43. function isRecord(r: unknown): r is MIRecord {
  44. return !!r && typeof r === 'object' && 'marker' in (r as object);
  45. }
  46. export { isRecord };
  47. /** Parse `name=value,name=value,...` at top level. */
  48. export function parseResultList(s: string): MIFields {
  49. const out: MIFields = {};
  50. const p = new Cursor(s);
  51. p.skipSpaces();
  52. while (!p.eof()) {
  53. const name = p.readName();
  54. if (name === null || !p.eat('=')) break;
  55. out[name] = p.readValue();
  56. p.skipSpaces();
  57. if (!p.eat(',')) break;
  58. p.skipSpaces();
  59. }
  60. return out;
  61. }
  62. class Cursor {
  63. pos = 0;
  64. constructor(public s: string) {}
  65. eof(): boolean {
  66. return this.pos >= this.s.length;
  67. }
  68. skipSpaces(): void {
  69. while (this.s[this.pos] === ' ') this.pos++;
  70. }
  71. eat(c: string): boolean {
  72. if (this.s[this.pos] === c) { this.pos++; return true; }
  73. return false;
  74. }
  75. readName(): string | null {
  76. const m = /^[A-Za-z_][A-Za-z0-9_\-]*/.exec(this.s.slice(this.pos));
  77. if (!m) return null;
  78. this.pos += m[0].length;
  79. return m[0];
  80. }
  81. readValue(): MIValue {
  82. this.skipSpaces();
  83. const c = this.s[this.pos];
  84. if (c === '"') return this.readCString();
  85. if (c === '{') return this.readTuple();
  86. if (c === '[') return this.readList();
  87. return this.readConst();
  88. }
  89. readCString(): string {
  90. // Opening quote already peeked.
  91. this.pos++;
  92. let out = '';
  93. while (this.pos < this.s.length) {
  94. const c = this.s[this.pos];
  95. if (c === '"') { this.pos++; return out; }
  96. if (c === '\\') {
  97. const esc = this.s.slice(this.pos, this.pos + 4);
  98. const decoded = decodeEscape(esc);
  99. out += decoded.text;
  100. this.pos += decoded.length;
  101. continue;
  102. }
  103. out += c;
  104. this.pos++;
  105. }
  106. return out;
  107. }
  108. readTuple(): MIFields {
  109. this.pos++; // {
  110. const out: MIFields = {};
  111. this.skipSpaces();
  112. if (this.eat('}')) return out;
  113. for (;;) {
  114. this.skipSpaces();
  115. const name = this.readName();
  116. if (name === null || !this.eat('=')) break;
  117. out[name] = this.readValue();
  118. this.skipSpaces();
  119. if (this.eat(',')) continue;
  120. break;
  121. }
  122. this.eat('}');
  123. return out;
  124. }
  125. readList(): MIValue[] {
  126. this.pos++; // [
  127. const out: MIValue[] = [];
  128. this.skipSpaces();
  129. if (this.eat(']')) return out;
  130. for (;;) {
  131. this.skipSpaces();
  132. out.push(this.readListItem());
  133. this.skipSpaces();
  134. if (this.eat(',')) continue;
  135. break;
  136. }
  137. this.eat(']');
  138. return out;
  139. }
  140. readListItem(): MIValue {
  141. // Items are values, but result-shaped `name=value` items occur as well.
  142. const save = this.pos;
  143. const name = this.readName();
  144. if (name !== null && this.eat('=')) {
  145. const v = this.readValue();
  146. const o: MIFields = {};
  147. o[name] = v;
  148. return o;
  149. }
  150. this.pos = save;
  151. return this.readValue();
  152. }
  153. readConst(): string {
  154. const start = this.pos;
  155. while (this.pos < this.s.length && ![',', '}', ']'].includes(this.s[this.pos])) this.pos++;
  156. return this.s.slice(start, this.pos);
  157. }
  158. }
  159. function decodeEscape(esc: string): { text: string; length: number } {
  160. const c = esc[1];
  161. switch (c) {
  162. case 'n': return { text: '\n', length: 2 };
  163. case 'r': return { text: '\r', length: 2 };
  164. case 't': return { text: '\t', length: 2 };
  165. case 'a': return { text: '\x07', length: 2 };
  166. case 'b': return { text: '\b', length: 2 };
  167. case 'f': return { text: '\f', length: 2 };
  168. case 'v': return { text: '\v', length: 2 };
  169. case 'e': return { text: '\x1b', length: 2 };
  170. case '\\': return { text: '\\', length: 2 };
  171. case '"': return { text: '"', length: 2 };
  172. case "'": return { text: "'", length: 2 };
  173. case '0': case '1': case '2': case '3':
  174. case '4': case '5': case '6': case '7': {
  175. const m = /^\\([0-7]{1,3})/.exec(esc);
  176. if (m) return { text: String.fromCharCode(parseInt(m[1], 8)), length: m[0].length };
  177. return { text: c, length: 2 };
  178. }
  179. default: return { text: c ?? '', length: 2 };
  180. }
  181. }
  182. /** Unescape the inside of an MI `"..."` stream payload. */
  183. export function unescapeMIString(quoted: string): string {
  184. const inner = quoted.startsWith('"') && quoted.endsWith('"') && quoted.length >= 2
  185. ? quoted.slice(1, -1)
  186. : quoted;
  187. let out = '';
  188. let i = 0;
  189. while (i < inner.length) {
  190. if (inner[i] === '\\') {
  191. const decoded = decodeEscape(inner.slice(i, i + 4));
  192. out += decoded.text;
  193. i += decoded.length;
  194. } else {
  195. out += inner[i];
  196. i++;
  197. }
  198. }
  199. return out;
  200. }
  201. // ---- Convenience accessors (all total: undefined on shape mismatch) ----
  202. export function asString(v: MIValue | undefined): string | undefined {
  203. return typeof v === 'string' ? v : undefined;
  204. }
  205. export function asFields(v: MIValue | undefined): MIFields | undefined {
  206. return v !== undefined && typeof v === 'object' && !Array.isArray(v) ? v as MIFields : undefined;
  207. }
  208. export function asList(v: MIValue | undefined): MIValue[] {
  209. return Array.isArray(v) ? v : [];
  210. }
  211. export function fieldString(fields: MIFields, name: string): string | undefined {
  212. return asString(fields[name]);
  213. }