Skip to content

C: string literals containing ??!, ??/ etc. are rewritten by trigraphs under -std=c11 ("what??!" prints what|) #107

Description

@matt-edmondson

What's wrong

LanguageGeneratorBase.EscapeString (Coder/Languages/LanguageGeneratorBase.cs ~784) escapes only \, ", \n, \r and \t. In ISO C (C89 through C17) and C++ before C++17, trigraphs are replaced inside string literals during translation phase 1:

Trigraph Becomes
??! |
??= #
??' ^
??/ \

The ??/ case is the worst: it becomes a backslash that escapes the next character, which can swallow the closing quote and break compilation.

Repro (reproduced with MSTest, compiled with gcc)

ReturnStatement(new LiteralExpression<string>("what??!")) in a string-returning function, generated with CGenerator:

  • Generated: return "what??!";
  • Compiled with gcc -std=c11, the same flag the repo's own CGeneratedSourceCompilesTests uses: the program prints what|.
  • Expected: what??!

Strict standard modes enable trigraphs, so any user-supplied text containing ?? followed by one of the characters in the table above (e.g. "Really??!" or "path??/x") silently changes value or fails to compile.

Suggested fix

For the C and C++ generators, escape ? as \?. That escape is valid in every C and C++ standard and has no effect where trigraphs are disabled. At minimum, escape the second ? of every ??. Keep the change out of the shared escaping for languages where \? is not a valid escape (e.g. Go, Rust and JS, where it is an error or changes meaning). Add a C compile-and-run test with "what??!" and "a??/b".

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingreadyFully specified; implement as written

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions