From 93a7395c1928752b44f35f34d7dd633cb58a7253 Mon Sep 17 00:00:00 2001 From: Max Brunsfeld Date: Sun, 4 Nov 2018 15:25:30 -0800 Subject: [PATCH] Fix invalid dot syntax when token names contain quotes or newlines --- src/runtime/subtree.c | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/src/runtime/subtree.c b/src/runtime/subtree.c index 13af2ba2..6415a176 100644 --- a/src/runtime/subtree.c +++ b/src/runtime/subtree.c @@ -766,6 +766,18 @@ static size_t ts_subtree__write_char_to_string(char *s, size_t n, int32_t c) { return snprintf(s, n, "%d", c); } +static void ts_subtree__write_dot_string(FILE *f, const char *string) { + for (const char *c = string; *c; c++) { + if (*c == '"') { + fputs("\\\"", f); + } else if (*c == '\n') { + fputs("\\n", f); + } else { + fputc(*c, f); + } + } +} + static size_t ts_subtree__write_to_string(Subtree self, char *string, size_t limit, const TSLanguage *language, bool is_root, bool include_all, TSSymbol alias_symbol, @@ -845,10 +857,9 @@ void ts_subtree__print_dot_graph(const Subtree *self, uint32_t start_offset, TSSymbol subtree_symbol = ts_subtree_symbol(*self); TSSymbol symbol = alias_symbol ? alias_symbol : subtree_symbol; uint32_t end_offset = start_offset + ts_subtree_total_bytes(*self); - fprintf( - f, "tree_%p [label=\"%s\"", - self, ts_language_symbol_name(language, symbol) - ); + fprintf(f, "tree_%p [label=\"", self); + ts_subtree__write_dot_string(f, ts_language_symbol_name(language, symbol)); + fprintf(f, "\""); if (ts_subtree_child_count(*self) == 0) fprintf(f, ", shape=plaintext"); if (ts_subtree_extra(*self)) fprintf(f, ", fontcolor=gray");