yohhoyの日記

技術的メモをしていきたい日記

#embedディレクティブ

プログラミング言語Cの次期C2x(C23)言語仕様に追加される#embedディレクティブについて。外部ファイルをバイナリデータとしてプログラムに埋込む機能。

下記コードは、外部PNGファイル内容を生成プログラム中のuint8_t型配列として埋め込む例*1 *2。C17現在は外部ツール*3を用いたビルドステップで対応しているものが、C2x以降はC言語処理系(プリプロセッサ)のみで実現される。

// C2x
#include <stdint.h>  // uint8_t

#if __has_embed("resource/icon.png")
constexpr uint8_t icon[] = {
#embed "resource/icon.png"
};
static_assert(
  (icon[0]==137 && icon[1]=='P' && icon[2]=='N' && icon[3]=='G'
   && icon[4]==13 && icon[5]==10 && icon[6]==26 && icon[7]==10),
  "invalid PNG format");
// https://www.w3.org/TR/PNG-Structure.html
#else
#error "icon resource not found!"
#endif

// icon[] == PNG圧縮画像データ列

まとめ:

  • #emdedディレクティブ
    • 指定されたファイル(<path>"path"またはマクロ置換結果)の中身を読み取り、コンマ区切りの整数定数リストへと展開する。
    • C2x標準は下記パラメータ4種類の追加指定をサポートし、また処理系定義(implementation-defined)のパラメータ定義を許容する。
    • limit(N):展開されるバイナリデータをNバイト以下に制限する。
    • prefix(tokens):展開後リストの直前にtokensを配置する。バイナリデータ長=0の場合は何もしない。
    • suffix(tokens):展開後リストの直後にtokensを配置する。バイナリデータ長=0の場合は何もしない。
    • if_empty(tokens):バイナリデータ長=0の場合にtokensを代替配置する。それ以外は何もしない。
  • __has_embed
    • 指定ファイルの有無、空(empty)のバイナリデータを判定するプリプロセッサ式。
    • 0:指定ファイルが見つからない。
    • 1:指定ファイルが存在し、バイナリデータは空ではない。
    • 2:指定ファイルが存在し、バイナリデータは空(サイズ0)。
  • おまけ:C++標準に対してもP1967が提案されている。2022年9月現在の検討状況より、C++2c(C++26)以降での導入が想定される。

ホストプログラム中に外部ファイルに記述されたGLSLシェーダプログラムを埋め込む例(提案文書N3017より改変引用):

#define SHADER_TARGET "ches.glsl"
extern char* merp;

void init_data () {
  const char whl[] = {
#embed SHADER_TARGET \
    prefix(0xEF, 0xBB, 0xBF, ) /* UTF-8 BOM */ \
    suffix(,)
    0
  };
  // always null terminated,
  // contains BOM if not-empty
  int is_good = (sizeof(whl) == 1 && whl[0] == '\0')
    || (whl[0] == '\xEF' && whl[1] == '\xBB'
      && whl[2] == '\xBF' && whl[sizeof(whl) - 1] == '\0');
  assert(is_good);
  strcpy(merp, whl);
}
#define SHADER_TARGET "edith-impl.glsl"
extern char* null_term_shader_data;

void fill_in_data () {
  const char internal_data[] = {
#embed SHADER_TARGET  \
    suffix(, 0) \
    if_empty(0)
  };
  strcpy(null_term_shader_data, internal_data);
}

関連URL

*1:コンパイル時constexpr定数は提案文書 N3018 にてC2x導入予定。コンパイル時constexpr関数をもつC++とは異なり、C2x時点ではconstexpr定数のみが導入される。

*2:C2x仕様には(PDF)N2934が採択され、C++言語と同じ static_assert キーワードが導入される。一方で、C11からの _Static_assert は廃止予定の機能(obsolescent feature)となる。また例示コードでは利用していないが、(PDF)N2265の採択により理由文字列もC2xから省略可能となる。C++17以降の static_assert と同等。

