2018年3月5日月曜日

My original programming language, Expresso -- Explaining the core

Hi, this is HAZAMA. And this is the second entry to Expresso.

First of all, I'll explain several features that stand out.
First, Expresso supports vectors and dictionaries as builtin types. They can be written in literal forms and the compiler treats them as special types(although they are compiled to System.Collections.Generic.List and System.Collections.Generic.Dictionary respectively). But patterns don't support them yet because of the problems of the implementation.
Second, Expresso supports the intseq type, which is short for "integer sequence" and is a generator for integers like the xrange type in Python or the Range type in Rust. Unfortunately, even though it only handles 32 bit integers, it will be frequently used for counting up in for loops because Expresso doesn't support the traditional for loops as in C. If you index into vectors or arrays with an intseq, it will produce an iterator(in .NET terms it will be called an enumerator) that yields elements that match to the integer sequence, which is called a slice.
Third, Expresso also supports match statements like Rust. This construct pattern-matches against values and destructures objects and matches against literal values. Even though it will only match to tuple patterns, the variable declaration statements also now support pattern matches.
Oh, though I forgot to mention this, you can omit the parameters types and the return type in closures if they are obvious like the closures will be passed to functions or methods directly. This implementation expects that writing chains of methods is easy when in the future the methods in System.Linq.Enumerable can be called but I'm being hesitated to implement extension methods. I doubt that it will result in having to iterate through every type defined whenever a new type is defined.

Now that we know the features of Expresso that stand out, let's look at how Expresso works next. Currently the compiler is entirely made in C#. The lexer, the parser, the analyzer and the code generator are all written in C# at present. The binary the compiler will output is in the IL code, and the parser generator is also written in C#. These are the reasons why I chose C# for the language that the compiler is written in(you only need to generate expression trees in order to generate some data that can be executed). I'm keen to implement the compiler in Expresso, but there are a lot of problems that should be solved like how I can split the parser and the analyzer and assume we will use the parser that is written in C#, because the parser and the analyzer are the part that can't be separated, then what will be left is the code generator and so that will make no difference in how the compiler is written. In addition, how I can implement the intseq and the slice type is also a problem when I will write the compiler in Expresso. The intseq type is compiled to the ExpressoIntegerSequence type and doing so is made easy by the feature of the C# compiler so if I will implement it in Expresso, then I should also fully implement the ExpressoIntegerSequence without the convenient C# compiler's feature(This feature transforms the source code into a state machine. So it would be no problem if I know how the compiler transforms the source code).
Even though there are some problems, because the code generation is fairy easy, there is a parser generator and it runs on multiple platforms by default, I can say C# is the language for writing a compiler. If you are interested in creating your own programming language, I recommend you to start by implementing a LISP interpreter rather than recommending you to start by implementing a new language in the first place, for example. After you do that, you can easily see what the parser, the lexer and the interpreter are doing.
Next onto the grammar, it is not currently available in printed format or something similar so if you need to know which construct creates what object, see the Coco parser specification. Of the specifications there are ones that don't work at present because they are not implemented yet(namely, the comprehension and interfaces). If you need to grasp a bit of the grammar, see the files under cloned_directory/ExpressoTest/sources/. Of those files there are ones that the parser can't recognize but you will find what the grammar is like.
For documentations, I'm writing them in Markdown in English only. They are located in cloned_directory/Expresso/Documentation/.
And this wraps up the entry. I'll write another entry if I have more informations to share. See you again ;)

2018年3月2日金曜日

My original programming language, Expresso -- Introduction

Hi, I'm HAZAMA. This is the first entry in this blog written in English. This is the introduction to my original programming language, Expresso.
First of all, what do you really want to finish as a programmer in your whole life? I guess and wish it's a programming language.

