ref: 1804f4d6850b475b6cbd3e065b7e7c8562b4afc2
parent: 61d8cb619913f5b54df22c02c97b999e592ef70f
author: Roberto E. Vargas Caballero <k0ga@shike2.com>
date: Sun Oct 31 11:24:49 EDT 2021
cc2: Print strings with C escape sequences Qbe and assemblers usually need strings in a form that they can parse them easilly. For this reason the function pprint() is added as a way to let targets to format strings in the C way.
--- a/src/cmd/cc/cc2/cc2.h
+++ b/src/cmd/cc/cc2/cc2.h
@@ -229,6 +229,7 @@
extern Node *label2node(Node *np, Symbol *sym);
extern Node *constnode(Node *np, TUINT n, Type *tp);
extern Symbol *newlabel(void);
+extern void pprint(char *s);
/* node.c */
#define SETCUR 1
--- a/src/cmd/cc/cc2/code.c
+++ b/src/cmd/cc/cc2/code.c
@@ -1,7 +1,10 @@
+#include <ctype.h>
+#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <scc/scc.h>
+
#include "cc2.h"
Inst *pc, *prog;
@@ -54,6 +57,61 @@
default:
abort();
}
+}
+
+void
+pprint(char *s)
+{
+ int c;
+ char *t;
+
+ putchar('"');
+ while ((c = *s++) != '\0') {
+ switch (c) {
+ case '\n':
+ t = "\\n";
+ goto print_str;
+ case '\v':
+ t = "\\v";
+ goto print_str;
+ case '\b':
+ t = "\\b";
+ goto print_str;
+ case '\t':
+ t = "\\t";
+ goto print_str;
+ case '\a':
+ t = "\\a";
+ goto print_str;
+ case '\f':
+ t = "\\f";
+ goto print_str;
+ case '\r':
+ t = "\\r";
+ goto print_str;
+ case '"':
+ t = "\\\"";
+ goto print_str;
+ case '\'':
+ t = "\\'";
+ goto print_str;
+ case '\?':
+ t = "\\\?";
+ goto print_str;
+ case '\\':
+ putchar('\\');
+ default:
+ if (!isprint(c))
+ printf("\\x%x", c);
+ else
+ putchar(c);
+ break;
+ print_str:
+ fputs(t, stdout);
+ break;
+ }
+ }
+ putchar('"');
}
Symbol *
--- a/src/cmd/cc/cc2/target/amd64-sysv/code.c
+++ b/src/cmd/cc/cc2/target/amd64-sysv/code.c
@@ -79,7 +79,7 @@
switch (np->op) {
case OSTRING:
- printf("\"%s\"", np->u.s);
+ pprint(np->u.s);
free(np->u.s);
np->u.s = NULL;
break;
--- a/src/cmd/cc/cc2/target/i386-sysv/code.c
+++ b/src/cmd/cc/cc2/target/i386-sysv/code.c
@@ -79,7 +79,7 @@
switch (np->op) {
case OSTRING:
- printf("\"%s\"", np->u.s);
+ pprint(np->u.s);
free(np->u.s);
np->u.s = NULL;
break;
--- a/src/cmd/cc/cc2/target/qbe/code.c
+++ b/src/cmd/cc/cc2/target/qbe/code.c
@@ -232,7 +232,7 @@
switch (np->op) {
case OSTRING:
- printf("\"%s\"", np->u.s);
+ pprint(np->u.s);
free(np->u.s);
np->u.s = NULL;
break;
--- a/src/cmd/cc/cc2/target/z80-scc/code.c
+++ b/src/cmd/cc/cc2/target/z80-scc/code.c
@@ -105,7 +105,7 @@
switch (np->op) {
case OSTRING:
- printf("\"%s\"", np->u.s);
+ pprint(np->u.s);
free(np->u.s);
np->u.s = NULL;
break;