diff options
| author | nsfisis <nsfisis@gmail.com> | 2022-12-23 23:27:09 +0900 |
|---|---|---|
| committer | nsfisis <nsfisis@gmail.com> | 2023-03-06 01:46:04 +0900 |
| commit | 88ba6cfe220216f371f8756921059fac51a21262 (patch) | |
| tree | f272db2a0a3340f103df6618f19a101e65941b37 /content/posts/2021-10-02 | |
| parent | 8f988a6e899aed678406ddfac1be4ef105439274 (diff) | |
| download | blog.nsfisis.dev-88ba6cfe220216f371f8756921059fac51a21262.tar.gz blog.nsfisis.dev-88ba6cfe220216f371f8756921059fac51a21262.tar.zst blog.nsfisis.dev-88ba6cfe220216f371f8756921059fac51a21262.zip | |
AsciiDoc to DocBook
Diffstat (limited to 'content/posts/2021-10-02')
14 files changed, 910 insertions, 956 deletions
diff --git a/content/posts/2021-10-02/cpp-you-can-use-keywords-in-attributes.adoc b/content/posts/2021-10-02/cpp-you-can-use-keywords-in-attributes.adoc deleted file mode 100644 index afa0f3f..0000000 --- a/content/posts/2021-10-02/cpp-you-can-use-keywords-in-attributes.adoc +++ /dev/null @@ -1,106 +0,0 @@ -= [C++] 属性構文の属性名にはキーワードが使える -:tags: cpp, cpp17 -:description: C++ の属性構文の属性名には、キーワードが使える。ネタ記事。 -:revision-1: 2021-10-02 Qiita から移植 - -この記事は Qiita から移植してきたものです。 元 URL: -https://qiita.com/nsfisis/items/94090937bcf860cfa93b - -''''' - -タイトル落ち。まずはこのコードを見て欲しい。 - -[source,cpp] ----- -#include <iostream> - -[[alignas]] [[alignof]] [[and]] [[and_eq]] [[asm]] [[auto]] [[bitand]] -[[bitor]] [[bool]] [[break]] [[case]] [[catch]] [[char]] [[char16_t]] -[[char32_t]] [[class]] [[compl]] [[const]] [[const_cast]] [[constexpr]] -[[continue]] [[decltype]] [[default]] [[delete]] [[do]] [[double]] -[[dynamic_cast]] [[else]] [[enum]] [[explicit]] [[export]] [[extern]] [[false]] -[[final]] [[float]] [[for]] [[friend]] [[goto]] [[if]] [[inline]] [[int]] -[[long]] [[mutable]] [[namespace]] [[new]] [[noexcept]] [[not]] [[not_eq]] -[[nullptr]] [[operator]] [[or]] [[or_eq]] [[override]] [[private]] -[[protected]] [[public]] [[register]] [[reinterpret_cast]] [[return]] [[short]] -[[signed]] [[sizeof]] [[static]] [[static_assert]] [[static_cast]] [[struct]] -[[switch]] [[template]] [[this]] [[thread_local]] [[throw]] [[true]] [[try]] -[[typedef]] [[typeid]] [[typename]] [[union]] [[unsigned]] -[[virtual]] [[void]] [[volatile]] [[wchar_t]] [[while]] [[xor]] [[xor_eq]] -// [[using]] -int main() { - std::cout << "Hello, World!" << std::endl; -} ----- - -____ -コンパイラのバージョン $ clang++ –version Apple clang version 11.0.0 -(clang-1100.0.33.8) Target: x86_64-apple-darwin19.6.0 Thread model: -posix InstalledDir: -/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin - -コンパイルコマンド (C++17指定) $ clang++ –std=c++17 hoge.cpp -____ - -この記事から得られるものはこれ以上ないので以下は蛇足になる。 - -別件で cppreference.com の -https://en.cppreference.com/w/cpp/language/identifiers[identifier -のページ] を読んでいた時、次の文が目に止まった。 - -____ -* the identifiers that are keywords cannot be used for other purposes; -** The only place they can be used as non-keywords is in an -attribute-token. (e.g. [[private]] is a valid attribute) (since C++11) -____ - -キーワードでも属性として指定する場合は非キーワードとして使えるらしい。 -実際にやってみる。 - -同サイトの https://en.cppreference.com/w/cpp/keyword[keywords のページ] -から一覧を拝借し、上のコードが出来上がった (C++17 -においてキーワードでないものなど、一部省いている)。 大量の警告 (unknown -attribute `〇〇' ignored) -がコンパイラから出力されるが、コンパイルできる。 - -上のコードでは `[[using]]` をコメントアウトしているが、これは `using` -キーワードのみ属性構文の中で意味を持つからであり、このコメントアウトを外すとコンパイルに失敗する。 - -[source,cpp] ----- -// using の例 -[[using foo: attr1, attr2]] int x; // [[foo::attr1, foo::attr2]] の糖衣構文 ----- - -C++17 の仕様も見てみる (正確には標準化前のドラフト)。 - -引用元: https://timsong-cpp.github.io/cppwp/n4659/dcl.attr#grammar-4 - -____ -If a keyword or an alternative token that satisfies the syntactic -requirements of an identifier is contained in an attribute-token, it is -considered an identifier. -____ - -「`identifier` の構文上の要件を満たすキーワードまたは代替トークンが -`attribute-token` に含まれている場合、`identifier` -とみなされる」とある。どうやら間違いないようだ。 - -ところで、代替トークン (alternative token) とは `and` (`&`) や `bitor` -(`|`) などのことだが、`identifier` -の構文上の要件を満たさないような代替トークンなどあるのか? -疑問に思って調べたところ、代替トークンという語にはダイグラフも含まれるらしい -(参考: -https://timsong-cpp.github.io/cppwp/n4659/lex.digraph[同ドラフト]) - -* `<%` → `{` -* `%>` → `}` -* `<:` → `[` -* `:>` → `]` -* `%:` → `#` -* `%:%:` → `##` - -「`identifier` -の構文上の要件を満たさないような代替トークン」はこれらが当てはまると思われる。 - -調べた感想: 字句解析器か構文解析器が辛そう diff --git a/content/posts/2021-10-02/cpp-you-can-use-keywords-in-attributes.xml b/content/posts/2021-10-02/cpp-you-can-use-keywords-in-attributes.xml new file mode 100644 index 0000000..f212b7c --- /dev/null +++ b/content/posts/2021-10-02/cpp-you-can-use-keywords-in-attributes.xml @@ -0,0 +1,116 @@ +<?xml version="1.0" encoding="UTF-8"?> +<article xmlns="http://docbook.org/ns/docbook" xmlns:xl="http://www.w3.org/1999/xlink" version="5.0"> + <info> + <title>【C++】 属性構文の属性名にはキーワードが使える</title> + <abstract> + C++ の属性構文の属性名には、キーワードが使える。ネタ記事。 + </abstract> + <keywordset> + <keyword>cpp</keyword> + <keyword>cpp17</keyword> + </keywordset> + <revhistory> + <revision> + <date>2021-10-02</date> + <revremark>Qiita から移植</revremark> + </revision> + </revhistory> + </info> + <simpara>この記事は Qiita から移植してきたものです。 元 URL: + <link xl:href="https://qiita.com/nsfisis/items/94090937bcf860cfa93b">https://qiita.com/nsfisis/items/94090937bcf860cfa93b</link></simpara> +<simpara><hr/></simpara> +<simpara>タイトル落ち。まずはこのコードを見て欲しい。</simpara> +<programlisting language="cpp" linenumbering="unnumbered">#include <iostream> + +[[alignas]] [[alignof]] [[and]] [[and_eq]] [[asm]] [[auto]] [[bitand]] +[[bitor]] [[bool]] [[break]] [[case]] [[catch]] [[char]] [[char16_t]] +[[char32_t]] [[class]] [[compl]] [[const]] [[const_cast]] [[constexpr]] +[[continue]] [[decltype]] [[default]] [[delete]] [[do]] [[double]] +[[dynamic_cast]] [[else]] [[enum]] [[explicit]] [[export]] [[extern]] [[false]] +[[final]] [[float]] [[for]] [[friend]] [[goto]] [[if]] [[inline]] [[int]] +[[long]] [[mutable]] [[namespace]] [[new]] [[noexcept]] [[not]] [[not_eq]] +[[nullptr]] [[operator]] [[or]] [[or_eq]] [[override]] [[private]] +[[protected]] [[public]] [[register]] [[reinterpret_cast]] [[return]] [[short]] +[[signed]] [[sizeof]] [[static]] [[static_assert]] [[static_cast]] [[struct]] +[[switch]] [[template]] [[this]] [[thread_local]] [[throw]] [[true]] [[try]] +[[typedef]] [[typeid]] [[typename]] [[union]] [[unsigned]] +[[virtual]] [[void]] [[volatile]] [[wchar_t]] [[while]] [[xor]] [[xor_eq]] +// [[using]] +int main() { +std::cout << "Hello, World!" << std::endl; +}</programlisting> +<blockquote> + <simpara>コンパイラのバージョン $ clang++ –version Apple clang version 11.0.0 + (clang-1100.0.33.8) Target: x86_64-apple-darwin19.6.0 Thread model: + posix InstalledDir: + /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin</simpara> +<simpara>コンパイルコマンド (C17指定) $ clang –std=c++17 hoge.cpp</simpara> +</blockquote> +<simpara>この記事から得られるものはこれ以上ないので以下は蛇足になる。</simpara> +<simpara>別件で cppreference.com の +<link xl:href="https://en.cppreference.com/w/cpp/language/identifiers">identifier +のページ</link> を読んでいた時、次の文が目に止まった。</simpara> +<blockquote> + <itemizedlist> + <listitem> + <simpara>the identifiers that are keywords cannot be used for other purposes;</simpara> + <itemizedlist> + <listitem> + <simpara>The only place they can be used as non-keywords is in an + attribute-token. (e.g. [[private]] is a valid attribute) (since C++11)</simpara> + </listitem> + </itemizedlist> + </listitem> +</itemizedlist> +</blockquote> +<simpara>キーワードでも属性として指定する場合は非キーワードとして使えるらしい。 +実際にやってみる。</simpara> +<simpara>同サイトの <link xl:href="https://en.cppreference.com/w/cpp/keyword">keywords のページ</link> + から一覧を拝借し、上のコードが出来上がった (C++17 + においてキーワードでないものなど、一部省いている)。 大量の警告 (unknown + attribute `〇〇' ignored) + がコンパイラから出力されるが、コンパイルできる。</simpara> +<simpara>上のコードでは <literal>[[using]]</literal> をコメントアウトしているが、これは <literal>using</literal> + キーワードのみ属性構文の中で意味を持つからであり、このコメントアウトを外すとコンパイルに失敗する。</simpara> +<programlisting language="cpp" linenumbering="unnumbered">// using の例 +[[using foo: attr1, attr2]] int x; // [[foo::attr1, foo::attr2]] の糖衣構文</programlisting> +<simpara>C++17 の仕様も見てみる (正確には標準化前のドラフト)。</simpara> +<simpara>引用元: <link xl:href="https://timsong-cpp.github.io/cppwp/n4659/dcl.attr#grammar-4">https://timsong-cpp.github.io/cppwp/n4659/dcl.attr#grammar-4</link></simpara> +<blockquote> + <simpara>If a keyword or an alternative token that satisfies the syntactic + requirements of an identifier is contained in an attribute-token, it is + considered an identifier.</simpara> +</blockquote> +<simpara>「<literal>identifier</literal> の構文上の要件を満たすキーワードまたは代替トークンが +<literal>attribute-token</literal> に含まれている場合、<literal>identifier</literal> +とみなされる」とある。どうやら間違いないようだ。</simpara> +<simpara>ところで、代替トークン (alternative token) とは <literal>and</literal> (<literal>&</literal>) や <literal>bitor</literal> + (<literal>|</literal>) などのことだが、<literal>identifier</literal> + の構文上の要件を満たさないような代替トークンなどあるのか? + 疑問に思って調べたところ、代替トークンという語にはダイグラフも含まれるらしい + (参考: + <link xl:href="https://timsong-cpp.github.io/cppwp/n4659/lex.digraph">同ドラフト</link>)</simpara> +<itemizedlist> + <listitem> + <simpara><literal><%</literal> → <literal>{</literal></simpara> + </listitem> + <listitem> + <simpara><literal>%></literal> → <literal>}</literal></simpara> + </listitem> + <listitem> + <simpara><literal><:</literal> → <literal>[</literal></simpara> + </listitem> + <listitem> + <simpara><literal>:></literal> → <literal>]</literal></simpara> + </listitem> + <listitem> + <simpara><literal>%:</literal> → <literal>#</literal></simpara> + </listitem> + <listitem> + <simpara><literal>%:%:</literal> → <literal>##</literal></simpara> + </listitem> +</itemizedlist> +<simpara>「<literal>identifier</literal> + の構文上の要件を満たさないような代替トークン」はこれらが当てはまると思われる。</simpara> +<simpara>調べた感想: 字句解析器か構文解析器が辛そう</simpara> +</article> diff --git a/content/posts/2021-10-02/python-unbound-local-error.adoc b/content/posts/2021-10-02/python-unbound-local-error.adoc deleted file mode 100644 index f68ae4d..0000000 --- a/content/posts/2021-10-02/python-unbound-local-error.adoc +++ /dev/null @@ -1,66 +0,0 @@ -= [Python] クロージャとUnboundLocalError: local variable 'x' referenced before assignment -:tags: python, python3 -:description: Python における UnboundLocalError の理由と対処法。 -:revision-1: 2021-10-02 Qiita から移植 - -この記事は Qiita から移植してきたものです。 元 URL: -https://qiita.com/nsfisis/items/5d733703afcb35bbf399 - -''''' - -本記事は Python 3.7.6 の動作結果を元にして書かれている。 - -Python でクロージャを作ろうと、次のようなコードを書いた。 - -[source,python] ----- -def f(): - x = 0 - def g(): - x += 1 - g() - -f() ----- - -関数 `g` から 関数 `f` のスコープ内で定義された変数 `x` を参照し、それに -1 を足そうとしている。 これを実行すると `x += 1` -の箇所でエラーが発生する。 - -____ -UnboundLocalError: local variable `x' referenced before assignment -____ - -local変数 `x` が代入前に参照された、とある。これは、`f` の `x` -を参照するのではなく、新しく別の変数を `g` 内に作ってしまっているため。 -前述のコードを宣言と代入を便宜上分けて書き直すと次のようになる。`var` -を変数宣言のための構文として擬似的に利用している。 - -[source,python] ----- -# 注: var は正しい Python の文法ではない。上記参照のこと -def f(): - var x # f の local変数 'x' を宣言 - x = 0 # x に 0 を代入 - def g(): # f の内部関数 g を定義 - var x # g の local変数 'x' を宣言 - # たまたま f にも同じ名前の変数があるが、それとは別の変数 - x += 1 # x に 1 を加算 (x = x + 1 の糖衣構文) - # 加算する前の値を参照しようとするが、まだ代入されていないためエラー - g() ----- - -当初の意図を表現するには、次のように書けばよい。 - -[source,python] ----- -def f(): - x = 0 - def g(): - nonlocal x ## (*) - x += 1 - g() ----- - -`(*)` のように、`nonlocal` を追加する。これにより一つ外側のスコープ (`g` -の一つ外側 = `f`) で定義されている `x` を探しに行くようになる。 diff --git a/content/posts/2021-10-02/python-unbound-local-error.xml b/content/posts/2021-10-02/python-unbound-local-error.xml new file mode 100644 index 0000000..3d33628 --- /dev/null +++ b/content/posts/2021-10-02/python-unbound-local-error.xml @@ -0,0 +1,60 @@ +<?xml version="1.0" encoding="UTF-8"?> +<article xmlns="http://docbook.org/ns/docbook" xmlns:xl="http://www.w3.org/1999/xlink" version="5.0"> + <info> + <title>【Python】 クロージャとUnboundLocalError: local variable 'x' referenced before assignment</title> + <abstract> + Python における UnboundLocalError の理由と対処法。 + </abstract> + <keywordset> + <keyword>python</keyword> + <keyword>python3</keyword> + </keywordset> + <revhistory> + <revision> + <date>2021-10-02</date> + <revremark>Qiita から移植</revremark> + </revision> + </revhistory> + </info> + <simpara>この記事は Qiita から移植してきたものです。 元 URL: + <link xl:href="https://qiita.com/nsfisis/items/5d733703afcb35bbf399">https://qiita.com/nsfisis/items/5d733703afcb35bbf399</link></simpara> +<simpara><hr/></simpara> +<simpara>本記事は Python 3.7.6 の動作結果を元にして書かれている。</simpara> +<simpara>Python でクロージャを作ろうと、次のようなコードを書いた。</simpara> +<programlisting language="python" linenumbering="unnumbered">def f(): +x = 0 +def g(): +x += 1 +g() + +f()</programlisting> +<simpara>関数 <literal>g</literal> から 関数 <literal>f</literal> のスコープ内で定義された変数 <literal>x</literal> を参照し、それに +1 を足そうとしている。 これを実行すると <literal>x += 1</literal> +の箇所でエラーが発生する。</simpara> +<blockquote> + <simpara>UnboundLocalError: local variable `x' referenced before assignment</simpara> +</blockquote> +<simpara>local変数 <literal>x</literal> が代入前に参照された、とある。これは、<literal>f</literal> の <literal>x</literal> + を参照するのではなく、新しく別の変数を <literal>g</literal> 内に作ってしまっているため。 + 前述のコードを宣言と代入を便宜上分けて書き直すと次のようになる。<literal>var</literal> + を変数宣言のための構文として擬似的に利用している。</simpara> +<programlisting language="python" linenumbering="unnumbered"># 注: var は正しい Python の文法ではない。上記参照のこと +def f(): +var x # f の local変数 'x' を宣言 +x = 0 # x に 0 を代入 +def g(): # f の内部関数 g を定義 +var x # g の local変数 'x' を宣言 +# たまたま f にも同じ名前の変数があるが、それとは別の変数 +x += 1 # x に 1 を加算 (x = x + 1 の糖衣構文) +# 加算する前の値を参照しようとするが、まだ代入されていないためエラー +g()</programlisting> +<simpara>当初の意図を表現するには、次のように書けばよい。</simpara> +<programlisting language="python" linenumbering="unnumbered">def f(): +x = 0 +def g(): +nonlocal x ## (*) +x += 1 +g()</programlisting> +<simpara><literal>(*)</literal> のように、<literal>nonlocal</literal> を追加する。これにより一つ外側のスコープ (<literal>g</literal> + の一つ外側 = <literal>f</literal>) で定義されている <literal>x</literal> を探しに行くようになる。</simpara> +</article> diff --git a/content/posts/2021-10-02/ruby-detect-running-implementation.adoc b/content/posts/2021-10-02/ruby-detect-running-implementation.adoc deleted file mode 100644 index 1434891..0000000 --- a/content/posts/2021-10-02/ruby-detect-running-implementation.adoc +++ /dev/null @@ -1,72 +0,0 @@ -= [Ruby] 自身を実行している処理系の種類を判定する -:tags: ruby -:description: Ruby には複数の実装があるが、自身を実行している処理系の種類を \ - スクリプト上からどのように判定すればよいだろうか。 -:revision-1: 2021-10-02 Qiita から移植 - -この記事は Qiita から移植してきたものです。 元 URL: -https://qiita.com/nsfisis/items/74d7ffeeebc51b20d791 - -''''' - -Ruby -という言語には複数の実装があるが、それらをスクリプト上からどのようにして -programmatically に見分ければよいだろうか。 - -`Object` クラスに定義されている `RUBY_ENGINE` -という定数がこの用途に使える。 - -参考: -https://docs.ruby-lang.org/ja/latest/method/Object/c/RUBY_ENGINE.html[Object::RUBY_ENGINE] - -上記ページの例から引用する: - -[source,shell-session] ----- -$ ruby-1.9.1 -ve 'p RUBY_ENGINE' -ruby 1.9.1p0 (2009-03-04 revision 22762) [x86_64-linux] -"ruby" -$ jruby -ve 'p RUBY_ENGINE' -jruby 1.2.0 (ruby 1.8.6 patchlevel 287) (2009-03-16 rev 9419) [i386-java] -"jruby" ----- - -それぞれの処理系がどのような値を返すかだが、stack overflow -に良い質問と回答があった。 - -https://stackoverflow.com/a/9894232[What values for RUBY_ENGINE -correspond to which Ruby implementations?] より引用: - -____ -[cols="^,<",options="header",] -|=== -|RUBY_ENGINE |Implementation -|<undefined> |MRI < 1.9 -|`ruby' |MRI >= 1.9 or REE -|`jruby' |JRuby -|`macruby' |MacRuby -|`rbx' |Rubinius -|`maglev' |MagLev -|`ironruby' |IronRuby -|`cardinal' |Cardinal -|=== -____ - -なお、この質問・回答は -2014年になされたものであり、値は変わっている可能性がある。MRI (aka -CRuby) については執筆時現在 (2020/12/8) も `'ruby'` -が返ってくることを確認済み。 - -この表にない主要な処理系として、https://mruby.org[mruby] は `'mruby'` -を返す。 - -https://github.com/mruby/mruby/blob/ed29d74bfd95362eaeb946fcf7e865d80346b62b/include/mruby/version.h#L32-L35[mruby -該当部分のソース] より引用: - -[source,c] ----- -/* - * Ruby engine. - */ -#define MRUBY_RUBY_ENGINE "mruby" ----- diff --git a/content/posts/2021-10-02/ruby-detect-running-implementation.xml b/content/posts/2021-10-02/ruby-detect-running-implementation.xml new file mode 100644 index 0000000..ccc797b --- /dev/null +++ b/content/posts/2021-10-02/ruby-detect-running-implementation.xml @@ -0,0 +1,95 @@ +<?xml version="1.0" encoding="UTF-8"?> +<article xmlns="http://docbook.org/ns/docbook" xmlns:xl="http://www.w3.org/1999/xlink" version="5.0"> + <info> + <title>【Ruby】 自身を実行している処理系の種類を判定する</title> + <abstract> + Ruby には複数の実装があるが、自身を実行している処理系の種類をスクリプト上からどのように判定すればよいだろうか。 + </abstract> + <keywordset> + <keyword>ruby</keyword> + </keywordset> + <revhistory> + <revision> + <date>2021-10-02</date> + <revremark>Qiita から移植</revremark> + </revision> + </revhistory> + </info> + <simpara>この記事は Qiita から移植してきたものです。 元 URL: + <link xl:href="https://qiita.com/nsfisis/items/74d7ffeeebc51b20d791">https://qiita.com/nsfisis/items/74d7ffeeebc51b20d791</link></simpara> +<simpara><hr/></simpara> +<simpara>Ruby +という言語には複数の実装があるが、それらをスクリプト上からどのようにして +programmatically に見分ければよいだろうか。</simpara> +<simpara><literal>Object</literal> クラスに定義されている <literal>RUBY_ENGINE</literal> + という定数がこの用途に使える。</simpara> +<simpara>参考: +<link xl:href="https://docs.ruby-lang.org/ja/latest/method/Object/c/RUBY_ENGINE.html">Object::RUBY_ENGINE</link></simpara> +<simpara>上記ページの例から引用する:</simpara> +<programlisting language="shell-session" linenumbering="unnumbered">$ ruby-1.9.1 -ve 'p RUBY_ENGINE' +ruby 1.9.1p0 (2009-03-04 revision 22762) [x86_64-linux] +"ruby" +$ jruby -ve 'p RUBY_ENGINE' +jruby 1.2.0 (ruby 1.8.6 patchlevel 287) (2009-03-16 rev 9419) [i386-java] +"jruby"</programlisting> +<simpara>それぞれの処理系がどのような値を返すかだが、stack overflow +に良い質問と回答があった。</simpara> +<simpara><link xl:href="https://stackoverflow.com/a/9894232">What values for RUBY_ENGINE +correspond to which Ruby implementations?</link> より引用:</simpara> +<blockquote> + <table> + <thead> + <tr> + <td>RUBY_ENGINE</td> + <td>Implementation</td> + </tr> + </thead> + <tbody> + <tr> + <td><undefined></td> + <td>MRI < 1.9</td> + </tr> + <tr> + <td>`ruby'</td> + <td>MRI >= 1.9 or REE</td> + </tr> + <tr> + <td>`jruby'</td> + <td>JRuby</td> + </tr> + <tr> + <td>`macruby'</td> + <td>MacRuby</td> + </tr> + <tr> + <td>`rbx'</td> + <td>Rubinius</td> + </tr> + <tr> + <td>`maglev'</td> + <td>MagLev</td> + </tr> + <tr> + <td>`ironruby'</td> + <td>IronRuby</td> + </tr> + <tr> + <td>`cardinal'</td> + <td>Cardinal</td> + </tr> + </tbody> + </table> +</blockquote> +<simpara>なお、この質問・回答は +2014年になされたものであり、値は変わっている可能性がある。MRI (aka +CRuby) については執筆時現在 (2020/12/8) も <literal>'ruby'</literal> +が返ってくることを確認済み。</simpara> +<simpara>この表にない主要な処理系として、https://mruby.org[mruby] は <literal>'mruby'</literal> + を返す。</simpara> +<simpara><link xl:href="https://github.com/mruby/mruby/blob/ed29d74bfd95362eaeb946fcf7e865d80346b62b/include/mruby/version.h#L32-L35">mruby +該当部分のソース</link> より引用:</simpara> +<programlisting language="c" linenumbering="unnumbered">/* +* Ruby engine. +*/ +#define MRUBY_RUBY_ENGINE "mruby"</programlisting> +</article> diff --git a/content/posts/2021-10-02/ruby-then-keyword-and-case-in.adoc b/content/posts/2021-10-02/ruby-then-keyword-and-case-in.adoc deleted file mode 100644 index 94fcf48..0000000 --- a/content/posts/2021-10-02/ruby-then-keyword-and-case-in.adoc +++ /dev/null @@ -1,226 +0,0 @@ -= [Ruby] then キーワードと case in -:tags: ruby, ruby3 -:description: Ruby 3.0 で追加される case in 構文と、then キーワードについて。 -:revision-1: 2021-10-02 Qiita から移植 - -この記事は Qiita から移植してきたものです。 元 URL: -https://qiita.com/nsfisis/items/787a8cf888a304497223 - -''''' - -== TL; DR - -`case` - `in` によるパターンマッチング構文でも、`case` - `when` -と同じように `then` が使える (場合によっては使う必要がある)。 - -== `then` とは - -使われることは稀だが、Ruby では `then` -がキーワードになっている。次のように使う: - -[source,ruby] ----- -if cond then - puts "Y" -else - puts "N" -end ----- - -このキーワードが現れうる場所はいくつかあり、`if`、`unless`、`rescue`、`case` -構文がそれに当たる。 上記のように、何か条件を書いた後 `then` -を置き、式がそこで終了していることを示すマーカーとして機能する。 - -[source,ruby] ----- -# Example: - -if x then - a -end - -unless x then - a -end - -begin - a -rescue then - b -end - -case x -when p then - a -end ----- - -== なぜ普段は書かなくてもよいのか - -普通 Ruby のコードで `then` -を書くことはない。なぜか。次のコードを実行してみるとわかる。 - -[source,ruby] ----- -if true puts 'Hello, World!' end ----- - -次のような構文エラーが出力される。 - -.... -20:1: syntax error, unexpected local variable or method, expecting `then' or ';' or '\n' -if true puts 'Hello, World!' end - ^~~~ -20:1: syntax error, unexpected `end', expecting end-of-input -...f true puts 'Hello, World!' end -.... - -二つ目のメッセージは無視して一つ目を読むと、`then` か `;` -か改行が来るはずのところ変数だかメソッドだかが現れたことによりエラーとなっているようだ。 - -ポイントは改行が `then` (や `;`) の代わりとなることである。`true` -の後に改行を入れてみる。 - -[source,ruby] ----- -if true -puts 'Hello, World!' end ----- - -無事 Hello, World! と出力されるようになった。 - -== なぜ `then` や `;` や改行が必要か - -なぜ `then` や `;` や改行 (以下 「`then` 等」) -が必要なのだろうか。次の例を見てほしい: - -[source,ruby] ----- -if a b end ----- - -`then` も `;` -も改行もないのでエラーになるが、これは条件式がどこまで続いているのかわからないためだ。 -この例は二通りに解釈できる。 - -[source,ruby] ----- -# a という変数かメソッドの評価結果が truthy なら b という変数かメソッドを評価 -if a then - b -end ----- - -[source,ruby] ----- -# a というメソッドに b という変数かメソッドの評価結果を渡して呼び出し、 -# その結果が truthy なら何もしない -if a(b) then -end ----- - -`then` 等はこの曖昧性を排除するためにあり、条件式は `if` から `then` -等までの間にある、ということを明確にする。 C系の `if` 後に来る `(`/`)` -や、Python の `:`、Rust/Go/Swift などの `{` も同じ役割を持つ。 - -Ruby の場合、プログラマーが書きやすいよう改行でもって `then` -が代用できるので、ほとんどの場合 `then` は必要ない。 - -== `case` - `in` における `then` - -ようやく本題にたどり着いた。来る Ruby 3.0 では `case` と `in` -キーワードを使ったパターンマッチングの構文が入る予定である。この構文でもパターン部との区切りとして -`then` 等が必要になる。 (現在の) Ruby には formal -な形式での文法仕様は存在しないので、yacc の定義ファイルを参照した (yacc -の説明は省略)。 - -https://github.com/ruby/ruby/blob/221ca0f8281d39f0dfdfe13b2448875384bbf735/parse.y#L3961-L3986 - -[source,yacc] ----- -p_case_body : keyword_in - { - SET_LEX_STATE(EXPR_BEG|EXPR_LABEL); - p->command_start = FALSE; - $<ctxt>1 = p->ctxt; - p->ctxt.in_kwarg = 1; - $<tbl>$ = push_pvtbl(p); - } - { - $<tbl>$ = push_pktbl(p); - } - p_top_expr then - { - pop_pktbl(p, $<tbl>3); - pop_pvtbl(p, $<tbl>2); - p->ctxt.in_kwarg = $<ctxt>1.in_kwarg; - } - compstmt - p_cases - { - /*%%%*/ - $$ = NEW_IN($4, $7, $8, &@$); - /*% %*/ - /*% ripper: in!($4, $7, escape_Qundef($8)) %*/ - } - ; ----- - -簡略版: - -[source,yacc] ----- -p_case_body : keyword_in p_top_expr then compstmt p_cases - ; ----- - -ここで、`keyword_in` は文字通り `in`、`p_top_expr` -はいわゆるパターン、`then` は `then` -キーワードのことではなく、この記事で `then` 等と呼んでいるもの、つまり -`then` キーワード、`;`、改行のいずれかである。 - -これにより、`case` - `when` による従来の構文と同じように、`then` -等をパターンの後ろに挿入すればよいことがわかった。つまり次の3通りのいずれかになる: - -[source,ruby] ----- -case x -in 1 then a -in 2 then b -in 3 then c -end - -case x -in 1 - a -in 2 - b -in 3 - c -end - -case x -in 1; a -in 2; b -in 3; c -end ----- - -ところで、`p_top_expr` には `if` による guard clause -が書けるので、その場合は `if` - `then` と似たような見た目になる。 - -[source,ruby] ----- -case x -in 0 then a -in n if n < 0 then b -in n then c -end ----- - -== まとめ - -* `if` や `case` の条件の後ろには `then`、`;`、改行のいずれかが必要 -** 通常は改行しておけばよい -* 3.0 で入る予定の `case` - `in` でも `then` 等が必要になる -* Ruby の構文を正確に知るには (現状) `parse.y` を直接読めばよい diff --git a/content/posts/2021-10-02/ruby-then-keyword-and-case-in.xml b/content/posts/2021-10-02/ruby-then-keyword-and-case-in.xml new file mode 100644 index 0000000..c3fd933 --- /dev/null +++ b/content/posts/2021-10-02/ruby-then-keyword-and-case-in.xml @@ -0,0 +1,191 @@ +<?xml version="1.0" encoding="UTF-8"?> +<article xmlns="http://docbook.org/ns/docbook" xmlns:xl="http://www.w3.org/1999/xlink" version="5.0"> + <info> + <title>【Ruby】 then キーワードと case in</title> + <abstract> + Ruby 3.0 で追加される case in 構文と、then キーワードについて。 + </abstract> + <keywordset> + <keyword>ruby</keyword> + <keyword>ruby3</keyword> + </keywordset> + <revhistory> + <revision> + <date>2021-10-02</date> + <revremark>Qiita から移植</revremark> + </revision> + </revhistory> + </info> + <simpara>この記事は Qiita から移植してきたものです。 元 URL: + <link xl:href="https://qiita.com/nsfisis/items/787a8cf888a304497223">https://qiita.com/nsfisis/items/787a8cf888a304497223</link></simpara> +<simpara><hr/></simpara> +<section xml:id="_tl_dr"> + <title>TL; DR</title> + <simpara><literal>case</literal> - <literal>in</literal> によるパターンマッチング構文でも、<literal>case</literal> - <literal>when</literal> + と同じように <literal>then</literal> が使える (場合によっては使う必要がある)。</simpara> +</section> +<section xml:id="_then_とは"> + <title><literal>then</literal> とは</title> + <simpara>使われることは稀だが、Ruby では <literal>then</literal> + がキーワードになっている。次のように使う:</simpara> + <programlisting language="ruby" linenumbering="unnumbered">if cond then + puts "Y" + else + puts "N" + end</programlisting> +<simpara>このキーワードが現れうる場所はいくつかあり、<literal>if</literal>、<literal>unless</literal>、<literal>rescue</literal>、<literal>case</literal> + 構文がそれに当たる。 上記のように、何か条件を書いた後 <literal>then</literal> + を置き、式がそこで終了していることを示すマーカーとして機能する。</simpara> +<programlisting language="ruby" linenumbering="unnumbered"># Example: + +if x then +a +end + +unless x then +a +end + +begin +a +rescue then +b +end + +case x +when p then +a +end</programlisting> +</section> +<section xml:id="_なぜ普段は書かなくてもよいのか"> + <title>なぜ普段は書かなくてもよいのか</title> + <simpara>普通 Ruby のコードで <literal>then</literal> + を書くことはない。なぜか。次のコードを実行してみるとわかる。</simpara> + <programlisting language="ruby" linenumbering="unnumbered">if true puts 'Hello, World!' end</programlisting> + <simpara>次のような構文エラーが出力される。</simpara> + <literallayout class="monospaced">20:1: syntax error, unexpected local variable or method, expecting `then' or ';' or '\n' + if true puts 'Hello, World!' end + ^~~~ + 20:1: syntax error, unexpected `end', expecting end-of-input + ...f true puts 'Hello, World!' end</literallayout> +<simpara>二つ目のメッセージは無視して一つ目を読むと、<literal>then</literal> か <literal>;</literal> + か改行が来るはずのところ変数だかメソッドだかが現れたことによりエラーとなっているようだ。</simpara> +<simpara>ポイントは改行が <literal>then</literal> (や <literal>;</literal>) の代わりとなることである。<literal>true</literal> + の後に改行を入れてみる。</simpara> +<programlisting language="ruby" linenumbering="unnumbered">if true +puts 'Hello, World!' end</programlisting> +<simpara>無事 Hello, World! と出力されるようになった。</simpara> +</section> +<section xml:id="_なぜ_then_や_や改行が必要か"> + <title>なぜ <literal>then</literal> や <literal>;</literal> や改行が必要か</title> + <simpara>なぜ <literal>then</literal> や <literal>;</literal> や改行 (以下 「<literal>then</literal> 等」) + が必要なのだろうか。次の例を見てほしい:</simpara> +<programlisting language="ruby" linenumbering="unnumbered">if a b end</programlisting> +<simpara><literal>then</literal> も <literal>;</literal> + も改行もないのでエラーになるが、これは条件式がどこまで続いているのかわからないためだ。 + この例は二通りに解釈できる。</simpara> +<programlisting language="ruby" linenumbering="unnumbered"># a という変数かメソッドの評価結果が truthy なら b という変数かメソッドを評価 +if a then +b +end</programlisting> +<programlisting language="ruby" linenumbering="unnumbered"># a というメソッドに b という変数かメソッドの評価結果を渡して呼び出し、 +# その結果が truthy なら何もしない +if a(b) then +end</programlisting> +<simpara><literal>then</literal> 等はこの曖昧性を排除するためにあり、条件式は <literal>if</literal> から <literal>then</literal> + 等までの間にある、ということを明確にする。 C系の <literal>if</literal> 後に来る <literal>(</literal>/<literal>)</literal> + や、Python の <literal>:</literal>、Rust/Go/Swift などの <literal>{</literal> も同じ役割を持つ。</simpara> +<simpara>Ruby の場合、プログラマーが書きやすいよう改行でもって <literal>then</literal> + が代用できるので、ほとんどの場合 <literal>then</literal> は必要ない。</simpara> +</section> +<section xml:id="_case_in_における_then"> + <title><literal>case</literal> - <literal>in</literal> における <literal>then</literal></title> + <simpara>ようやく本題にたどり着いた。来る Ruby 3.0 では <literal>case</literal> と <literal>in</literal> + キーワードを使ったパターンマッチングの構文が入る予定である。この構文でもパターン部との区切りとして + <literal>then</literal> 等が必要になる。 (現在の) Ruby には formal + な形式での文法仕様は存在しないので、yacc の定義ファイルを参照した (yacc + の説明は省略)。</simpara> + <simpara><link xl:href="https://github.com/ruby/ruby/blob/221ca0f8281d39f0dfdfe13b2448875384bbf735/parse.y#L3961-L3986">https://github.com/ruby/ruby/blob/221ca0f8281d39f0dfdfe13b2448875384bbf735/parse.y#L3961-L3986</link></simpara> + <programlisting language="yacc" linenumbering="unnumbered">p_case_body : keyword_in + { + SET_LEX_STATE(EXPR_BEG|EXPR_LABEL); + p->command_start = FALSE; + $<ctxt>1 = p->ctxt; + p->ctxt.in_kwarg = 1; + $<tbl>$ = push_pvtbl(p); + } + { + $<tbl>$ = push_pktbl(p); + } + p_top_expr then + { + pop_pktbl(p, $<tbl>3); + pop_pvtbl(p, $<tbl>2); + p->ctxt.in_kwarg = $<ctxt>1.in_kwarg; + } + compstmt + p_cases + { + /*%%%*/ + $$ = NEW_IN($4, $7, $8, &@$); + /*% %*/ + /*% ripper: in!($4, $7, escape_Qundef($8)) %*/ + } + ;</programlisting> +<simpara>簡略版:</simpara> +<programlisting language="yacc" linenumbering="unnumbered">p_case_body : keyword_in p_top_expr then compstmt p_cases +;</programlisting> +<simpara>ここで、<literal>keyword_in</literal> は文字通り <literal>in</literal>、<literal>p_top_expr</literal> + はいわゆるパターン、<literal>then</literal> は <literal>then</literal> + キーワードのことではなく、この記事で <literal>then</literal> 等と呼んでいるもの、つまり + <literal>then</literal> キーワード、<literal>;</literal>、改行のいずれかである。</simpara> +<simpara>これにより、<literal>case</literal> - <literal>when</literal> による従来の構文と同じように、<literal>then</literal> + 等をパターンの後ろに挿入すればよいことがわかった。つまり次の3通りのいずれかになる:</simpara> +<programlisting language="ruby" linenumbering="unnumbered">case x +in 1 then a +in 2 then b +in 3 then c +end + +case x +in 1 +a +in 2 +b +in 3 +c +end + +case x +in 1; a +in 2; b +in 3; c +end</programlisting> +<simpara>ところで、<literal>p_top_expr</literal> には <literal>if</literal> による guard clause +が書けるので、その場合は <literal>if</literal> - <literal>then</literal> と似たような見た目になる。</simpara> +<programlisting language="ruby" linenumbering="unnumbered">case x +in 0 then a +in n if n < 0 then b +in n then c +end</programlisting> +</section> +<section xml:id="_まとめ"> + <title>まとめ</title> + <itemizedlist> + <listitem> + <simpara><literal>if</literal> や <literal>case</literal> の条件の後ろには <literal>then</literal>、<literal>;</literal>、改行のいずれかが必要</simpara> + <itemizedlist> + <listitem> + <simpara>通常は改行しておけばよい</simpara> + </listitem> + </itemizedlist> + </listitem> + <listitem> + <simpara>3.0 で入る予定の <literal>case</literal> - <literal>in</literal> でも <literal>then</literal> 等が必要になる</simpara> + </listitem> + <listitem> + <simpara>Ruby の構文を正確に知るには (現状) <literal>parse.y</literal> を直接読めばよい</simpara> + </listitem> + </itemizedlist> +</section> +</article> diff --git a/content/posts/2021-10-02/rust-where-are-primitive-types-from.adoc b/content/posts/2021-10-02/rust-where-are-primitive-types-from.adoc deleted file mode 100644 index 8fc70b4..0000000 --- a/content/posts/2021-10-02/rust-where-are-primitive-types-from.adoc +++ /dev/null @@ -1,201 +0,0 @@ -= Rust のプリミティブ型はどこからやって来るか -:tags: rust -:description: Rust のプリミティブ型は予約語ではなく普通の識別子である。 \ - どのようにこれが名前解決されるのかを調べた。 -:revision-1: 2021-10-02 Qiita から移植 - -この記事は Qiita から移植してきたものです。 元 URL: -https://qiita.com/nsfisis/items/9a429432258bbcd6c565 - -''''' - -== 前置き - -Rust -において、プリミティブ型の名前は予約語でない。したがって、次のコードは合法である。 - -[source,rust] ----- -#![allow(non_camel_case_types)] -#![allow(dead_code)] - -struct bool; -struct char; -struct i8; -struct i16; -struct i32; -struct i64; -struct i128; -struct isize; -struct u8; -struct u16; -struct u32; -struct u64; -struct u128; -struct usize; -struct f32; -struct f64; -struct str; ----- - -では、普段単に `bool` と書いたとき、この `bool` -は一体どこから来ているのか。rustc のソースを追ってみた。 - -____ -前提知識: 一般的なコンパイラの構造、用語。`rustc` そのものの知識は不要 -(というよりも筆者自身がよく知らない) -____ - -== 調査 - -調査に使用したソース (調査時点での最新 master) - -https://github.com/rust-lang/rust/tree/511ed9f2356af365ad8affe046b3dd33f7ac3c98 - -どのようにして調べるか。rustc -の構造には詳しくないため、すぐに当たりをつけるのは難しい。 - -大雑把な構造としては、`compiler` フォルダ以下に `rustc_*` -という名前のクレートが数十個入っている。これがどうやら `rustc` -コマンドの実装部のようだ。 - -`rustc` はセルフホストされている (= `rustc` 自身が Rust で書かれている) -ので、`bool` や `char` -などで適当に検索をかけてもノイズが多すぎて話にならない。 -しかし、お誂え向きなことに `i128`/`u128` -というコンパイラ自身が使うことがなさそうな型が存在するのでこれを使って -`git grep` してみる。 - -.... -$ git grep "\bi128\b" | wc # i128 - 165 1069 15790 - -$ git grep "\bu128\b" | wc # u128 - 293 2127 26667 - -$ git grep "\bbool\b" | wc # cf. bool の結果 - 3563 23577 294659 -.... - -165 -程度であれば探すことができそうだ。今回は、クレート名を見ておおよその当たりをつけた。 - -.... -$ git grep "\bi128\b" -... -rustc_resolve/src/lib.rs: table.insert(sym::i128, Int(IntTy::I128)); -... -.... - -`rustc_resolve` -というのはいかにも名前解決を担いそうなクレート名である。該当箇所を見てみる。 - -[source,rust] ----- -/// Interns the names of the primitive types. -/// -/// All other types are defined somewhere and possibly imported, but the primitive ones need -/// special handling, since they have no place of origin. -struct PrimitiveTypeTable { - primitive_types: FxHashMap<Symbol, PrimTy>, -} - -impl PrimitiveTypeTable { - fn new() -> PrimitiveTypeTable { - let mut table = FxHashMap::default(); - - table.insert(sym::bool, Bool); - table.insert(sym::char, Char); - table.insert(sym::f32, Float(FloatTy::F32)); - table.insert(sym::f64, Float(FloatTy::F64)); - table.insert(sym::isize, Int(IntTy::Isize)); - table.insert(sym::i8, Int(IntTy::I8)); - table.insert(sym::i16, Int(IntTy::I16)); - table.insert(sym::i32, Int(IntTy::I32)); - table.insert(sym::i64, Int(IntTy::I64)); - table.insert(sym::i128, Int(IntTy::I128)); - table.insert(sym::str, Str); - table.insert(sym::usize, Uint(UintTy::Usize)); - table.insert(sym::u8, Uint(UintTy::U8)); - table.insert(sym::u16, Uint(UintTy::U16)); - table.insert(sym::u32, Uint(UintTy::U32)); - table.insert(sym::u64, Uint(UintTy::U64)); - table.insert(sym::u128, Uint(UintTy::U128)); - Self { primitive_types: table } - } -} ----- - -これは初めに列挙したプリミティブ型の一覧と一致している。doc comment -にも、 - -____ -All other types are defined somewhere and possibly imported, but the -primitive ones need special handling, since they have no place of -origin. -____ - -とある。次はこの struct -の使用箇所を追う。追うと言っても使われている箇所は次の一箇所しかない。なお説明に不要な箇所は大きく削っている。 - -[source,rust] ----- - /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope. - /// (略) - fn resolve_ident_in_lexical_scope( - &mut self, - mut ident: Ident, - ns: Namespace, - // (略) - ) -> Option<LexicalScopeBinding<'a>> { - // (略) - - if ns == TypeNS { - if let Some(prim_ty) = self.primitive_type_table.primitive_types.get(&ident.name) { - let binding = - (Res::PrimTy(*prim_ty), ty::Visibility::Public, DUMMY_SP, ExpnId::root()) - .to_name_binding(self.arenas); - return Some(LexicalScopeBinding::Item(binding)); - } - } - - None - } ----- - -関数名や doc comment が示している通り、この関数は識別子 (identifier, -ident) を現在のレキシカルスコープ内で解決 (resolve) する。 -`if ns == TypeNS` のブロック内では、`primitive_type_table` (上記の -`PrimitiveTypeTable::new()` で作られた変数) に含まれている識別子 -(`bool`、`i32` など) -かどうか判定し、そうであればそれに紐づけられたプリミティブ型を返している。 - -なお、`ns` は「名前空間」を示す変数である。Rust -における名前空間はC言語におけるそれとほとんど同じで、今探している名前が関数名/変数名なのか型なのかマクロなのかを区別している。この -`if` -は、プリミティブ型に解決されるのは型を探しているときだけだ、と言っている。 - -重要なのは、これが `resolve_ident_in_lexical_scope()` -の最後に書かれている点である。つまり、最初に挙げたプリミティブ型の識別子は、「名前解決の最終段階で」、「他に同名の型が見つかっていなければ」プリミティブ型として解決される。 - -動作がわかったところで、例として次のコードを考える。 - -[source,rust] ----- -#![allow(non_camel_case_types)] - -struct bool; - -fn main() { - let _: bool = bool; -} ----- - -ここで `main()` の `bool` は `struct bool` -として解決される。なぜなら、プリミティブ型の判定をする前に `bool` -という名前の別の型が見つかるからだ。 - -== まとめ - -Rust -のプリミティブ型は予約語ではない。名前解決の最終段階で特別扱いされ、他に同名の型が見つかっていなければ対応するプリミティブ型に解決される。 diff --git a/content/posts/2021-10-02/rust-where-are-primitive-types-from.xml b/content/posts/2021-10-02/rust-where-are-primitive-types-from.xml new file mode 100644 index 0000000..35ec0c8 --- /dev/null +++ b/content/posts/2021-10-02/rust-where-are-primitive-types-from.xml @@ -0,0 +1,174 @@ +<?xml version="1.0" encoding="UTF-8"?> +<article xmlns="http://docbook.org/ns/docbook" xmlns:xl="http://www.w3.org/1999/xlink" version="5.0"> + <info> + <title>Rust のプリミティブ型はどこからやって来るか</title> + <abstract> + Rust のプリミティブ型は予約語ではなく普通の識別子である。どのようにこれが名前解決されるのかを調べた。 + </abstract> + <keywordset> + <keyword>rust</keyword> + </keywordset> + <revhistory> + <revision> + <date>2021-10-02</date> + <revremark>Qiita から移植</revremark> + </revision> + </revhistory> + </info> + <simpara>この記事は Qiita から移植してきたものです。 元 URL: + <link xl:href="https://qiita.com/nsfisis/items/9a429432258bbcd6c565">https://qiita.com/nsfisis/items/9a429432258bbcd6c565</link></simpara> +<simpara><hr/></simpara> +<section xml:id="_前置き"> + <title>前置き</title> + <simpara>Rust + において、プリミティブ型の名前は予約語でない。したがって、次のコードは合法である。</simpara> +<programlisting language="rust" linenumbering="unnumbered">#![allow(non_camel_case_types)] +#![allow(dead_code)] + +struct bool; +struct char; +struct i8; +struct i16; +struct i32; +struct i64; +struct i128; +struct isize; +struct u8; +struct u16; +struct u32; +struct u64; +struct u128; +struct usize; +struct f32; +struct f64; +struct str;</programlisting> +<simpara>では、普段単に <literal>bool</literal> と書いたとき、この <literal>bool</literal> + は一体どこから来ているのか。rustc のソースを追ってみた。</simpara> +<blockquote> + <simpara>前提知識: 一般的なコンパイラの構造、用語。<literal>rustc</literal> そのものの知識は不要 + (というよりも筆者自身がよく知らない)</simpara> +</blockquote> +</section> +<section xml:id="_調査"> + <title>調査</title> + <simpara>調査に使用したソース (調査時点での最新 master)</simpara> + <simpara><link xl:href="https://github.com/rust-lang/rust/tree/511ed9f2356af365ad8affe046b3dd33f7ac3c98">https://github.com/rust-lang/rust/tree/511ed9f2356af365ad8affe046b3dd33f7ac3c98</link></simpara> + <simpara>どのようにして調べるか。rustc + の構造には詳しくないため、すぐに当たりをつけるのは難しい。</simpara> +<simpara>大雑把な構造としては、<literal>compiler</literal> フォルダ以下に <literal>rustc_*</literal> + という名前のクレートが数十個入っている。これがどうやら <literal>rustc</literal> + コマンドの実装部のようだ。</simpara> +<simpara><literal>rustc</literal> はセルフホストされている (= <literal>rustc</literal> 自身が Rust で書かれている) +ので、<literal>bool</literal> や <literal>char</literal> +などで適当に検索をかけてもノイズが多すぎて話にならない。 +しかし、お誂え向きなことに <literal>i128</literal>/<literal>u128</literal> +というコンパイラ自身が使うことがなさそうな型が存在するのでこれを使って +<literal>git grep</literal> してみる。</simpara> +<literallayout class="monospaced">$ git grep "\bi128\b" | wc # i128 +165 1069 15790 + +$ git grep "\bu128\b" | wc # u128 +293 2127 26667 + +$ git grep "\bbool\b" | wc # cf. bool の結果 +3563 23577 294659</literallayout> +<simpara>165 +程度であれば探すことができそうだ。今回は、クレート名を見ておおよその当たりをつけた。</simpara> +<literallayout class="monospaced">$ git grep "\bi128\b" +... +rustc_resolve/src/lib.rs: table.insert(sym::i128, Int(IntTy::I128)); +...</literallayout> +<simpara><literal>rustc_resolve</literal> + というのはいかにも名前解決を担いそうなクレート名である。該当箇所を見てみる。</simpara> +<programlisting language="rust" linenumbering="unnumbered">/// Interns the names of the primitive types. +/// +/// All other types are defined somewhere and possibly imported, but the primitive ones need +/// special handling, since they have no place of origin. +struct PrimitiveTypeTable { +primitive_types: FxHashMap<Symbol, PrimTy>, +} + +impl PrimitiveTypeTable { +fn new() -> PrimitiveTypeTable { +let mut table = FxHashMap::default(); + +table.insert(sym::bool, Bool); +table.insert(sym::char, Char); +table.insert(sym::f32, Float(FloatTy::F32)); +table.insert(sym::f64, Float(FloatTy::F64)); +table.insert(sym::isize, Int(IntTy::Isize)); +table.insert(sym::i8, Int(IntTy::I8)); +table.insert(sym::i16, Int(IntTy::I16)); +table.insert(sym::i32, Int(IntTy::I32)); +table.insert(sym::i64, Int(IntTy::I64)); +table.insert(sym::i128, Int(IntTy::I128)); +table.insert(sym::str, Str); +table.insert(sym::usize, Uint(UintTy::Usize)); +table.insert(sym::u8, Uint(UintTy::U8)); +table.insert(sym::u16, Uint(UintTy::U16)); +table.insert(sym::u32, Uint(UintTy::U32)); +table.insert(sym::u64, Uint(UintTy::U64)); +table.insert(sym::u128, Uint(UintTy::U128)); +Self { primitive_types: table } +} +}</programlisting> +<simpara>これは初めに列挙したプリミティブ型の一覧と一致している。doc comment +にも、</simpara> +<blockquote> + <simpara>All other types are defined somewhere and possibly imported, but the + primitive ones need special handling, since they have no place of + origin.</simpara> +</blockquote> +<simpara>とある。次はこの struct +の使用箇所を追う。追うと言っても使われている箇所は次の一箇所しかない。なお説明に不要な箇所は大きく削っている。</simpara> +<programlisting language="rust" linenumbering="unnumbered"> /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope. +/// (略) +fn resolve_ident_in_lexical_scope( +&mut self, +mut ident: Ident, +ns: Namespace, +// (略) +) -> Option<LexicalScopeBinding<'a>> { +// (略) + +if ns == TypeNS { +if let Some(prim_ty) = self.primitive_type_table.primitive_types.get(&ident.name) { +let binding = +(Res::PrimTy(*prim_ty), ty::Visibility::Public, DUMMY_SP, ExpnId::root()) +.to_name_binding(self.arenas); +return Some(LexicalScopeBinding::Item(binding)); +} +} + +None +}</programlisting> +<simpara>関数名や doc comment が示している通り、この関数は識別子 (identifier, +ident) を現在のレキシカルスコープ内で解決 (resolve) する。 +<literal>if ns == TypeNS</literal> のブロック内では、<literal>primitive_type_table</literal> (上記の +<literal>PrimitiveTypeTable::new()</literal> で作られた変数) に含まれている識別子 +(<literal>bool</literal>、<literal>i32</literal> など) +かどうか判定し、そうであればそれに紐づけられたプリミティブ型を返している。</simpara> +<simpara>なお、<literal>ns</literal> は「名前空間」を示す変数である。Rust +における名前空間はC言語におけるそれとほとんど同じで、今探している名前が関数名/変数名なのか型なのかマクロなのかを区別している。この +<literal>if</literal> +は、プリミティブ型に解決されるのは型を探しているときだけだ、と言っている。</simpara> +<simpara>重要なのは、これが <literal>resolve_ident_in_lexical_scope()</literal> + の最後に書かれている点である。つまり、最初に挙げたプリミティブ型の識別子は、「名前解決の最終段階で」、「他に同名の型が見つかっていなければ」プリミティブ型として解決される。</simpara> +<simpara>動作がわかったところで、例として次のコードを考える。</simpara> +<programlisting language="rust" linenumbering="unnumbered">#![allow(non_camel_case_types)] + +struct bool; + +fn main() { +let _: bool = bool; +}</programlisting> +<simpara>ここで <literal>main()</literal> の <literal>bool</literal> は <literal>struct bool</literal> + として解決される。なぜなら、プリミティブ型の判定をする前に <literal>bool</literal> + という名前の別の型が見つかるからだ。</simpara> +</section> +<section xml:id="_まとめ"> + <title>まとめ</title> + <simpara>Rust + のプリミティブ型は予約語ではない。名前解決の最終段階で特別扱いされ、他に同名の型が見つかっていなければ対応するプリミティブ型に解決される。</simpara> +</section> +</article> diff --git a/content/posts/2021-10-02/vim-difference-between-autocmd-bufwrite-and-bufwritepre.adoc b/content/posts/2021-10-02/vim-difference-between-autocmd-bufwrite-and-bufwritepre.adoc deleted file mode 100644 index 061e764..0000000 --- a/content/posts/2021-10-02/vim-difference-between-autocmd-bufwrite-and-bufwritepre.adoc +++ /dev/null @@ -1,120 +0,0 @@ -= [Vim] autocmd events の BufWrite/BufWritePre の違い -:tags: vim -:description: Vim の autocmd events における BufWrite/BufWritePre がどう違うのかを調べた結果、 \ - 違いはないことがわかった。 -:revision-1: 2021-10-02 Qiita から移植 - -この記事は Qiita から移植してきたものです。 元 URL: -https://qiita.com/nsfisis/items/79ab4db8564032de0b25 - -''''' - -== TL; DR - -違いはない。ただのエイリアス。 - -== 調査記録 - -Vim の autocmd events には似通った名前のものがいくつかある。大抵は -`:help` -に説明があるが、この記事のタイトルにある2つを含めた以下のイベントには、その違いについて説明がない。 - -* `BufRead`/`BufReadPost` -* `BufWrite`/`BufWritePre` -* `BufAdd`/`BufCreate` - -このうち、`BufAdd`/`BufCreate` に関しては、`:help BufCreate` に - -____ -The BufCreate event is for historic reasons. -____ - -とあり、おそらくは `BufAdd` -のエイリアスであろうということがわかる。他の2組も同様ではないかと予想されるが、確認のため -vim と neovim のソースコードを調査した。 - -____ -ソースコードへのリンク -https://github.com/vim/vim/tree/8e6be34338f13a6a625f19bcef82019c9adc65f2[vim -(調査時点での master branch)] -https://github.com/neovim/neovim/tree/71d4f5851f068eeb432af34850dddda8cc1c71e3[neovim -(上に同じ)] -____ - -=== vim のソースコード - -以下は、autocmd events -の名前と内部で使われている整数値とのマッピングを定義している箇所である。見ての通り、上でエイリアスではないかと述べた3組には、それぞれ同じ内部値が使われている。 - -https://github.com/vim/vim/blob/8e6be34338f13a6a625f19bcef82019c9adc65f2/src/autocmd.c#L85-L86 - -[source,c] ----- - {"BufAdd", EVENT_BUFADD}, - {"BufCreate", EVENT_BUFADD}, ----- - -https://github.com/vim/vim/blob/8e6be34338f13a6a625f19bcef82019c9adc65f2/src/autocmd.c#L95-L97 - -[source,c] ----- - {"BufRead", EVENT_BUFREADPOST}, - {"BufReadCmd", EVENT_BUFREADCMD}, - {"BufReadPost", EVENT_BUFREADPOST}, ----- - -https://github.com/vim/vim/blob/8e6be34338f13a6a625f19bcef82019c9adc65f2/src/autocmd.c#L103-L105 - -[source,c] ----- - {"BufWrite", EVENT_BUFWRITEPRE}, - {"BufWritePost", EVENT_BUFWRITEPOST}, - {"BufWritePre", EVENT_BUFWRITEPRE}, ----- - -=== neovim のソースコード - -neovim の場合でも同様のマッピングが定義されているが、こちらの場合は Lua -で書かれている。以下にある通り、はっきり `aliases` と書かれている。 - -https://github.com/neovim/neovim/blob/71d4f5851f068eeb432af34850dddda8cc1c71e3/src/nvim/auevents.lua#L119-L124 - -[source,lua] ----- - aliases = { - BufCreate = 'BufAdd', - BufRead = 'BufReadPost', - BufWrite = 'BufWritePre', - FileEncoding = 'EncodingChanged', - }, ----- - -ところで、上では取り上げなかった `FileEncoding` だが、これは -`:help FileEncoding` にしっかりと書いてある。 - -.... - *FileEncoding* -FileEncoding Obsolete. It still works and is equivalent - to |EncodingChanged|. -.... - -=== まとめ - -記事タイトルについて言えば、どちらも変わらないので好きな方を使えばよい。あえて言えば、次のようになるだろう。 - -* `BufAdd`/`BufCreate` -** → `BufCreate` は歴史的な理由により (``for historic reasons'') -存在しているため、新しい方 (`BufAdd`) を使う -* `BufRead`/`BufReadPost` -** → `BufReadPre` との対称性のため、あるいは `BufWritePost` -との対称性のため `BufReadPost` を使う -* `BufWrite`/`BufWritePre` -** → `BufWritePost` との対称性のため、あるいは `BufReadPre` -との対称性のため `BufWritePre` を使う -* `FileEncoding`/`EncodingChanged` -** → `FileEncoding` は ``Obsolete'' -と明言されているので、`EncodingChanged` を使う - -ところでこの調査で知ったのだが、`BufRead` と `BufWrite` -は上にある通り発火するタイミングが「後」と「前」で対称性がない。可能なら -`Pre`/`Post` 付きのものを使った方が分かりやすいだろう。 diff --git a/content/posts/2021-10-02/vim-difference-between-autocmd-bufwrite-and-bufwritepre.xml b/content/posts/2021-10-02/vim-difference-between-autocmd-bufwrite-and-bufwritepre.xml new file mode 100644 index 0000000..ed7f03f --- /dev/null +++ b/content/posts/2021-10-02/vim-difference-between-autocmd-bufwrite-and-bufwritepre.xml @@ -0,0 +1,134 @@ +<?xml version="1.0" encoding="UTF-8"?> +<article xmlns="http://docbook.org/ns/docbook" xmlns:xl="http://www.w3.org/1999/xlink" version="5.0"> + <info> + <title>【Vim】 autocmd events の BufWrite/BufWritePre の違い</title> + <abstract> + Vim の autocmd events における BufWrite/BufWritePre がどう違うのかを調べた結果、違いはないことがわかった。 + </abstract> + <keywordset> + <keyword>vim</keyword> + </keywordset> + <revhistory> + <revision> + <date>2021-10-02</date> + <revremark>Qiita から移植</revremark> + </revision> + </revhistory> + </info> + <simpara>この記事は Qiita から移植してきたものです。 元 URL: + <link xl:href="https://qiita.com/nsfisis/items/79ab4db8564032de0b25">https://qiita.com/nsfisis/items/79ab4db8564032de0b25</link></simpara> +<simpara><hr/></simpara> +<section xml:id="_tl_dr"> + <title>TL; DR</title> + <simpara>違いはない。ただのエイリアス。</simpara> +</section> +<section xml:id="_調査記録"> + <title>調査記録</title> + <simpara>Vim の autocmd events には似通った名前のものがいくつかある。大抵は + <literal>:help</literal> + に説明があるが、この記事のタイトルにある2つを含めた以下のイベントには、その違いについて説明がない。</simpara> +<itemizedlist> + <listitem> + <simpara><literal>BufRead</literal>/<literal>BufReadPost</literal></simpara> + </listitem> + <listitem> + <simpara><literal>BufWrite</literal>/<literal>BufWritePre</literal></simpara> + </listitem> + <listitem> + <simpara><literal>BufAdd</literal>/<literal>BufCreate</literal></simpara> + </listitem> +</itemizedlist> +<simpara>このうち、<literal>BufAdd</literal>/<literal>BufCreate</literal> に関しては、<literal>:help BufCreate</literal> に</simpara> +<blockquote> + <simpara>The BufCreate event is for historic reasons.</simpara> +</blockquote> +<simpara>とあり、おそらくは <literal>BufAdd</literal> + のエイリアスであろうということがわかる。他の2組も同様ではないかと予想されるが、確認のため + vim と neovim のソースコードを調査した。</simpara> +<blockquote> + <simpara>ソースコードへのリンク + <link xl:href="https://github.com/vim/vim/tree/8e6be34338f13a6a625f19bcef82019c9adc65f2">vim + (調査時点での master branch)</link> +<link xl:href="https://github.com/neovim/neovim/tree/71d4f5851f068eeb432af34850dddda8cc1c71e3">neovim +(上に同じ)</link></simpara> +</blockquote> +<section xml:id="_vim_のソースコード"> + <title>vim のソースコード</title> + <simpara>以下は、autocmd events + の名前と内部で使われている整数値とのマッピングを定義している箇所である。見ての通り、上でエイリアスではないかと述べた3組には、それぞれ同じ内部値が使われている。</simpara> +<simpara><link xl:href="https://github.com/vim/vim/blob/8e6be34338f13a6a625f19bcef82019c9adc65f2/src/autocmd.c#L85-L86">https://github.com/vim/vim/blob/8e6be34338f13a6a625f19bcef82019c9adc65f2/src/autocmd.c#L85-L86</link></simpara> +<programlisting language="c" linenumbering="unnumbered"> {"BufAdd", EVENT_BUFADD}, +{"BufCreate", EVENT_BUFADD},</programlisting> +<simpara><link xl:href="https://github.com/vim/vim/blob/8e6be34338f13a6a625f19bcef82019c9adc65f2/src/autocmd.c#L95-L97">https://github.com/vim/vim/blob/8e6be34338f13a6a625f19bcef82019c9adc65f2/src/autocmd.c#L95-L97</link></simpara> +<programlisting language="c" linenumbering="unnumbered"> {"BufRead", EVENT_BUFREADPOST}, +{"BufReadCmd", EVENT_BUFREADCMD}, +{"BufReadPost", EVENT_BUFREADPOST},</programlisting> +<simpara><link xl:href="https://github.com/vim/vim/blob/8e6be34338f13a6a625f19bcef82019c9adc65f2/src/autocmd.c#L103-L105">https://github.com/vim/vim/blob/8e6be34338f13a6a625f19bcef82019c9adc65f2/src/autocmd.c#L103-L105</link></simpara> +<programlisting language="c" linenumbering="unnumbered"> {"BufWrite", EVENT_BUFWRITEPRE}, +{"BufWritePost", EVENT_BUFWRITEPOST}, +{"BufWritePre", EVENT_BUFWRITEPRE},</programlisting> +</section> +<section xml:id="_neovim_のソースコード"> + <title>neovim のソースコード</title> + <simpara>neovim の場合でも同様のマッピングが定義されているが、こちらの場合は Lua + で書かれている。以下にある通り、はっきり <literal>aliases</literal> と書かれている。</simpara> +<simpara><link xl:href="https://github.com/neovim/neovim/blob/71d4f5851f068eeb432af34850dddda8cc1c71e3/src/nvim/auevents.lua#L119-L124">https://github.com/neovim/neovim/blob/71d4f5851f068eeb432af34850dddda8cc1c71e3/src/nvim/auevents.lua#L119-L124</link></simpara> +<programlisting language="lua" linenumbering="unnumbered"> aliases = { +BufCreate = 'BufAdd', +BufRead = 'BufReadPost', +BufWrite = 'BufWritePre', +FileEncoding = 'EncodingChanged', +},</programlisting> +<simpara>ところで、上では取り上げなかった <literal>FileEncoding</literal> だが、これは +<literal>:help FileEncoding</literal> にしっかりと書いてある。</simpara> +<literallayout class="monospaced"> *FileEncoding* +FileEncoding Obsolete. It still works and is equivalent +to |EncodingChanged|.</literallayout> +</section> +<section xml:id="_まとめ"> + <title>まとめ</title> + <simpara>記事タイトルについて言えば、どちらも変わらないので好きな方を使えばよい。あえて言えば、次のようになるだろう。</simpara> + <itemizedlist> + <listitem> + <simpara><literal>BufAdd</literal>/<literal>BufCreate</literal></simpara> + <itemizedlist> + <listitem> + <simpara>→ <literal>BufCreate</literal> は歴史的な理由により (<literal>`for historic reasons'') + 存在しているため、新しい方 (`BufAdd</literal>) を使う</simpara> + </listitem> + </itemizedlist> +</listitem> +<listitem> + <simpara><literal>BufRead</literal>/<literal>BufReadPost</literal></simpara> + <itemizedlist> + <listitem> + <simpara>→ <literal>BufReadPre</literal> との対称性のため、あるいは <literal>BufWritePost</literal> + との対称性のため <literal>BufReadPost</literal> を使う</simpara> + </listitem> + </itemizedlist> +</listitem> +<listitem> + <simpara><literal>BufWrite</literal>/<literal>BufWritePre</literal></simpara> + <itemizedlist> + <listitem> + <simpara>→ <literal>BufWritePost</literal> との対称性のため、あるいは <literal>BufReadPre</literal> + との対称性のため <literal>BufWritePre</literal> を使う</simpara> + </listitem> + </itemizedlist> +</listitem> +<listitem> + <simpara><literal>FileEncoding</literal>/<literal>EncodingChanged</literal></simpara> + <itemizedlist> + <listitem> + <simpara>→ <literal>FileEncoding</literal> は <literal>`Obsolete'' + と明言されているので、`EncodingChanged</literal> を使う</simpara> +</listitem> +</itemizedlist> +</listitem> +</itemizedlist> +<simpara>ところでこの調査で知ったのだが、<literal>BufRead</literal> と <literal>BufWrite</literal> + は上にある通り発火するタイミングが「後」と「前」で対称性がない。可能なら + <literal>Pre</literal>/<literal>Post</literal> 付きのものを使った方が分かりやすいだろう。</simpara> +</section> +</section> +</article> diff --git a/content/posts/2021-10-02/vim-swap-order-of-selected-lines.adoc b/content/posts/2021-10-02/vim-swap-order-of-selected-lines.adoc deleted file mode 100644 index b937625..0000000 --- a/content/posts/2021-10-02/vim-swap-order-of-selected-lines.adoc +++ /dev/null @@ -1,165 +0,0 @@ -= Vimで選択した行の順番を入れ替える -:tags: vim -:description: Vim で選択した行の順番を入れ替える方法。 -:revision-1: 2021-10-02 Qiita から移植 - -この記事は Qiita から移植してきたものです。 元 URL: -https://qiita.com/nsfisis/items/4fefb361d9a693803520 - -''''' - -== バージョン情報 - -`:version` の一部 - -____ -VIM - Vi IMproved 8.2 (2019 Dec 12, compiled Jan 26 2020 11:30:30) macOS -version Included patches: 1-148 Huge version without GUI. -____ - -== よく紹介されている手法 - -=== `tac` / `tail` - -`tac` や `tail -r` などの外部コマンドを `!` -を使って呼び出し、置き換える。 - -____ -:h v_! -____ - -`tac` コマンドや `tail` の `-r` -オプションは環境によって利用できないことがあり、複数の環境を行き来する場合に採用しづらい - -=== `:g/^/m0` - -こちらは外部コマンドに頼らず、Vim の機能のみを使う。`g` は `:global` -コマンドの、`m` は `:move` コマンドの略 - -`:global` コマンドは `:[range]global/{pattern}/[command]` -のように使い、`[range]` で指定された範囲の行のうち、`{pattern}` -で指定された検索パターンにマッチする行に対して、順番に `[command]` -で指定された Ex コマンドを呼び出す。 - -____ -:h :global -____ - -`:move` コマンドは `[range]:move {address}` のように使い、`[range]` -で指定された範囲の行を `{address}` で指定された位置に移動させる。 - -____ -:h :move -____ - -`:g/^/m0` のように組み合わせると、「すべての行を1行ずつ -0行目(1行目の上)に動かす」という動きをする。これは確かに行の入れ替えになっている。 - -なお、`:g/^/m0` は全ての行を入れ替えるが、`:N,Mg/^/mN-1` とすることで -N行目から -M行目を処理範囲とするよう拡張できる。手でこれを入力するわけにはいかないので、次のようなコマンドを用意する。 - -[source,vim] ----- -command! -bar -range=% - \ Reverse - \ <line1>,<line2>g/^/m<line1>-1 ----- - -これは望みの動作をするが、実際に実行してみると全行がハイライトされてしまう。次節で詳細を述べる。 - -== `:g/^/m0` の問題点 - -`:global` -コマンドは各行に対してマッチングを行う際、現在の検索パターンを上書きしてしまう。`^` -は行の先頭にマッチするため、結果として全ての行がハイライトされてしまう。`'hlsearch'` -オプションを無効にしている場合その限りではないが、その場合でも直前の検索パターンが失われてしまうと -`n` コマンドなどの際に不便である。 - -____ -:h @/ -____ - -== 解決策 - -____ -[2020/9/28追記] より簡潔な方法を見つけたので次節に追記した -____ - -前述した `:Reverse` コマンドの定義を少し変えて、次のようにする: - -[source,vim] ----- -function! s:reverse_lines(from, to) abort - execute printf("%d,%dg/^/m%d", a:from, a:to, a:from - 1) -endfunction - -command! -bar -range=% - \ Reverse - \ call <SID>reverse_lines(<line1>, <line2>) ----- - -実行しているコマンドが変わったわけではないが、関数呼び出しを経由するようにした。これだけで前述の問題が解決する。 - -この理由は、ユーザー定義関数を実行する際は検索パターンが一度保存され、実行が終了したあと復元されるため。結果として検索パターンが -`^` で上書きされることがなくなる。 - -Vim のヘルプから該当箇所を引用する (強調は筆者による)。 - -____ -:h autocmd-searchpat - -*Autocommands do not change the current search patterns.* Vim saves the -current search patterns before executing autocommands then restores them -after the autocommands finish. This means that autocommands do not -affect the strings highlighted with the `hlsearch' option. -____ - -これは autocommand -の実行に関しての記述だが、これと同じことがユーザー定義関数の実行時にも適用される。このことは -`:nohlsearch` のヘルプにある。同じく該当箇所を引用する -(強調は筆者による)。 - -____ -:h :nohlsearch - -(略) This command doesn’t work in an autocommand, because the -highlighting state is saved and restored when executing autocommands -|autocmd-searchpat|. *Same thing for when invoking a user function.* -____ - -この仕様により、`:g/^/m0` -の呼び出しをユーザー定義関数に切り出すことで上述の問題を解決できる。 - -== 解決策 (改訂版) - -____ -[2020/9/28追記] より簡潔な方法を見つけたため追記する -____ - -[source,vim] ----- -command! -bar -range=% - \ Reverse - \ keeppatterns <line1>,<line2>g/^/m<line1>-1 ----- - -まさにこのための Exコマンド、`:keeppatterns` -が存在する。`:keeppatterns {command}` -のように使い、読んで字の如く、後ろに続く -Exコマンドを「現在の検索パターンを保ったまま」実行する。はるかに分かりやすく意図を表現できる。 - -____ -:h :keeppatterns -____ - -== コピペ用再掲 - -[source,vim] ----- -" License: Public Domain - -command! -bar -range=% - \ Reverse - \ keeppatterns <line1>,<line2>g/^/m<line1>-1 ----- diff --git a/content/posts/2021-10-02/vim-swap-order-of-selected-lines.xml b/content/posts/2021-10-02/vim-swap-order-of-selected-lines.xml new file mode 100644 index 0000000..9b7c809 --- /dev/null +++ b/content/posts/2021-10-02/vim-swap-order-of-selected-lines.xml @@ -0,0 +1,140 @@ +<?xml version="1.0" encoding="UTF-8"?> +<article xmlns="http://docbook.org/ns/docbook" xmlns:xl="http://www.w3.org/1999/xlink" version="5.0"> + <info> + <title>Vimで選択した行の順番を入れ替える</title> + <abstract> + Vim で選択した行の順番を入れ替える方法。 + </abstract> + <keywordset> + <keyword>vim</keyword> + </keywordset> + <revhistory> + <revision> + <date>2021-10-02</date> + <revremark>Qiita から移植</revremark> + </revision> + </revhistory> + </info> + <simpara>この記事は Qiita から移植してきたものです。 元 URL: + <link xl:href="https://qiita.com/nsfisis/items/4fefb361d9a693803520">https://qiita.com/nsfisis/items/4fefb361d9a693803520</link></simpara> +<simpara><hr/></simpara> +<section xml:id="_バージョン情報"> + <title>バージョン情報</title> + <simpara><literal>:version</literal> の一部</simpara> + <blockquote> + <simpara>VIM - Vi IMproved 8.2 (2019 Dec 12, compiled Jan 26 2020 11:30:30) macOS + version Included patches: 1-148 Huge version without GUI.</simpara> +</blockquote> +</section> +<section xml:id="_よく紹介されている手法"> + <title>よく紹介されている手法</title> + <section xml:id="_tac_tail"> + <title><literal>tac</literal> / <literal>tail</literal></title> + <simpara><literal>tac</literal> や <literal>tail -r</literal> などの外部コマンドを <literal>!</literal> + を使って呼び出し、置き換える。</simpara> + <blockquote> + <simpara>:h v_!</simpara> + </blockquote> + <simpara><literal>tac</literal> コマンドや <literal>tail</literal> の <literal>-r</literal> + オプションは環境によって利用できないことがあり、複数の環境を行き来する場合に採用しづらい</simpara> + </section> + <section xml:id="_gm0"> + <title><literal>:g/^/m0</literal></title> + <simpara>こちらは外部コマンドに頼らず、Vim の機能のみを使う。<literal>g</literal> は <literal>:global</literal> + コマンドの、<literal>m</literal> は <literal>:move</literal> コマンドの略</simpara> + <simpara><literal>:global</literal> コマンドは <literal>:[range]global/{pattern}/[command]</literal> + のように使い、<literal>[range]</literal> で指定された範囲の行のうち、<literal>{pattern}</literal> + で指定された検索パターンにマッチする行に対して、順番に <literal>[command]</literal> + で指定された Ex コマンドを呼び出す。</simpara> + <blockquote> + <simpara>:h :global</simpara> + </blockquote> + <simpara><literal>:move</literal> コマンドは <literal>[range]:move {address}</literal> のように使い、<literal>[range]</literal> + で指定された範囲の行を <literal>{address}</literal> で指定された位置に移動させる。</simpara> + <blockquote> + <simpara>:h :move</simpara> + </blockquote> + <simpara><literal>:g/^/m0</literal> のように組み合わせると、「すべての行を1行ずつ + 0行目(1行目の上)に動かす」という動きをする。これは確かに行の入れ替えになっている。</simpara> + <simpara>なお、<literal>:g/^/m0</literal> は全ての行を入れ替えるが、<literal>:N,Mg/^/mN-1</literal> とすることで + N行目から + M行目を処理範囲とするよう拡張できる。手でこれを入力するわけにはいかないので、次のようなコマンドを用意する。</simpara> +<programlisting language="vim" linenumbering="unnumbered">command! -bar -range=% +\ Reverse +\ <line1>,<line2>g/^/m<line1>-1</programlisting> +<simpara>これは望みの動作をするが、実際に実行してみると全行がハイライトされてしまう。次節で詳細を述べる。</simpara> +</section> +</section> +<section xml:id="_gm0_の問題点"> + <title><literal>:g/^/m0</literal> の問題点</title> + <simpara><literal>:global</literal> + コマンドは各行に対してマッチングを行う際、現在の検索パターンを上書きしてしまう。<literal>^</literal> + は行の先頭にマッチするため、結果として全ての行がハイライトされてしまう。<literal>'hlsearch'</literal> + オプションを無効にしている場合その限りではないが、その場合でも直前の検索パターンが失われてしまうと + <literal>n</literal> コマンドなどの際に不便である。</simpara> + <blockquote> + <simpara>:h @/</simpara> + </blockquote> +</section> +<section xml:id="_解決策"> + <title>解決策</title> + <blockquote> + <simpara>[2020/9/28追記] より簡潔な方法を見つけたので次節に追記した</simpara> + </blockquote> + <simpara>前述した <literal>:Reverse</literal> コマンドの定義を少し変えて、次のようにする:</simpara> + <programlisting language="vim" linenumbering="unnumbered">function! s:reverse_lines(from, to) abort + execute printf("%d,%dg/^/m%d", a:from, a:to, a:from - 1) + endfunction + + command! -bar -range=% + \ Reverse + \ call <SID>reverse_lines(<line1>, <line2>)</programlisting> +<simpara>実行しているコマンドが変わったわけではないが、関数呼び出しを経由するようにした。これだけで前述の問題が解決する。</simpara> +<simpara>この理由は、ユーザー定義関数を実行する際は検索パターンが一度保存され、実行が終了したあと復元されるため。結果として検索パターンが +<literal>^</literal> で上書きされることがなくなる。</simpara> +<simpara>Vim のヘルプから該当箇所を引用する (強調は筆者による)。</simpara> +<blockquote> + <simpara>:h autocmd-searchpat</simpara> + <simpara><emphasis role="strong">Autocommands do not change the current search patterns.</emphasis> Vim saves the + current search patterns before executing autocommands then restores them + after the autocommands finish. This means that autocommands do not + affect the strings highlighted with the `hlsearch' option.</simpara> +</blockquote> +<simpara>これは autocommand +の実行に関しての記述だが、これと同じことがユーザー定義関数の実行時にも適用される。このことは +<literal>:nohlsearch</literal> のヘルプにある。同じく該当箇所を引用する +(強調は筆者による)。</simpara> +<blockquote> + <simpara>:h :nohlsearch</simpara> + <simpara>(略) This command doesn’t work in an autocommand, because the + highlighting state is saved and restored when executing autocommands + |autocmd-searchpat|. <emphasis role="strong">Same thing for when invoking a user function.</emphasis></simpara> +</blockquote> +<simpara>この仕様により、<literal>:g/^/m0</literal> + の呼び出しをユーザー定義関数に切り出すことで上述の問題を解決できる。</simpara> +</section> +<section xml:id="_解決策_改訂版"> + <title>解決策 (改訂版)</title> + <blockquote> + <simpara>[2020/9/28追記] より簡潔な方法を見つけたため追記する</simpara> + </blockquote> + <programlisting language="vim" linenumbering="unnumbered">command! -bar -range=% + \ Reverse + \ keeppatterns <line1>,<line2>g/^/m<line1>-1</programlisting> +<simpara>まさにこのための Exコマンド、<literal>:keeppatterns</literal> + が存在する。<literal>:keeppatterns {command}</literal> + のように使い、読んで字の如く、後ろに続く + Exコマンドを「現在の検索パターンを保ったまま」実行する。はるかに分かりやすく意図を表現できる。</simpara> +<blockquote> + <simpara>:h :keeppatterns</simpara> +</blockquote> +</section> +<section xml:id="_コピペ用再掲"> + <title>コピペ用再掲</title> + <programlisting language="vim" linenumbering="unnumbered">" License: Public Domain + + command! -bar -range=% + \ Reverse + \ keeppatterns <line1>,<line2>g/^/m<line1>-1</programlisting> +</section> +</article> |