Expresso first originated about 4, 5 years ago, and it now supports try, catch statements and it would accomplish many tasks so I've decided to release it as an alpha version. But I won't yet publish any official web sites or something.
The language name, Expresso, was coined as a mixture of "expressive" and "Espresso", meaning that it's highly expressive and it would be an easy-to-write programming language. There is a slogan as well saying that "Easy for beginners, elegant for enthusiasts". This slogan deliberately contains a lot of "e"s on the heads of words, meaning "Seeking for good things" in Japanese. That is, "e wo sagasu gengo". The pronunciation of e is the same as that of a Japanese word for "good". So it's just a pun in Japanese.
Expresso would aim to be an educational programming language if it gets spread over the world. So the slogan is shouted. In other words, Expresso is going to be an easy-to-write programming language for beginners and yet it is going to be an expressive programming language for enthusiasts.
You might be wondering why it aims to be a programming language for education. Here is the answer: I learned Pascal when I was a university student and it was an old-fashoned language. And Wikipedia says it is a programming language for education(only in Japanese and as of writing this entry. The English version says "a language intended to encourage good programming practices using structured programming and data structuring", though). That's why I made my original programming language a language for education. Yes, I admit that Expresso won't be faster than Rust.

Its specification, which is vague about many things currently, is a type-strict and object-oriented programming language. Because Rust has a big influence on Expresso, it also has a lot of features from Rust.
Currently Expresso runs on .NET environment only. The reasons for this are that you can rather easily set up a .NET environment and that it runs on multiple platforms. Oh yeah, I like C# the most.

Before covering the traditional Hello world program in Expresso, we'll look at how to set up an Expresso environment. Above all, git clone the repository from Github because we have no official web sites. Then run "git submodule update --init".  The dependencies will be resolved. And then make a directory named "test_executables" on cloned_directory/ExpressoTest/. Because binaries will be created on this directory when tested, it won't get run if it is missing. I guess I want to add this directory to the git repository.
Apr. 7 2018 added: Then, build the InteroperabilityTest project and move the resulting dll file to /ExpressoTest/sources/for_unit_tests.
After that, if you are a Mac or Linux user, then you should now be able to open up the solution file in your IDE and build and run the solution(Note that you may have to change your IDE settings so that it automatically download missing projects with NuGet because it now uses NuGet to download a dependency project). If you are a Windows user, then you must get Coco. And probably you should write a batch file that automatically build the parser with Coco. After downloading Coco from Coco/R for C# section in the above web site, put it in cloned_directory/Expresso/. The Expresso project contains the core source files that powers Expresso. After that, write a batch file similar to cloned_directory/Expresso/parserCompile.sh. It would be better to modify the project setting to automatically run the batch file because then it can automatically generate and compile the parser when you running the build command.
Even though I have said a lot about setting up on Windows, I won't guarantee that it runs on Windows. So I recommend you to use Mac + Visual Studio or Linux + Xamarin Studio(I used the latter and am using the former now)(Apr. 7 2018 added: I found that the EmitterTests don't run on Windows because Mono on Mac and .NET on Windows provide different implementations.)(Apr. 8 2018 added: Now most of the EmitterTests run on Windows. But there are still some tests that issue errors I can't resolve).

OK, enough with pre-execution or something:) Now let's get on a real program, the hello world program.

module main;
def main()
{
    println("Hello, world!");
}

Let's execute an Expresso program before inspecting it. Build the ExpressoConsole project and run mono exsc.exe hello_world.exs -o ./ -e hello_world. Then it should compile the source file to main.exe and to run the executable, you need to have Expresso.dll and ExpressoRuntime.dll in the current directory. So copy them first and then run mono hello_world.exe to actually executing the Expresso program. Do you see "Hello, world!" text on the console? You made it! You've successfully compiled and run an Expresso program!

In Expresso, one file corresponds to one module like Python. Every module has to be explicitly named. The program's entry point will be the main function. At present the main function takes no parameters and returns nothing(you can write those but they will be simply ignored)(Apr. 11 2018 added: now the main function should take an args parameter and be able to return an int.).
As you can see, functions and methods are defined with the def keyword. I think it is a keyword in Python and Ruby, but it is strange to use some keyword derived from "function" like Rust in Expresso. Rust has trait objects but doesn't have objects themselves so it is fine in Rust.
Even though it doesn't appear in this example, names precede types. The (- sign separates the name and the type. This sign is unique to Expresso(it should be), derived from the mathematical ∈ sign. It is a 2 type-strokes sign because of the idea of not wanting programmers to explicitly write the types of variables as much as possible.
If you need to explicitly write the return type of a method or a function, you use -> sign as in Rust. Because the return types of methods or functions will be inferred from their bodies, you can omit them(In fact in the above code, the return type will be void).
The println function that the main function calls is a builtin one, which calls Console.WriteLine method and therefore takes a variable number of parameters and prints them out separated with commas. There are the print function which doesn't put a new line at the end, and the printFormat function which takes a format string as the first parameter that Console.WriteLine takes(Apr. 11 2018 added: now it is unsupported because I implemented string interpolation).