*3:例えば https://linux.die.net/man/1/xxd などでバイナリファイルをC言語用の変数定義へと変換可能。

typeof演算子 in 標準C

プログラミング言語Cの次期仕様C2x(C23)では、式から型情報を取り出す typeof演算子(typeof operator) が追加される。

// C2x
const int x = /*...*/;
typeof(x) y;  // const int型
typeof_unqual(x) z;  // int型

int func(int);
typeof(func)* pf;  // int(*)(int)型

まとめ:

  • 2種類のtypeof演算子が追加される。
    • typeofオペランドの型情報をそのまま返す。従来からある同名のGCC拡張機能を標準化したもの。
    • typeof_unqualオペランドから型修飾(type qualifiers)を除去*1した型情報を返す。
    • C2x typeof_unqual(E)C++ std::remove_cvref_t<decltype(E)>*2
  • typeof演算子は 式(expression) または 型名(type-name) を対象とする。
    • sizeof演算子とは異なり*3、typeof演算子に式を指定する場合も括弧は必須。
  • C言語typeof != C++言語のdecltype
    • C2x typeofは型名も指定可能/C++decltypeは式のみサポート。
    • C言語には参照型(reference type)が存在しないため、オペランドの括弧有無により両者の挙動が異なる。

typeof(C) vs. decltype(C++)

C言語typeofC++言語のdecltype(→id:yohhoy:20200817)とで導出される型が異なる例:

int x;  // int

// C2x
typeof( x ) y0;  // int
typeof((x)) y1;  // int

// C++
decltype( x ) z0;  // int
decltype((x)) z1;  // int&(参照型)

C++11 decltype検討時の提案文書N1607*4でもGCC拡張機能typeofにおける参照型の扱いを取り上げ、それとは異なる動きをするキーワードとしてC++へ導入した経緯がある。

3 Design alternatives for typeof
Two main options for the semantics of a typeof operator have been discussed: either to preserve or to drop references in types.
(snip)
A reference-dropping typeof always removes top-level references. Some compiler vendors (EDG, Metrowerks, GCC) provide a typeof operator as an extension with reference-dropping semantics. This appears to be a reasonable semantics for expressing the type of variables. On the other hand, the reference-dropping semantics fails to provide a mechanism for exactly expressing the return types of generic functions, as demonstrated by Stroustrup. This implies that a reference-dropping typeof would cause problems for writers of generic libraries.
(snip)
Therefore, we propose that the operator be named decltype.

関連URL

*1:トップレベルの const, volatile, restrict(→id:yohhoy:20120223), _Atomic の4種類全てが除去される。C言語の _Atomic キーワードには、指定子 _Atomic(T) と 修飾子 _Atomic T の2種類の用法があるが、typeof_unqual は両者を区別せずに除去する。

*2:C++言語仕様には restrict 修飾子は存在しない。またC++のatomic変数はクラステンプレート std::atomic<T> として定義され、C言語のような _Atomic キーワードが存在しない。

*3:https://qiita.com/yohhoy/items/a2ab2900a2bd36c31879

*4:https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1607.pdf

reproducible/unsequenced属性

