Upload
dcubeio
View
166
Download
1
Embed Size (px)
Citation preview
Scala マクロ入門アレクセリス アンドレアス(龍ちゃん) Team RegionUp
2017-02-17 株式会社ビズリーチ
Today’s Presentation• Speaker Introduction → 誰なの、こいつ?• About Macros in general →「マクロ」って「真黒」のこと?• Macros in Scala → 何とか implicit 理解できたばかりなのに、 また面倒臭いこと…• In Action: Code Sample (master branch) → やっと、コードがでてくる
• Macros in Scala (code explanation) → は!…けど、使う自信がないな…
Today’s Presentation• In Action: Code Sample (cdef_macro branch) → おっと、面白くなってきたぞ
• (Scala Refresh) Structural Types → 「構造的部分型」 <(_ _)>• (Scala Refresh) Type-classes → 「型クラス」 <(_ _)><(_ _)>• Notes on Reflections: Types, Symbols, Trees → Trees? 花粉所の時期を思い出す…• Macro specific methods → これって Scala???• Summarizing → やっと終わったみたい。早う飲みに行きたいわ!• Q&A → ちょ、ちょっと待って!〇〇をどうやるんでしたっけ?
自己紹介• アレクセリス アンドレアス
• ギリシャ生まれ、日本好き 44歳• アテネ効果大学電子情報科学部情報学科• 1997 年来日、 NAIST 情報科学研究科修士課程• ATR ネットワーク研究所 各員研究員• 大手メーカーで SE 10 年間• いろいろあって。。。• 株式会社ビズリーチ2014年5月入社• 2年前までずっと関西。
m(_ _)m スマン時間切れで、スライドの殆どは英語のままです。誠に申し訳ありません。当然発表は、日本語で
About Macros in General• What is a macro
• Macro(Macroinstruction): An instruction to the compiler, to replace one part of the program with a replacement, created based on a procedure/template[ https://en.wikipedia.org/wiki/Macro_(computer_science) ]
About Macros in General• Typical example: C preprocessor macros
• In C language, perhaps the most common macro is the debug macro
About Macros in General• Typical example: C preprocessor macros
• In C language, perhaps the most common macro is the debug macro• In C language, macro works with text substitution by the pre-
compiler
About Macros in General• Typical example: C preprocessor macros
• In C language, perhaps the most common macro is the debug macro
• This illustrates the point from the definition we gave before
• In C language, macro works with text substitution by the pre-compiler
• This also illustrates the problem with this kind of macros
About Macros in General• This also illustrates the problem with this
kind of macros
About Macros in General• This also illustrates the problem with this
kind of macros
Macros in Scala• Experimental feature
• Originally introduced in v.2.10• Gained a very high rate of adoption.• Has been in active development/extention ever since• Currently(2.12), still experimental
• Main researcher/developer behind scalamacros: Eugene Burmako, EPFL
• Resourceshttp://scalamacros.org/http://docs.scala-lang.org/overviews/macros/overview.html ( 邦訳有り )
Macros in Scala• In contrast to macros in C, Scala macros:
• 1) are written in full-fledged Scala, • 2) work with expression trees, not with raw strings, • 3) cannot change syntax of Scala.
• They get expanded at compile time, so they are statically checked, as will be illustrated later
• Macros are called by the compiler during compilation, so they have access to the compiler’s API (Compile-time Reflection)
• Using macros relies heavily on understanding Scala reflectionResource: http://docs.scala-lang.org/overviews/reflection/overview.html
Macros in Scala• But why do we need macros in the first place?
• [ http://scalamacros.org/paperstalks/2013-07-17-WhatAreMacrosGoodFor.pdf ]
• Basically:• Code Generation (& reduction of boilerplate code)• Static Checks• Domain-specific languages (DSLs)
• In this talk, we will demonstrate the 1st use
Macros in Scala• Macros come in many flavors:
• Def macros• Implicit Materializers• Type providers• Macro Annotations• (still under rigorous extension)
• Here we will introduce the various concepts related to macros by examining types:• Def macros, as the very very basic case of a macro• Implicit Materializers, as the real use-case that turned up during work.
In Action: Code Sample(master branch)
https://github.com/aalexelis/scalaMacroNyumon
Macros in Scala• Macros is an experimental feature, must be imported• A macro declaration is a method declaration, delegating to a macro
implementation, by the keyword macro• Macros depend on a Context
• Context is …• Blackbox / Whitebox contexts
• They bring reflection API into scope by importing universe• The return type of a macro is of type Tree (AST: Abstract Syntactic
Tree) (more on this later)
Macros in Scala• At the calling site, a macro invocation is a plain method call• Macro implementation has to be already compiled when the macro calling
code is being compiled.• Therefore, to set up SBT for macros we have to structure macro definitions
and macro invocations in separate projects• Usually macros will need to have access to data structures and interfaces,
so it is better to include them (or make them depend on the “common” subsystem)• Macro subsystem should declare dependency on scale-reflect module• For some “more experimental” features, you must install the macro-
paradise compiler plugin
Macros in Scala• Macro Bundles
• A new (2.11) convention regarding where to allocate the implementation of a macro• Before, macro implementation was represented as a function
inside an object it was declared• With macro bundles, implementation can be a method in a
trait that extends the Macro trait, separately from the declaration site
• This has several advantages, mostly regarding modularity of the code, and scope visibility
Macros in Scala• Macro Bundles
Macros in Scala• Quasiquotes
• A new (2.11) way to define AST using string interpolation• Before, AST had to be created “by hand”, from the
basic API elements provided by the reflection API• With Quasiquotes, we can interpolate variables
inside a string that looks exactly how we want the macro expansion to be
Macros in Scala• Quasiquotes
Macros in Scala• Quasiquotes
• They can be used for pattern matching too, which is very convenient
• Although the concept looks simple, its implementation is probably complex, so the scalamacros people warn that there might be still residual bugs. In such case we have to resort back to writing the AST by hand.
In Action: Code Sample(cdef_macro branch)
https://github.com/aalexelis/scalaMacroNyumon/tree/cdefext_macro
Typeclass• A typeclass is a sort of interface that defines
some behavior. If a type is a part of a typeclass, that means that it supports and implements the behavior the typeclass describes.
• It means “in order to perform this operation in a meaningful way, the type of the instance or argument must be a member of the type class
Type Classes• The idea of typeclasses is that you provide
evidence that a class satisfies an interface• Instead of having the type directly implement
the interface, I can provide the implementation elsewhere in the code
• This allow us avoid the inheritance spaghetti of unrelated classes, and allows us to use different libraries uniformly.
Notes on Reflection• Reflection: the possibility that a program can have access, inspect and
manipulate it’s own representation• Usually reflection is a “run-time” tool
• However 、 Scala allows for a “compile-time” type of reflection, via macros• They are based on the same api with the run-time reflection, which allows
code sharing• Reflection Environment
• Universe: the environment info for current use of reflection• Mirror: the parts we have access to reflectively
Notes on Reflection: Types
• Types• Types represent information about the type of a
corresponding symbol.• They are available to the compiler, to be able to produce
the proper implementation of the program• In general, they are erased after the type checking part of
the compilation is done• However, when using reflections, we need access to type
information, in order to manipulate the entities properly.
Notes on Reflection: TypeTags
• TypeTags: what are they?• They are a type of manifest, of all the information the compiler
knows about a specific type• They can be passed as parameters to methods, and used to
extract type information related to the manipulated entities• In Scala reflection there are 3 types of TypeTags
• TypeTags• WeakTypeTags• ClassTags
Notes on Reflection: Symbols
• Symbols• Symbols bind entities to names, so that we can refer to them. Whatever you
can name in Scala gets an associated Symbol• TypeSymbol: symbol for a type in general
• ClassSymbol: symbol for a class or trait• TermSymbol: symbol for val, var, def, object, package, value parameters
• MethodSymbol: symbol for methods• ModuleSymbol: symbol for object declarations
• NoSymbol: top level symbol owner, (something like Nil for symbols)• Free Symbols (@ look at reification for more info)
Notes on Reflection: Trees
• Trees: abstract syntax trees (ASTs) represent programs• Annotations• reify• Macros
• Subcategories of Trees: trees are made up of nodes• TermTree: represent terms: Apply nodes for method invocations, New nodes for
instantiations etc.• TypTree: represent types: ???• SymTree: represent definitions: ClassDef for definition of class,, ValDef for
definition of val, etc• …some other type of short-lived tree types also exist
Macro Specific methods
• reify: creates Expr with trees• splice: inserts a subtree into a tree
Summarizing
Thank you for your kind attention.
I will be glad to take questions→ お手柔らかに <(_ _)>