This finishes the introduction. In the next entry, we'll examine the features and how Expresso works.

2018年2月26日月曜日

interfaceを動的に継承する方法

どうも、こんにちは、はざまです。今回は需要があるかどうかわかりませんが久しぶりに単独の技術ネタを書こうかなと思います。
先日の記事で私が自作言語を作っていることは周知のことかと思いますが、そのコードを書いている際にある問題に出くわしました。Interfaceの実装問題です。C#にはTypeBuilderというクラスがあり、これを使えば、型(interfaceもclassもstructも)を定義できるはずなのですが、なぜかinterfaceを実装するclassを定義しようとしてもうまくいかない。MSDNのTypeBuilder.AddInterfaceImplemetationメソッドの例の通りに書いているのにうまくいかない、なんでだろうと1週間以上試行錯誤を経てたどり着いた結果が、生成したクラスがobjectを継承していないことでした。つまり、C#でinterfaceを継承した型を動的に生成する最小のコードは、以下のような感じになるでしょう。
using System;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;

namespace Test
{
    class Main
    {
        public static void Main(string[] args)
        {
            var name = new AssemblyName("test");
            var asm_builder = Thread.GetDomain().DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave, "./");
            var file_name = "test.exe";
            var mod_builder = asm_builder.DefineDynamicModule(file_name);
            var interface_builder = mod_builder.DefineType("IInterface", TypeAttributes.Abstract | TypeAttributes.Interface);
            interface_builder.DefineMethod("DoSomeBehavior", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual, typeof(int), null);
            var interface_type = interface_builder.CreateType();

            var type_builder = mod_builder.DefineType("TestClass", TypeAttributes.NotPublic | TypeAttributes.Class, typeof(object), new []{interface_type});
            var ctor = type_builder.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
                CallingConventions.Standard, Enumerable.Empty<Type>().ToArray());
            var il_generator = ctor.GetILGenerator();
            il_generator.Emit(OpCodes.Ret);

            type_builder.AddInterfaceImplementation(interface_type);
            var method_builder = type_builder.DefineMethod("DoSomeBehavior", MethodAttributes.Public | MethodAttributes.Virtual, typeof(int), Enumerable.Empty<Type>().ToArray());
            var il_generator2 = method_builder.GetILGenerator();
            il_generator2.Emit(OpCodes.Ldc_I4_0);
            il_generator2.Emit(OpCodes.Ret);

            var class_type = type_builder.CreateType();
            var instance = Activator.CreateInstance(class_type);

            asm_builder.Save(file_name);
            var method = class_type.GetMethod("DoSomeBehavior");
            var return_value = method.Invoke(instance, null);
            Console.WriteLine(return_value);
        }
    }
}

注意点としては、classにobjectを継承させる以外にも、interfaceはabstractにすること、interfaceのメソッドは、abstractかつvirtual、publicで宣言すること、classのメソッドは、publicかつvirtualで宣言することが挙げられます。今回は、フィールドを宣言したり、アクセスしたりしないので簡潔になっていますが、フィールドにメソッド内でアクセスしようとすると途端に複雑になり、TypeBuilder単独では達成できなくなったりしますが、それはまた別の話です。そこに関しては、他の方が記事にしているので、当方では記事にするつもりはありません。

2018年2月17日土曜日

オレオレ言語、Expressoについて・・・骨格解説編

こんにちは、はざまです。今回も前回に引き続き、自作言語Expressoの解説をしていこうと思います。

