Cask macros code analysis covers the macros implementation and related data types. To debug Macro AST, use def scalacOptions = Seq("-Ymacro-debug-lite") to inpsect generated code.
1 The Routes
An instance of Routes has a set of defined Decorator, an implicit actor Context, an implicit log, and an instance of RoutesEndpointsMetatadata. A subtype of Routes is required to call the Routes#initialize() method that has an implicit parameter of RoutesEndpointsMetatadata. The call triggers the call to the RoutesEndpointsMetadata.iniitalize macro to create an instance of RoutesEndpointsMetatadata[T] for this subtype T of the Routes.
The RoutesEndpointsMetadata[T] case class only has a value member that is a sequence of EndpointMetadata[T]. An EndpointMetadata[T] has
- a sequnce of
Decoratorexcluding theEndpoint(?) - one
Endpoint - one
EntryPoint[T, _].
The macro’s function it to return a list of EndpointMetadta for the delcared subtype of Routes by performning the following steps:
- Get members of
T, for each member, get its non-empty annotations that are a subtype ofDecorator. Generate anEndpointMetaData[T]for each annotated member. - Abort if the last annotation doesn’t have a type of
Endpointor there are more than oneEndpointannotations. - Genereate a list of
EndpointMetadatafor the list of endpoints.
For each annotated member (an endpoint):
- Generate all annotation objects.
- Generate a list of names and positions for the annotation objects
- Call the
Macros.extraceMethodto create anEntryPointobject for this annotated endpoint. - create a list of definitions for the annotation ojbects
- verify that the inner annotation’s
OuterReturnedtype is the enclosing annotation’sInnerREturnedtype. - generate the code block that has
- the declaration of all generated annotation objects
- an instance of
EndpointMetadata - A list of annotations in the order of definition, from outmost to the inner most, removing the last endpoint annontation
- the endpoint annontation
- the
EntrypPoint
2 Macros.extraceMethod
The parameters are
method: MethodSymbol: the method annotated by the endpoint as aMethodSymbolcurCls: c.universe.Type: current class, the type ofT, a subtype ofRoutesconvertToResultType: c.Tree: theEndpointannotation’sconvertToResultTypemethodctx: c.Tree: thecask.RequesttypeargReaders: Seq[c.Tree]: a list of each annotation object’sgetParamParsermethods, in reverse annotation orderannotDeserializeTypes: Seq[c.Tree]: a list of each annotation object’sInputTypeAliastypes, in reverse annotation order
The steps are
- generate a symbol for an instance of the current
Routestype, likefresh$macro$4. - generate method doc.
- generate a symbol for argument value, like
argValues$macro$5. - generate a symbol for argument signature, like
argSigs$macro$6. - generate a symbol for context, like
ctx$macro$7. It is used to define the context variable likectx$macro$7: cask.Request. - for each of the method’s parameter list, create
argDatathat is a list of quadruples:(argNameCats, argSigs, argNames, readArgs). Each argument list is corresponding toargNameCats: a list of argument names with a cast, likestatus.asInstanceOf[String].argSigs: the signature of arguments.ArgSigis a case class having two parameter lists: the first lis tincludes the name, type, doc, and default value of typeOption[T => V]. The 2nd list is an implicit val of the decorator’sgetParamParser.argNames: a list of argument namesreadArgs: a list of calls tocask.router.Runtime.makeReadCall. The call usesgetParamParserto parse the argument and returns anEitherresult forResult.ParamErroror valid result.
With the list of quadruples for each parameter list, create an EntryPoint[T, cask.Request]. It has four fields:
name: String: the method (entry point) name defined right below an end point notation.argSignatures: Seq[Seq[ArgSig[_, T, _, C]]]: a sequence of a seuqnce ofArgSig. The element of the first sequence is each parameter list. One parameter list for one decorator. the 2nd sequence is a list ofArgSigin an parameter list. Cask only allows empty or one parameter in a paramter list.doc: Option[String]: method doc stringinvoke0: it is a call tocask.router.Runtime.validate(Seq(makeReadCall(...), makeReadCall(...))).map(endpoint.convertToResultType(entryPoint(a3)(a2)(a1)).
3 The invoke method
For a matched route, the invoke method performs the following steps:
- For each decorator, the
Runtime.makeReadCalluses itsInputParser[T]to parse the parameter. - The
Runtime.validatevalidates all decorator results. The result is anEitherthat has either a list ofParamErroror a list of valid arguments for the entry point method. - Call the entry point mehtod with all arguments.
- Call the end point’s
convertToResultTypeto convert the entry point result to the type of declared result of the end point.
Each parameter list corresponds to one decorator. The endpoint decorator’s input is the output of the entry point. Its output is the input of the next decorator. For HTTPEndpoint, the output is Response.Raw, and all outer decoratos have a type of Response.Raw for their input and output.
|
|
4 Endpoint
An endpoint decorator is the last decorator enclosing the entry point. For an HttpEndpoint, the OuterReturned is fixed to Response.Raw, the InnerReturned is the type returned from entry point call. The Input is passed as the value type of Map[String, Input]. For example, in WebEndpoint, the wrapFunction is defined as: delegate(WebEndpoint.buildMapFromQueryParams(ctx)): it gets query parameters and passed into the entry point as an instance of Map[String, Seq[String]]. The warpPathSegment(s: String) = Seq(s) matches the Input type. The warpPathESgment result is combined with the result of buildMapFromQueryParams in Decorator#invoke method.
The HttpEndpoint uses QueryParamReader to convert a String to a set of predefined types. For custom data type T, define an implicit instance of QueryParamReader[T].
5 RawDecorator
Non Endpoint decorator should use RawDecorator to wrap perform action before or after the enclosing decorator. Its OutReturned and InnerReturned are Response.Raw. Its Input is Any and doesn’t use InputParser.
Therefore, the functions of a RawDecorator can be one or more of the following:
- perform an action before the enclosing decorator
- pass some arguments to the enclosing decorator
- perform an action after the enclosing decorator
6 Response.Raw
7 Example
For the following source:
|
|
The macros generates the following code:
|
|