プログラミング言語Cの次期C2x(C23)言語仕様に追加される属性(→id:yohhoy:20200505reproducible, unsequencedに関するメモ。関数呼び出しに対する最適化ヒント。

// C2x
int calc(int x, int y) [[unsequenced]];

int a = /*...*/;
int b = calc(a) * 2;
/* 任意の処理 */
int c = calc(a) * 4;
// calc関数に付与されたunsequenced属性により、
// コンパイラによる下記の最適化が許可される。
// int b = calc(a) * 2;
// int c = b * 2;
// /* 任意の処理 */

まとめ:

  • 関数または関数ポインタに対して付与する属性。
  • reproducible属性=副作用を持たない(effectless)+連続呼出しは同一結果(idempotent)
  • unsequenced属性=reproducible属性+可変状態を持たない(stateless)+引数以外に依存しない(independent)
  • 関数動作セマンティクスが指定属性に反する場合は未定義動作(undefined behavior)となる。
    • Cコンパイラは関数実装が指定属性を満たすことを検査しなくてもよいが、できる限り診断メッセージを出すことが推奨される(recommended practice)。
  • GCC拡張属性__attribute__((pure))reproducibleGCC拡張属性__attribute__((const))unsequencedと概ね近似できる。
  • 注意:unsequenced属性の関数は再入可能(reentrant)や並行実行(executed concurrently)に対する安全性を直接意味しない。*1

例えば標準ヘッダ<math.h>提供の数学関数群はエラー発生時にerrnoへ値を書込む可能性があるため、一般にreproducibleunsequencedいずれでもない。実引数に対して制約条件を保証できるのであれば、プログラマの責任で同属性を付与した関数再宣言を行ってもよい。提案文書N2956よりコード例を引用。*2 *3

// C2x
#include <math.h>
#include <fenv.h>

inline double distance (double const x[static 2]) [[reproducible]] {
  #pragma FP_CONTRACT OFF
  #pragma FENV_ROUND FE_TONEAREST
  // We assert that sqrt will not be called with invalid arguments
  // and the result only depends on the argument value.
  extern typeof(sqrt) [[unsequenced]] sqrt;
  return sqrt(x[0]*x[0] + x[1]*x[1]);
}

double g (double y[static 1], double const x[static 2]) {
  // We assert that distance will not see different states of the floating
  // point environment.
  extern double distance (double const x[static 2]) [[unsequenced]];
  y[0] = distance(x);
  ...
  return distance(x); // replacement by y[0] is valid
}

C2x WD N3047 6.7.12.7/p3, p5-8より一部引用。

3 The main purpose of the function type properties and attributes defined in this clause is to provide the translator with information about the access of objects by a function such that certain properties of function calls can be deduced; the properties distinguish read operations (stateless and independent) and write operations (effectless, idempotent and reproducible) or a combination of both (unsequenced). (snip)

5 A function definition f is stateless if any definition of an object of static or thread storage duration in f or in a function that is called by f is const but not volatile qualified.
6 (snip) A function pointer value f is independent if for any object X that is observed by some call to f through an lvalue that is not based on a parameter of the call, then all accesses to X in all calls to f during the same program execution observe the same value; otherwise if the access is based on a pointer parameter, there shall be a unique such pointer parameter P such that any access to X shall be to an lvalue that is based on P. A function definition is independent if the derived function pointer value is independent.
7 A store operation to an object X that is sequenced during a function call such that both synchronize is said to be observable if X is not local to the call, if the lifetime of X ends after the call, if the stored value is different from the value observed by the call, if any, and if it is the last value written before the termination of the call. An evaluation of a function call is effectless if any store operation that is sequenced during the call is the modification of an object that synchronizes with the call; (snip)
8 An evaluation E is idempotent if a second evaluation of E can be sequenced immediately after the original one without changing the resulting value, if any, or the observable state of the execution. A function definition is idempotent if the derived function pointer value is idempotent.
9 A function is reproducible if it is effectless and idempotent; it is unsequenced if it is stateless, effectless, idempotent and independent.

関連URL

*1:unsequencedを満たすには関数終了時点で観測可能な変化がなければよく、関数は(呼出し元がポインタ経由で渡した)静的記憶域期間(static storage duration)変数に対して読取/書込を行う可能性がある。...そんな用途にstatic変数を使うんじゃねぇ(`ェ´)

*2:関数引数リスト中の T arg[static N] はC99で導入された構文。T 型のポインタ型仮引数 arg が少なくとも N 要素を持つデータ領域を指すことを表明する。id:yohhoy:20170503 も参照のこと。

*3:typeof はC2xで導入される型情報を取り出す演算子(→id:yohhoy:20220912)。typeof(sqrt) はC標準ライブラリ関数 sqrt の型情報つまり「戻り値doubleかつ引数リスト(dubule)をもつ関数型」を表す型指定子であり、該当文は extern double sqrt(double) [[unsequenced]]; 関数宣言となる。

nullptr定数 in 標準C

プログラミング言語Cの次期仕様C2x(C23)にて、ついにC言語にも真のヌルポインタ定数nullptrがやってくる。
C++11(→id:yohhoy:20120503)から遅れること12年。

int *p1 = nullptr;  // C2x以降
int *p2 = NULL;
int *p3 = 0;

まとめ:

  • C/C++両言語のnullptrがセマンティクス一致するよう設計されている。
  • 事前定義定数*1nullptrは、専用のnullptr_t型が取りうる唯一の値。
    • 定数nullptrはいつでも利用可能(ヘッダinclude不要)。
    • nullptr_t型は標準ヘッダ <stddef.h> で定義される。*2
  • C2xで追加されるnullptrのほか、現行の整数定数値0やマクロNULLをいずれもヌルポインタ定数(null pointer constant)として扱う。
  • nullptr_t型はvoid*型と同じサイズ/アライメントを持ち、nullptr(void*)0の内部表現は等しい。
    • 可変引数リストに対する番兵(sentinel)実引数として、nullptrNULLよりもポータブルに使える。(→id:yohhoy:20160224

関連URL

*1:predefined constants はC2xにて新たに導入される構文要素。false, true, nulllptr の3種類が追加される。false/true については C言語のbool型とその名前について 〜もう_Boolは嫌だ〜 を参照。

*2:C2xで導入される typeof_unqual を利用して typedef typeof_unqual(nullptr) nullptr_t; と定義される。

改行コード(CR/LF)と改行文字と標準C

プログラミング言語C標準規格における改行文字(new-line character)と改行コードCR, LFとの関係性について。

まとめ:

  • C標準規格ではプログラム内部で扱う「改行文字」と、外部ファイルにおける具体的なCR, LF等の「文字コード」を区別する。*1 *2
  • 改行文字をファイル上でどう表現するかについて何ら規定しない。CR/LFを使わない方式も想定されている。
    • UNIX互換システムの場合、改行文字==改行コードLF(0x0A)となる。
    • Windows OSの場合、改行文字は2個の改行コードCRLF(0x0D 0x0A)で表現される。
    • 上記のような改行コードによる行区切り表現だけでなく、メタ情報を利用した行区切り位置表現、長さプレフィックスと文字列データ表現、固定長レコードと特殊パディング文字表現(!)*3など、多種多様なテキストデータの表現方式を許容する。
  • 仮想ターミナルなどの文字表示デバイスへ出力する場合、下記エスケープシーケンスの動作を規定する。
    • \n(new-line):次行の先頭位置にカーソル位置を移動する。
    • \r(carriage return):現在行の先頭位置にカーソル位置を移動する。

文字集合(Character sets)

C99 5.2.1/p1, p3より一部引用(下線部は強調)。

1 Two sets of characters and their associated collating sequences shall be defined: the set in which source files are written (the source character set), and the set interpreted in the execution environment (the execution character set). (snip)

3 Both the basic source and basic execution character sets shall have the following members:
 (snip)
In source files, there shall be some way of indicating the end of each line of text; this International Standard treats such an end-of-line indicator as if it were a single new-line character. In the basic execution character set, there shall be control characters representing alert, backspace, carriage return, and new line. (snip)

C99 Rationale, 5.2.1より一部引用。

The C89 Committee ultimately came to remarkable unanimity on the subject of character set requirements. There was strong sentiment that C should not be tied to ASCII, despite its heritage and despite the precedent of Ada being defined in terms of ASCII. Rather, an implementation is required to provide a unique character code for each of the printable graphics used by C, and for each of the control codes representable by an escape sequence. (No particular graphic representation for any character is prescribed; thus the common Japanese practice of using the glyph "¥" for the C character "\" is perfectly legitimate.) Translation and execution environments may have different character sets, but each must meet this requirement in its own way. The goal is to ensure that a conforming implementation can translate a C translator written in C.

For this reason, and for economy of description, source code is described as if it undergoes the same translation as text that is input by the standard library I/O routines: each line is terminated by some newline character regardless of its external representation.

文字表示セマンティクス(Character display semantics)

C99 5.2.2/p2-3より一部引用(下線部は強調)。

2 Alphabetic escape sequences representing nongraphic characters in the execution character set are intended to produce actions on display devices as follows:

  • (snip)
  • \n (new line) Moves the active position to the initial position of the next line.
  • \r (carriage return) Moves the active position to the initial position of the current line.
  • (snip)

3 Each of these escape sequences shall produce a unique implementation-defined value which can be stored in a single char object. The external representations in a text file need not be identical to the internal representations, and are outside the scope of this International Standard.

C99 Rationale, 5.2.2より一部引用(下線部は強調)。

The Standard defines a number of internal character codes for specifying "format-effecting actions on display devices," and provides printable escape sequences for each of them. These character codes are clearly modeled after ASCII control codes, and the mnemonic letters used to specify their escape sequences reflect this heritage. Nevertheless, they are internal codes for specifying the format of a display in an environment-independent manner; they must be written to a text file to effect formatting on a display device. The Standard states quite clearly that the external representation of a text file (or data stream) may well differ from the internal form, both in character codes and number of characters needed to represent a single internal code.

The distinction between internal and external codes most needs emphasis with respect to new-line. INCITS L2, Codes and Character Sets (and now also ISO/IEC JTC 1/SC2/WG1, 8 Bit Character Sets), uses the term to refer to an external code used for information interchange whose display semantics specify a move to the next line. Although ISO/IEC 646 deprecates the combination of the motion to the next line with a motion to the initial position on the line, the C Standard uses new-line to designate the end-of-line internal code represented by the escape sequence '\n'. While this ambiguity is perhaps unfortunate, use of the term in the latter sense is nearly universal within the C community. But the knowledge that this internal code has numerous external representations depending upon operating system and medium is equally widespread.

ストリーム(Streams)

C99 7.19.2/p1-3より一部引用(下線部は強調)。

1 Input and output, whether to or from physical devices such as terminals and tape drives, or whether to or from files supported on structured storage devices, are mapped into logical data streams, whose properties are more uniform than their various inputs and outputs. Two forms of mapping are supported, for text streams and for binary streams.232)
脚注232) An implementation need not distinguish between text streams and binary streams. In such an implementation, there need be no new-line characters in a text stream nor any limit to the length of a line.

2 A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to differing conventions for representing text in the host environment. Thus, there need not be a one-to-one correspondence between the characters in a stream and those in the external representation. Data read in from a text stream will necessarily compare equal to the data that were earlier written out to that stream only if: the data consist only of printing characters and the control characters horizontal tab and new-line; no new-line character is immediately preceded by space characters; and the last character is a new-line character. Whether space characters that are written out immediately before a new-line character appear when read in is implementation-defined.

C99 Rationale, 5.2.1, 7.19.2より一部引用。

C inherited its notion of text streams from the UNIX environment in which it was born. Having each line delimited by a single newline character, regardless of the characteristics of the actual terminal, supported a simple model of text as a sort of arbitrary length scroll or "galley." Having a channel that is "transparent" (no file structure or reserved data encodings) eliminated the need for a distinction between text and binary streams.

(snip)

Troublesome aspects of the stream concept include:

The definition of lines. In the UNIX model, division of a file into lines is effected by newline characters. Different techniques are used by other systems: lines may be separated by CR-LF (carriage return, line feed) or by unrecorded areas on the recording medium; or each line may be prefixed by its length. The Standard addresses this diversity by specifying that newline be used as a line separator at the program level, but then permitting an implementation to transform the data read or written to conform to the conventions of the environment.
Some environments represent text lines as blank-filled fixed-length records. Thus the Standard specifies that it is implementation-defined whether trailing blanks are removed from a line on input. (This specification also addresses the problems of environments which represent text as variable-length records, but do not allow a record length of 0: an empty line may be written as a one-character record containing a blank, and the blank is stripped on input.)

Transparency. Some programs require access to external data without modification. For instance, transformation of CR-LF to a newline character is usually not desirable when object code is processed. The Standard defines two stream types, text and binary, to allow a program to define, when a file is opened, whether the preservation of its exact contents or of its line structure is more important in an environment which cannot accurately reflect both.

関連URL

*1:プログラムへのデータ入出力をテキストストリーム(text stream)で扱う場合のお話。バイナリストリーム(binary stream)で扱う場合は外部ファイル上の文字コード値に直接アクセスする。

*2:標準入出力 stdin, strerr や標準エラー出力 stderr はいずれもテキストストリームとして初期化される。(C99 7.19.3/p7)

*3:テキストストリームをファイルに書き出す場合、処理系によっては一定長に切詰め(truncated)られる可能性が明記されている。(C99 7.19.3/p2)

MC Hammer in C++ Standard

プログラミング言語C++標準規格のサンプルコードでビートを刻むMCハマー
"U Can't Touch This" ( 'ω' و(و♪ ƪ( 'ω' ƪ )♪

template<ranges::constant_range R>
void cant_touch_this(R&&);

vector<char> hammer = {'m', 'c'};
span<char> beat = hammer;
cant_touch_this(views::as_const(beat));
  // will not modify the elements of hammer
https://github.com/cplusplus/draft/commit/32535186bc66b3485194b41d5b2107e15c6bd34a

std::ranges::constant_rangeコンセプトやstd::views::as_constレンジアダプタはC++2b(C++23)標準ライブラリへの追加予定機能。

関連URL

std::shared_ptr型と->*演算子とstd::invoke関数

C++標準ライブラリのスマートポインタ型std::shared_ptr<T>では->*演算子オーバーロードを提供しない(注:->はあるよ)。

#include <memory>

struct X { int mf(); };
// メンバ関数ポインタ
int (X::*pmf)() = &X::mf;

// (通常)ポインタ型
X* p = new X;
p->mf();      // OK
(p->*pmf)();  // OK

// std::shared_ptr型
std::shared_ptr<X> sp{ p };
sp->mf();      // OK
(sp->*pmf)();  // NG!
(sp.get()->*pmf)();  // OK: get()でポインタを取出す
(&*sp->*pmf)();      // OK: 暗号じみた記法

C++17で追加されたstd::invoke関数を利用すると、メンバ関数ポインタ呼び出しであっても通常ポインタとスマートポインタ型を統一的に扱える。

#include <functional>

std::invoke(pmf, p);   // OK: X*
std::invoke(pmf, sp);  // OK: std::shared_ptr<X>

// 代替(C++03/11/14)
(*s.*pmf)();   // OK
(*sp.*pmf)();  // OK

マイナー機能のため有用性は低いが、技術的には->*演算子オーバーロードを提供可能。C++14機能までを使った実装例(エッセンスのみ):

// スマートポインタ型
template <typename T>
struct SP {
  T* p_ = nullptr;
  SP(T* p): p_(p) {}

  // ->演算子オーバーロード
  T* operator->() { return p_; }

  // ->*演算子オーバーロード
  template<typename R, typename... Ts>
  auto operator->*(R (T::*pmf)(Ts...)) {
    return [p=p_, pmf](Ts&&... args) -> R {
      return (p->*pmf)(std::forward<Ts>(args)...);
    };
  }
};

// スマートポインタ型
SP<X> sp{ p };
sp->mf();      // OK
(sp->*pmf)();  // OK

関連URL