以下、まずはいくつか特筆すべきと思われるExpressoの機能を紹介します。
まず、Expressoでは、組み込み型でvectorやdictionaryがサポートされています。これらを生成するリテラルが用意されていますし、多少コンパイルでも特別扱い(実体は、それぞれSystem.Collections.Generic.ListとSystem.Collections.Generic.Dictionaryですが)されます。ただ、今の所は、実装上の問題により、パターンマッチの対象にはなっていないのですが……
他に組み込み型関連では、intseqという型があります。intseqとは"integer sequence"の略で、これはPythonで言うところのxrange型やRustのRange型と同様、整数列を生成するジェネレータです。残念ながら、int(32ビットの整数)の範囲の整数しか扱えないのですが、いわゆるCのような旧式のfor文が存在しないExpressoにおいて、カウントアップなどを行う際に多用される型です。vectorやarrayなどに作用して、整数列にマッチする要素だけを取り出すiterator(.NET用語だと、enumerator)も生成できます(sliceと呼ばれる)。
Expressoには、Rustにも存在するmatch文があります。これは、最近はやりのパターンマッチを行う文法要素で、各種オブジェクトの分解や、リテラル値とのマッチングを行います。tupleパターンとのマッチ程度しか想定していませんが、一応変数宣言(let文var文)でも、パターンが使用できるようになりました。
一つ書き忘れてましたが、クロージャは、関数やメソッドに直接渡すなど、すぐにその引数の型を推論できる状態であれば、型を省略することができます。将来的にEnumerable拡張のメソッドを呼べるようになった際にメソッドチェーンを書きやすくするための実装ですが、拡張メソッドを導入するかどうか悩んでいます。型を定義する度に、全型を走査しなければならなくなりそうで、ちょっと微妙なんですよね・・・

いくつか特筆に値する機能を見たところで、皆様も気になっているかもしれないExpressoの原理について解説しましょう。まず、現状、コンパイラは純C#製です。レキサ、パーサー、アナライザ、コード生成、全部C#で完結しています。吐かれるバイナリは、C#のコンパイル後の表現であるIL形式ですし、パーサージェネレータもC#のものを使用しています。この部分もC#を選んだ理由の一つに挙げられるでしょう(式木と呼ばれるデータ構造を生成するだけで実行可能なコードが生成できる)。いずれ、セルフホスティングしてコンパイラ自体をExpressoで実装したいところなのですが、パーサーとアナライザの切り離しをどうするか、パーサーはC#のものを使用するとして、現状、パーサーとアナライザは三位一体なので、そうするとあとはコード生成部分程度しかExpressoで書ける部分がなくなり、結局今のままと大して変わらないのではないかなどの問題があり、まだ実現していません。また、Expresso化するにあたって、組み込みのオブジェクト(intseq,slice)の実装をどうするかという問題もあります。intseq型は、ExpressoIntegerSequenceという型をC#で定義しているのですが、C#の機能を利用してEnumeratorを生成しやすくしているので、Expressoに置き換えるなら、それを自分で実装しなくてはならなくなります(コンパイラが自動で行う変換なので、それを知っていれば大した問題ではないかもしれません。yield式を使用するので、状態を保持するステートマシンみたいなものを自分で書かなければならない)。
とまあ、問題はあるものの、コード生成が楽だったり、パーサージェネレータが存在したり、標準でクロスプラットフォームで動くので、C#はオレオレ言語作りに結構向いている環境と言えるかもしれません。まあ、今から言語作りをしたい方にはいきなり言語作りするのではなく、まずはLISPのインタープリタあたりを実装するところから始められることをお勧めしますが。上で出したレキサ、パーサー、インタープリタ、それぞれの機能を具体的にイメージできるようになります。
次に文法についてですが、現状明文化していないので、Cocoのパーサー定義を見ていただくのが一番早いかと思います。中には、パーサー定義を作ったものの、機能の実装をしていなくて動かないものもありますが(具体的にいうとcomprehension, interfaceなどです)。大雑把に文法を把握したいのなら、ExpressoTest/sources配下のファイルが参考になるでしょう。こちらも仮で書いただけの定義があったりして、パースもできないものが含まれていたりしますが、概要を知りたいだけなら十分と思われます。
ドキュメントについては、Rustの公式解説本のようなものを英語でmarkdown形式で書いています。日本語で書き直すのは面倒なので、しないかもしれません。こちらは、Expresso/Documentation/配下に存在します。
まだ、書きたいことはあるような気がしますが、今回の記事はこの程度で、どうしても書いておきたいことができたら、また記事にしようと思います。では( ̄^ ̄)ゞ

2018年2月15日木曜日

オレオレ言語、Expressoについて・・・導入編

こちらでは、ご無沙汰しています、はざまです。
突然ですが、プログラマをされている皆様が生涯で何としても作り上げたいプログラムはなんでしょうか?これは私の願望も多分に含まれているのですが、恐らく一定数の方が、自作言語と答えるのではないでしょうか?

というわけで今回の記事は、自作言語のExpresso(エクスプレッソ)の紹介をします。4,5年前から開発しているオレオレ言語なんですが、最近、try,catchなども実装し、それなりに使える言語になってきたので、α版として公開することにしようかと思った次第です。とは言っても、専用のサイトはまだ用意しませんが。
Expressoという名前は、ExpressiveとEspressoからの造語です。表現力豊かに、かつエスプレッソ(コーヒー)一杯飲む間にでも開発できるような簡潔な言語を目指すという意味を込めています。また、言語のスローガンとして"Easy for beginners, elegant for enthusiasts"という標語も掲げています。「初学者には簡単に、熱狂者には華麗に」という意味ですね。この標語にはあえて、eで始まる単語を多用しています。これは「e(いい)を探す言語」というダジャレです。
Expressoは、オレオレ言語でありながら、普及、実用化させるならPascalのような教育用言語の地位を目指しています。そのために、先ほどの標語のような目標を掲げているわけです。つまり、初学者には簡単に書ける言語、しかしながら、習熟者にとっても、書きやすい言語を目指すということです。
なぜ、教育用言語を開発するのか不思議に思っているの方もいるかもしれないので、解説しておくと、私は大学時代にPascalという言語でプログラミングを学んだのですが、Wikipediaには教育用と書いてあるんですよ。200x年にしては時代錯誤的な構文とまだ設計に慣れていなかったせいもあって無事単位を落とし、翌年Cに変わったカリキュラムで再履したんですが、その現状を変えたいと思ったのがきっかけです。まあ、スピードとかを売りにしてもRustに敵うわけがないという本音もあります。

言語仕様としては、まだα版と銘打ってることもあって、かなりガバガバなところが多いんですが、基本は静的型付け、オブジェクト指向を基本とするマルチパラダイム言語になっています。一番強く影響を受けている言語が、Rustなので、Rustで採用されている仕様が結構入っています。
現状、Expressoは、.NET環境上でのみ動く言語になっています。理由は、.NETだと比較的ランタイム環境を整えるのも楽ですし、クロスプラットフォームで動くのが大きいです。まあ、私が、いちばん好きな言語がC#だからというのもありますが……

伝統的なHello worldプログラムの解説をする前に、導入方法を紹介しましょう。現状、専用のサイトがないので、Githubのリポジトリからcloneして導入していただく形になります。こちらからcloneしてください。cloneしたら、git submodule update --initを実行してください。依存リポジトリの解決が行われます(といっても、一つしかありませんが)。そして、cloneしたディレクトリ/ExpressoTest/配下にtest_executablesというディレクトリを作成してください。ここにテストで使用するバイナリが吐かれる設定になっているので、これがないとテストが実行できません。gitにこのディレクトリを追加できるのなら、追加したいところではあります。
2018/4/7 追記: それからソリューションをVisual Studioなどで開いて、InteroperabilityTestプロジェクトをビルドし、出力されたDLLファイルを/ExpressoTest/sources/for_unit_testsディレクトリに移動してください。
そうしたら、Mac,Linuxユーザの方なら、あとはメインのソリューションファイルをIDEで開けば、ビルドして実行できるはずです(NuGetを使って一部の依存プロジェクトをダウンロードするようになったので、自動で手元にないプロジェクトをダウンロードするよう、IDEの設定を変える必要があるかもしれません)。Windowsユーザの方は、Cocoという依存プログラムを拾ってこなければなりません。あと、パーサ定義をシェルスクリプトで自動生成しているので、その代わりのバッチファイルも書かなきゃダメですね、多分。
Coco/R for C#からCoco.exeを選択してバイナリを拾ってきたら、cloneしたディレクトリ/Expresso/配下に配置してください。Expressoが言語のコアを担うプロジェクトです。バッチファイルは、cloneしたディレクトリ/Expresso/parserCompile.shというシェルスクリプトを参考に作成していただきたいのですが、Coco.exeに渡すオプションは自由に変更してください。バッチファイルを作成したら、Expressoプロジェクト設定でビルド前に自動実行するように設定すれば、いちいち手動でパーサを生成する必要がなくなります。
長々と書きましたが、Windowsでの動作確認は不十分な(動きはするもののテストは通らない程度までしか確認していない)ので、動くことは保証しません。手軽に使いたいなら、Mac+Visual StudioかLinux+Xamarin Studioあたりの環境をお勧めします(昔は、後者、今は前者の開発環境で作ってます)(2018/4/7 追記: 現状、Windowsでは.NET自体の実装が異なるようでEmitterTestsが動きません)(2018/4/8 追記: Windowsでも、大方のEmitterTestsを動かせるようになりました。ですが、動かないものは割とどうしようもなさそうなエラーで失敗してます・・・特にOOPのはずなのに、インターフェイスが動かないのは痛すぎる・・・)。

さて、ここまでで肝心のコンパイラは動かせるようになったはずなので、伝統的なHello worldプログラムに移ります。Hello worldプログラムは、以下のように書きます。
module main;
def main()
{
    println("Hello, world!");
}

中身の解説をする前に実行してみましょう。ExpressoConsoleプロジェクトをビルドし、MacかLinuxならmono exsc.exe hello_world.exs -o ./ -e hello_worldなどとしてまずコンパイルします。その後、カレントディレクトリにExpresso.dllとExpressoRuntime.dllをコピーしてください。正式リリースする頃には、この部分はなんとかすると思いますが、とりあえず今は、ランタイム環境が必要です。そして、できあがったmain.exeをmono hello_world.exeとして実行すると、Hello, world!と画面上に出力されるはずです。Expressoプログラムの実行に成功しました!

Expressoでは、基本的に1ファイル1モジュール構成を採用しています。ここは、Python譲りですね。各モジュールは、明示的に名前付けすることを義務付けられています。プログラムのエントリーポイントは、mainモジュールのmain関数からになります。今のところ、main関数は、引数も戻り値もなしの仕様になっています(Cのように文字列配列の引数を定義したり、intを戻り値にしても動きますが、単純に無視されます)(2018/4/11 追記: main関数がargs引数を取り、intを返せるようになりました。monoを使って実行するからです)。
ご覧の通り、関数、メソッドはdefキーワードで定義します。PythonやRubyで採用されている構文だったと思いますが、Rustのようにfunction由来のキーワードだとメソッド定義に違和感があるからです。Rustにはトレイトオブジェクトはあるものの、オブジェクトはないので、メソッドは存在しないはずです(追記: 公式ドキュメントでは、implブロックの関数をメソッドと呼んでいるようですので、これは間違いだったようです)。
この例ではどこにも明示されていません(というか変数宣言がない)が、型は後置です。その際、変数名と型の区切り記号には、(-という記号を使用します。これは、数学の∈に由来するExpresso独自の記号(のはず)です。あまり型は明示してほしくないという思想の元、入力しづらい2文字の記号を採用しています。Rustには似た記号を一元化してくれる機能があったと思いますが、Expressoには導入していないので、(-を∈と書いても、認識してくれませんので悪しからず。
関数、メソッドの戻り値を明示する場合は、Rustでも採用されている->記号を使います。関数の戻り値は、return文から推論するので、省略しても構いません(上のmain関数では省略しているが、voidに推論される)。
上記のプログラムで呼び出しているprintln関数は、組み込みの関数です。.NET環境のConsole.WriteLine関数を使用しているので、可変長の引数をとって、それをカンマ区切りで標準出力に出力します。他に、お尻に改行を追加しないprintや、第1引数にConsole.WriteLineに準じるフォーマット文字列を取るprintFormat関数(追記: string interpolation(日本語だと「文字列補完」ですかね)を実装したので、廃止しました)などが存在します。

いかがでしたでしょうか。以上で、オレオレ言語Expressoの導入は終わりです。あ、Expressoの骨格の説明などをしませんでしたが、機能詳細などは次回の記事で行いましょう。コンパイラ作りに興味のある方には、次の記事が参考になるかもしれませんね。

2017年10月30日月曜日

C#のforとforeachに関する思想録

どうも、はざまです。つい先日、とあるニコ生を見ている際に、forとforeachの違いについて言及される場面があり、私がforeachを使うことを勧めたところ、foreachの方がiteratorオブジェクトの破棄がループごとに発生するから遅くなるという指摘をいただき、気になったので速度比較してみることにしました。私はそのとき、え〜Releaseビルドなら、ループ全体でiteratorを使い回すように最適化してくれるんじゃないと答えたのですが、果たして結果は(よく考えたら、iteratorは使いまわさないとおかしいですね。ループ状態を内包しているはずなので)。
今回試したコードは、以下のようなものです。
const int Max = 10_000_000;

var stopwatch = Stopwatch.StartNew();
int result = 0;
foreach(var i in Enumerable.Range(0, Max))
    result += i;

stopwatch.Stop();
Console.WriteLine("foreach Result: {0}/{1}ms", result, stopwatch.ElapsedMilliseconds);

var stopwatch2 = Stopwatch.StartNew();
int result2 = 0;
for(int i = 0; i < Max; ++i)
    result2 += i;

stopwatch2.Stop();
Console.WriteLine("for Result: {0}/{1}ms", result2, stopwatch2.ElapsedMilliseconds);


Stopwatchインスタンスを生成して、foreach/forループ内で足しこむだけです。最後にそれぞれの結果を出力するのは、デッドコード削除で足しこみ自体省略されたら、嫌だなという意図です。このコードだとそれぞれ、確実にオーバーフローが発生しますが、何も書かなければC#はオーバーフローを無視してくれるはずなので、今回は特に考慮していません。さて、この単純なコードで出た結果がこちら。

Debugビルド時
foreach Result: -2014260032/197ms
for Result: -2014260032/41ms

Releaseビルド時
foreach Result: -2014260032/171ms
for Result: -2014260032/26ms

テスト環境はMacBook Pro (Retina, 13-inch, Early 2015)で2.7Ghz Intel Core i5、メモリ16GBです。Debugビルド時でおよそ5倍、Releaseビルド時で7倍弱程度の差ができてしまいました。これを見る限り、ループごとに一時変数を用意してGC走らせていそうなのは間違いなさそうですね。それにしても、結構インパクトでかいです。そっか〜、foreachって遅かったのか〜。とは言っても、可読性重視したいので、使い続けますけどね。for使うとめんどくさいですしね。
速度にうるさいC++のrange-based forとかはどんな実装になってるんだろう。ループ全体で一時変数を使いまわしたりしてないのかな〜。まあ、そうしたら、この一時変数のスコープが大きくなっちゃうんですがね。
では、また(๑╹ω╹๑ )

2017年10月4日水曜日

Rust本の翻訳始めました

お久しぶりです。ご無沙汰してました、はざまです。昔のハンドルネームに戻したりしましたが、ここではこのままはざまと名乗り続けると思います。

さて、本題なのですが、題名の通り、Rustプログラミング言語の公式ドキュメントであるThe book第2版の翻訳を始めました。実際には数ヶ月前から行っているので、もっと早くにご報告していればよかったですね。公式リポジトリで今後大きな変更がないと考えられるFrozen扱いされた章から順に翻訳を進めているので、牛歩ではありますが、お付き合い頂ければと思います。
ドラフトの執筆が完了するまでは、こちらのgithubページのsecond-editionディレクトリで読んでいただくしかないかと思われます。目次がなく読みにくいかとは存じますが、どうぞご容赦ください。

では、今回はここまで。どうぞ、よしなに。