Compare commits
95 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
4fd03ed667 | ||
![]() |
4cb5ee4196 | ||
![]() |
888481094a | ||
![]() |
7686fe3e35 | ||
![]() |
747d07bfc5 | ||
![]() |
00640d8328 | ||
![]() |
77973f6007 | ||
![]() |
0df9c28ace | ||
![]() |
d90fb966d2 | ||
![]() |
9018b06279 | ||
![]() |
6ed0424093 | ||
![]() |
53868cc6f3 | ||
![]() |
296cc6c861 | ||
![]() |
56c2ed9642 | ||
![]() |
ac908bc82d | ||
![]() |
1604a135ae | ||
![]() |
5e65f5354f | ||
![]() |
8f81256731 | ||
![]() |
1b717919fa | ||
![]() |
3d9aec835e | ||
![]() |
86fa47eb0d | ||
![]() |
b5605e48ac | ||
![]() |
6f5eba983e | ||
![]() |
d5a44a9268 | ||
![]() |
a11804c3ab | ||
![]() |
380ceb39ea | ||
![]() |
c48d445a54 | ||
![]() |
b7e413d839 | ||
![]() |
e1e487079b | ||
![]() |
5f959f788e | ||
![]() |
4f84570bb7 | ||
![]() |
e398d0e694 | ||
![]() |
13d11f4f66 | ||
![]() |
d6142847eb | ||
![]() |
e6a0304016 | ||
![]() |
69368937a4 | ||
![]() |
df2389d2c8 | ||
![]() |
aad80afec2 | ||
![]() |
b68c6ac4a1 | ||
![]() |
682aeacce8 | ||
![]() |
9bcec770eb | ||
![]() |
2310b6d8e4 | ||
![]() |
7f13916154 | ||
![]() |
2b7204f8d3 | ||
![]() |
7ca0d4a650 | ||
![]() |
e38f5ae147 | ||
![]() |
4186225eb5 | ||
![]() |
f5a3d73c55 | ||
![]() |
f65df0e94b | ||
![]() |
55a4b1463f | ||
![]() |
0a6e39969b | ||
![]() |
f051345863 | ||
![]() |
74e37b4bf1 | ||
![]() |
42821979d9 | ||
![]() |
2aa0b07e9f | ||
![]() |
67e680f67f | ||
![]() |
ebade45e63 | ||
![]() |
40497bb1fc | ||
![]() |
d80b03fe9d | ||
![]() |
f269d13abf | ||
![]() |
f271cc880a | ||
![]() |
9cd59d3989 | ||
![]() |
40ee99df39 | ||
![]() |
1cb27daf46 | ||
![]() |
a9bea4287a | ||
![]() |
0be2090232 | ||
![]() |
0dc774db21 | ||
![]() |
a7c22bf5af | ||
![]() |
a164b335ed | ||
![]() |
d02306eebd | ||
![]() |
ff9ef59445 | ||
![]() |
bfc5c2b88f | ||
![]() |
57042819b1 | ||
![]() |
82d15d9ffc | ||
![]() |
0d9fff7e01 | ||
![]() |
45d5f3e0ea | ||
![]() |
800891bee2 | ||
![]() |
0802bf7f79 | ||
![]() |
42897c7cd5 | ||
![]() |
0e902745b1 | ||
![]() |
3dec4fa404 | ||
![]() |
c0ec918f52 | ||
![]() |
4eb9729f0e | ||
![]() |
7586b54ece | ||
![]() |
21c7d12be7 | ||
![]() |
f27d2796b1 | ||
![]() |
417a92cabc | ||
![]() |
4457ea7dee | ||
![]() |
209847e5ea | ||
![]() |
c94e4a0337 | ||
![]() |
cc009b2026 | ||
![]() |
0a36ee8e2b | ||
![]() |
5879773566 | ||
![]() |
58262a1810 | ||
![]() |
9ceadeb88f |
4
.haxerc
Normal file
4
.haxerc
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"version": "4.0.0-rc.3",
|
||||
"resolveLibs": "scoped"
|
||||
}
|
54
.travis.yml
54
.travis.yml
@@ -1,27 +1,41 @@
|
||||
sudo: required
|
||||
dist: trusty
|
||||
dist: xenial
|
||||
|
||||
language: haxe
|
||||
haxe:
|
||||
- 3.2.1
|
||||
- development
|
||||
stages:
|
||||
- test
|
||||
- deploy
|
||||
|
||||
matrix:
|
||||
allow_failures:
|
||||
- haxe: development
|
||||
language: node_js
|
||||
node_js: 8
|
||||
|
||||
install:
|
||||
- haxelib install travix
|
||||
- haxelib run travix install
|
||||
|
||||
script:
|
||||
- haxelib run travix node
|
||||
os:
|
||||
- linux
|
||||
# - osx
|
||||
|
||||
env:
|
||||
secure: T4SCtY5qmEsK1ARWPevJmqLm23tv4CobLrbPOQV3FsoQno7FCP1S/+9GmuoJKzeTjWMzdTeDsp8TVwZ6AyGjvhl2nZNjhU+QTsir4tfbYYRyvsz/QK6pveFbPQVv7OsnnaB4wbZtqGZ8mzFeQf7Ol4tsNe7iUFJb/iVc+4/lUxo=
|
||||
- HAXE_VERSION=3.4.7
|
||||
- HAXE_VERSION=edge
|
||||
|
||||
install:
|
||||
- npm i -g lix@15.3.13
|
||||
- lix install haxe $HAXE_VERSION
|
||||
- lix download
|
||||
|
||||
deploy:
|
||||
provider: script
|
||||
script: haxe && haxelib run travix release
|
||||
on:
|
||||
tags: true
|
||||
script:
|
||||
- lix run travix node -lib hx3compat
|
||||
|
||||
jobs:
|
||||
include:
|
||||
# - stage: test # should uncomment this when there is no matrix above (e.g. only one os, one env, etc)
|
||||
- stage: deploy
|
||||
language: haxe
|
||||
haxe: "3.4.7"
|
||||
os: linux
|
||||
install: skip
|
||||
script: skip
|
||||
env:
|
||||
secure: T4SCtY5qmEsK1ARWPevJmqLm23tv4CobLrbPOQV3FsoQno7FCP1S/+9GmuoJKzeTjWMzdTeDsp8TVwZ6AyGjvhl2nZNjhU+QTsir4tfbYYRyvsz/QK6pveFbPQVv7OsnnaB4wbZtqGZ8mzFeQf7Ol4tsNe7iUFJb/iVc+4/lUxo=
|
||||
after_success:
|
||||
- haxelib install travix
|
||||
- haxelib run travix install
|
||||
- haxelib run travix release
|
||||
|
5
.vscode/settings.json
vendored
5
.vscode/settings.json
vendored
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"haxe.displayConfigurations": [
|
||||
["tests.hxml"]
|
||||
]
|
||||
}
|
49
README.md
49
README.md
@@ -17,18 +17,17 @@ The library is build on top of the haxe macro API and `tink_core`, having three
|
||||
|
||||
<!-- START INDEX -->
|
||||
- [Macro API](#macro-api)
|
||||
-
|
||||
- [Expression Tools](#expression-tools)
|
||||
- [Basic Helpers](#basic-helpers)
|
||||
- [Extracting Constants](#extracting-constants)
|
||||
- [Shortcuts](#shortcuts)
|
||||
- [Type Inspection](#type-inspection)
|
||||
- [Advanced Transformations](#advanced-transformations)
|
||||
- [Position Tools](#position-tools)
|
||||
- [Type Tools](#type-tools)
|
||||
- [Function Tools](#function-tools)
|
||||
- [Operation Tools](#operation-tools)
|
||||
- [Metadata Tools](#metadata-tools)
|
||||
- [Expression Tools](#expression-tools)
|
||||
- [Basic Helpers](#basic-helpers)
|
||||
- [Extracting Constants](#extracting-constants)
|
||||
- [Shortcuts](#shortcuts)
|
||||
- [Type Inspection](#type-inspection)
|
||||
- [Advanced Transformations](#advanced-transformations)
|
||||
- [Position Tools](#position-tools)
|
||||
- [Type Tools](#type-tools)
|
||||
- [Function Tools](#function-tools)
|
||||
- [Operation Tools](#operation-tools)
|
||||
- [Metadata Tools](#metadata-tools)
|
||||
- [Build Infrastructure](#build-infrastructure)
|
||||
- [Member](#member)
|
||||
- [ClassBuilder](#classbuilder)
|
||||
@@ -51,9 +50,9 @@ It is suggested to use this API by `using tink.MacroApi;`
|
||||
|
||||
Apart form `tink_macro` specific things, it will also use `haxe.macro.ExprTools` and `tink.core.Outcome`.
|
||||
|
||||
### Expression Tools
|
||||
## Expression Tools
|
||||
|
||||
#### Basic Helpers
|
||||
### Basic Helpers
|
||||
|
||||
- `at(e:ExprDef, ?pos:Position):Expr`
|
||||
A short hand for creating expression as for example `EReturn(value).at(position)`, instead of the more verbose `{ expr: EReturn(value), pos: position }`.
|
||||
@@ -69,7 +68,7 @@ Traces the string representation of an expression and returns it.
|
||||
- `concat(e1:Expr, e2:Expr):Expr`
|
||||
Concats two expressions into a block. If either sub-expression is a block itself, it gets flattened into the resulting block.
|
||||
|
||||
#### Extracting Constants
|
||||
### Extracting Constants
|
||||
|
||||
- `isWildcard(e:Expr):Bool`
|
||||
Checks whether an expression is the identifier `_`
|
||||
@@ -82,7 +81,7 @@ Attempts extracting an identifier from an expression. Note that an identifier ca
|
||||
- `getName(e:Expr):Outcome<String, tink.core.Error>`
|
||||
Attempts extracting a name, i.e. a string constant or identifier from an expression
|
||||
|
||||
#### Shortcuts
|
||||
### Shortcuts
|
||||
|
||||
Often reification is prefereable to these shortcuts - if applicable. Unlike reification, the position of these expressions will default to `Context.currentPos()` rather than the position where they were created.
|
||||
|
||||
@@ -119,7 +118,7 @@ Generates a simple if statement.
|
||||
- `iterate(target:Expr, body:Expr, ?loopVar:String = 'i', ?pos:Position):Expr`
|
||||
Will loop over `target` with a loop variable called `loopVar` using `body`-
|
||||
|
||||
#### Type Inspection
|
||||
### Type Inspection
|
||||
|
||||
- `is(e:Expr, c:ComplexType):Bool`
|
||||
Tells you whether a given expression has a given type.
|
||||
@@ -129,7 +128,7 @@ Inspects, whether an expression can be iterated over and if so returns the eleme
|
||||
- `typeof(expr:Expr, ?locals:Array<Var>):Outcome<Type, tink.core.Error>`
|
||||
Attempts to determine the type of an expression. Note that you can use `locals` to hint the compiler the type of certain identifiers. For example if you are in a build macro, and you want to get the type of a subexpression of a method body, you could "fake" the other members of the class as local variables, because in that context, the other members do not yet exists from the compiler's perspective.
|
||||
|
||||
#### Advanced Transformations
|
||||
### Advanced Transformations
|
||||
|
||||
- `has(e:Expr, condition:Expr->Bool, ?options: { ?enterFunctions: Bool })`
|
||||
This function actually does no transformation, but is very close to the rest of these functions. It allows you to check whether an expression has a sub-expression that satisfies `condition`. By default, it does not enter nested functions.
|
||||
@@ -187,7 +186,7 @@ This will traverse an expression and will apply the `yielder` to the "leafs", wh
|
||||
|
||||
If you set `options.leaveLoops` to `true`, then loops (both for and while) will be considered leafs.
|
||||
|
||||
### Position Tools
|
||||
## Position Tools
|
||||
|
||||
- `sanitize(pos:Position):Position`
|
||||
Returns the position ITself or `Context.currentPos()` if it's null.
|
||||
@@ -202,7 +201,7 @@ Creates a failed `Outcome` associated with the supplied position.
|
||||
- `getOutcome<D, F>(pos:Position, outcome:Outcome<D, F>):D`
|
||||
Attempts getting the result of the supplied outcome. If it is a failure, it will cause an error at the given position.
|
||||
|
||||
### Type Tools
|
||||
## Type Tools
|
||||
|
||||
- `getID(t:Type, ?reduced = true):Null<String>`
|
||||
Returns a String identifier for a type if available. By default, the type will be reduced prior to getting its name (typedefs are resolved etc.). With `reduced = false` you can also get the name of a typedef.
|
||||
@@ -225,7 +224,7 @@ Will tell you whether a field is a variable or not. Signature is likely to chang
|
||||
- `toComplex(type:Type, ?option:{ ?direct: Bool }):ComplexType`
|
||||
Will convert a `Type` to a `ComplexType`. Ideally this is done with `Context.toComplexType` but for monomorphs and the like, this builtin method fails and `tink_macro` uses a hack to make it work none the less. You can also use `{ direct : true }` to force this hack in case the translation fails (which can be the case with private types).
|
||||
|
||||
### Function Tools
|
||||
## Function Tools
|
||||
|
||||
- `asExpr(f:Function, ?name:String, ?pos:Position):Expr`
|
||||
Converts a function to an expression, i.e. a local function definition.
|
||||
@@ -236,7 +235,7 @@ A shorthand to create function arguments.
|
||||
- `getArgIdents(f:Function):Array<Expr>`
|
||||
Will extract the argument list of a function as an expression list of identifiers (usefull when writing call-forwarding macros or the like).
|
||||
|
||||
### Operation Tools
|
||||
## Operation Tools
|
||||
|
||||
- `get(o:Binop, e:Expr):Outcome<{ e1:Expr, e2:Expr, pos:Position }, tink.core.Error>`
|
||||
Attempts to extract a specific binary operation from an expression.
|
||||
@@ -250,7 +249,7 @@ Attempts to extract a specific unary operation from an expression.
|
||||
- `getUnop(e:Expr):Outcome<{ op:Unop, e:Expr, postFix:Bool, pos:Position }, tink.core.Error>`
|
||||
Attempts to decompose an expression into the parts of a unary operation.
|
||||
|
||||
### Metadata Tools
|
||||
## Metadata Tools
|
||||
|
||||
- `toMap(m:Metadata):Map<String, Array<Array<Expr>>`
|
||||
Will deconstruct an array of metadata tags to a `Map` mapping the tag names to an array of the argument lists of each tag with that name. So `@foo(1) @foo(2) @bar` becomes `["foo" => [[1], [2]], "bar" => [[]]]`
|
||||
@@ -303,7 +302,7 @@ abstract Member from Field to Field {
|
||||
|
||||
Most of the API should be self-explaining. The `isBound` property is a bad name to convey the concept that a field can be either `inline` (`true`) or `dynamic` (`false`) or neither (`null`). Equally, `isPublic` is nullable which means that normally defaults to `private`.
|
||||
|
||||
The `publish` method will make a field `public` if it is not `private`. This can also be done with `if (m.isPublic == null) m.isPublic = true;` but the implementation is far more efficient - for what its worth.
|
||||
The `publish` method will make a field `public` if it is not explicitly marked as `private`. This can also be done with `if (m.isPublic == null) m.isPublic = true;` but the implementation is far more efficient - for what its worth.
|
||||
|
||||
The `extractMeta` method will "peel of" the first tag with a given `name` - if available. Note that the tag will be removed from the member.
|
||||
|
||||
@@ -391,7 +390,7 @@ The `init` method is the swiss army knife of initializing fields. The `options.p
|
||||
|
||||
#### Setter Bypass
|
||||
|
||||
It is important to know that when you initialize a field with `options.bypass` set to true, existing setters will by bypassed. That's particularly helpful if your setter triggers a side effect that you don't want triggered. This is achieved by generating the assignment as `(untyped this).$name = $value`. To make the code typesafe again, this is prefixed with `if (false) { var __tmp = this.$name; __tmp = $value; }`. This code is later thrown out by the compiler. Its role is to ensure type safety without interfering with the normal typing order.
|
||||
It is important to know that when you initialize a field with `options.bypass` set to true, existing setters will be bypassed. That's particularly helpful if your setter triggers a side effect that you don't want triggered. This is achieved by generating the assignment as `(untyped this).$name = $value`. To make the code typesafe again, this is prefixed with `if (false) { var __tmp = this.$name; __tmp = $value; }`. This code is later thrown out by the compiler. Its role is to ensure type safety without interfering with the normal typing order.
|
||||
|
||||
Setter bypass also causes the field to gain an `@:isVar`. And currently, with `-dce full`, additional code will be generated to avoid the field to be eliminated.
|
||||
|
||||
|
6
dev.hxml
Normal file
6
dev.hxml
Normal file
@@ -0,0 +1,6 @@
|
||||
tests.hxml
|
||||
-lib travix
|
||||
-lib tink_macro
|
||||
-lib hx3compat
|
||||
-js whatever.js
|
||||
--no-output
|
3
haxe_libraries/hx3compat.hxml
Normal file
3
haxe_libraries/hx3compat.hxml
Normal file
@@ -0,0 +1,3 @@
|
||||
-D hx3compat=1.0.0
|
||||
# @install: lix --silent download "haxelib:/hx3compat#1.0.0" into hx3compat/1.0.0/haxelib
|
||||
-cp ${HAXE_LIBCACHE}/hx3compat/1.0.0/haxelib/std
|
6
haxe_libraries/hxnodejs.hxml
Normal file
6
haxe_libraries/hxnodejs.hxml
Normal file
@@ -0,0 +1,6 @@
|
||||
# @install: lix --silent download "haxelib:hxnodejs#4.0.9" into hxnodejs/4.0.9/haxelib
|
||||
-D hxnodejs=4.0.9
|
||||
-cp ${HAXESHIM_LIBCACHE}/hxnodejs/4.0.9/haxelib/src
|
||||
-D nodejs
|
||||
--macro allowPackage('sys')
|
||||
--macro _hxnodejs.VersionWarning.include()
|
8
haxe_libraries/tink_cli.hxml
Normal file
8
haxe_libraries/tink_cli.hxml
Normal file
@@ -0,0 +1,8 @@
|
||||
-D tink_cli=0.3.1
|
||||
# @install: lix --silent download "haxelib:/tink_cli#0.3.1" into tink_cli/0.3.1/haxelib
|
||||
-lib tink_io
|
||||
-lib tink_stringly
|
||||
-lib tink_macro
|
||||
-cp ${HAXE_LIBCACHE}/tink_cli/0.3.1/haxelib/src
|
||||
# Make sure docs are generated
|
||||
-D use-rtti-doc
|
3
haxe_libraries/tink_core.hxml
Normal file
3
haxe_libraries/tink_core.hxml
Normal file
@@ -0,0 +1,3 @@
|
||||
# @install: lix --silent download "haxelib:tink_core#1.16.1" into tink_core/1.16.1/haxelib
|
||||
-D tink_core=1.16.1
|
||||
-cp ${HAXESHIM_LIBCACHE}/tink_core/1.16.1/haxelib/src
|
5
haxe_libraries/tink_io.hxml
Normal file
5
haxe_libraries/tink_io.hxml
Normal file
@@ -0,0 +1,5 @@
|
||||
-D tink_io=0.5.0
|
||||
# @install: lix --silent download "haxelib:/tink_io#0.5.0" into tink_io/0.5.0/haxelib
|
||||
-lib tink_streams
|
||||
-lib tink_core
|
||||
-cp ${HAXE_LIBCACHE}/tink_io/0.5.0/haxelib/src
|
3
haxe_libraries/tink_macro.hxml
Normal file
3
haxe_libraries/tink_macro.hxml
Normal file
@@ -0,0 +1,3 @@
|
||||
-D tink_macro
|
||||
-cp src
|
||||
-lib tink_core
|
4
haxe_libraries/tink_streams.hxml
Normal file
4
haxe_libraries/tink_streams.hxml
Normal file
@@ -0,0 +1,4 @@
|
||||
-D tink_streams=0.2.1
|
||||
# @install: lix --silent download "haxelib:/tink_streams#0.2.1" into tink_streams/0.2.1/haxelib
|
||||
-lib tink_core
|
||||
-cp ${HAXE_LIBCACHE}/tink_streams/0.2.1/haxelib/src
|
4
haxe_libraries/tink_stringly.hxml
Normal file
4
haxe_libraries/tink_stringly.hxml
Normal file
@@ -0,0 +1,4 @@
|
||||
-D tink_stringly=0.2.0
|
||||
# @install: lix --silent download "haxelib:/tink_stringly#0.2.0" into tink_stringly/0.2.0/haxelib
|
||||
-lib tink_core
|
||||
-cp ${HAXE_LIBCACHE}/tink_stringly/0.2.0/haxelib/src
|
6
haxe_libraries/travix.hxml
Normal file
6
haxe_libraries/travix.hxml
Normal file
@@ -0,0 +1,6 @@
|
||||
-D travix=0.12.2
|
||||
# @install: lix --silent download "gh://github.com/back2dos/travix#7da3bf96717b52bf3c7e5d2273bf927a8cd7aeb5" into travix/0.12.2/github/7da3bf96717b52bf3c7e5d2273bf927a8cd7aeb5
|
||||
# @post-install: cd ${HAXE_LIBCACHE}/travix/0.12.2/github/7da3bf96717b52bf3c7e5d2273bf927a8cd7aeb5 && haxe -cp src --run travix.PostDownload
|
||||
# @run: haxelib run-dir travix ${HAXE_LIBCACHE}/travix/0.12.2/github/7da3bf96717b52bf3c7e5d2273bf927a8cd7aeb5
|
||||
-lib tink_cli
|
||||
-cp ${HAXE_LIBCACHE}/travix/0.12.2/github/7da3bf96717b52bf3c7e5d2273bf927a8cd7aeb5/src
|
24
haxelib.json
24
haxelib.json
@@ -1,20 +1,20 @@
|
||||
{
|
||||
"name": "tink_macro",
|
||||
"license": "MIT",
|
||||
"description": "The macro toolkit ;)",
|
||||
"classPath": "src",
|
||||
"dependencies": {
|
||||
"tink_core": ""
|
||||
},
|
||||
"url": "http://haxetink.org/tink_macro",
|
||||
"contributors": [
|
||||
"back2dos"
|
||||
],
|
||||
"version": "0.17.7",
|
||||
"releasenote": "Use @:persistent as necessary.",
|
||||
"tags": [
|
||||
"tink",
|
||||
"macro",
|
||||
"utility"
|
||||
],
|
||||
"classPath": "src",
|
||||
"description": "The macro toolkit ;)",
|
||||
"contributors": [
|
||||
"back2dos"
|
||||
],
|
||||
"releasenote": "Support the new eval target.",
|
||||
"version": "0.14.0",
|
||||
"url": "http://haxetink.org/tink_macro",
|
||||
"dependencies": {
|
||||
"tink_core": ""
|
||||
}
|
||||
"license": "MIT"
|
||||
}
|
@@ -4,6 +4,7 @@ import haxe.macro.Expr.TypeDefinition;
|
||||
|
||||
using tink.CoreApi;
|
||||
using tink.macro.Positions;
|
||||
using StringTools;
|
||||
|
||||
typedef Positions = tink.macro.Positions;
|
||||
typedef ExprTools = haxe.macro.ExprTools;
|
||||
@@ -28,7 +29,20 @@ typedef TypeResolution = Ref<Either<String, TypeDefinition>>;
|
||||
|
||||
class MacroApi {
|
||||
|
||||
static var idCounter = 0;
|
||||
static var MAIN_CANDIDATES = ['-main', '-x', '--run'];
|
||||
static public function getMainClass():Option<String> {
|
||||
var args = Sys.args();
|
||||
|
||||
for (c in MAIN_CANDIDATES)
|
||||
switch args.indexOf(c) {
|
||||
case -1:
|
||||
case v: return Some(args[v+1]);
|
||||
}
|
||||
|
||||
return None;
|
||||
}
|
||||
|
||||
@:persistent static var idCounter = 0;
|
||||
|
||||
@:noUsing static public inline function tempName(?prefix:String = 'tmp'):String
|
||||
return '__tink_' + prefix + Std.string(idCounter++);
|
||||
@@ -36,4 +50,90 @@ class MacroApi {
|
||||
static public function pos()
|
||||
return haxe.macro.Context.currentPos();
|
||||
|
||||
static public var completionPoint(default, null):Option<{
|
||||
var file(default, never):String;
|
||||
var pos(default, never):Int;
|
||||
}>;
|
||||
|
||||
static public var args(default, null):Iterable<String>;
|
||||
static var initialized = initArgs();
|
||||
|
||||
static function initArgs() {
|
||||
var sysArgs = Sys.args();
|
||||
args = sysArgs;
|
||||
completionPoint = switch sysArgs.indexOf('--display') {
|
||||
case -1: None;
|
||||
case sysArgs[_ + 1] => arg:
|
||||
if (arg.startsWith('{"jsonrpc":')) {
|
||||
var payload:{
|
||||
jsonrpc:String,
|
||||
method:String,
|
||||
params:{
|
||||
file:String,
|
||||
offset:Int,
|
||||
}
|
||||
} = haxe.Json.parse(arg);
|
||||
switch payload {
|
||||
case { jsonrpc: '2.0', method: 'display/completion' }:
|
||||
Some({
|
||||
file: payload.params.file,
|
||||
pos: payload.params.offset,
|
||||
});
|
||||
default: None;
|
||||
}
|
||||
}
|
||||
else None;
|
||||
}
|
||||
try haxe.macro.Context.onMacroContextReused(initArgs)
|
||||
catch (all:Dynamic) {}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
#if (haxe_ver >= 4)
|
||||
typedef ObjectField = haxe.macro.Expr.ObjectField;
|
||||
typedef QuoteStatus = haxe.macro.Expr.QuoteStatus;
|
||||
#else
|
||||
enum QuoteStatus {
|
||||
Unquoted;
|
||||
Quoted;
|
||||
}
|
||||
private typedef F = {
|
||||
var field:String;
|
||||
var expr:haxe.macro.Expr;
|
||||
}
|
||||
|
||||
@:forward
|
||||
abstract ObjectField(F) to F {
|
||||
|
||||
static var QUOTED = "@$__hx__";
|
||||
|
||||
inline function new(o) this = o;
|
||||
|
||||
public var field(get, never):String;
|
||||
|
||||
function get_field()
|
||||
return
|
||||
if (quotes == Quoted)
|
||||
this.field.substr(QUOTED.length);
|
||||
else this.field;
|
||||
|
||||
public var quotes(get, never):QuoteStatus;
|
||||
|
||||
function get_quotes()
|
||||
return if (StringTools.startsWith(this.field, QUOTED)) Quoted else Unquoted;
|
||||
|
||||
@:from static function ofFull(o:{>F, quotes:QuoteStatus }):ObjectField
|
||||
return switch o.quotes {
|
||||
case null | Unquoted:
|
||||
new ObjectField({ field: o.field, expr: o.expr });
|
||||
default:
|
||||
new ObjectField({ field: QUOTED + o.field, expr: o.expr });
|
||||
}
|
||||
|
||||
@:from static function ofOld(o:F):ObjectField
|
||||
return new ObjectField(o);
|
||||
}
|
||||
#end
|
@@ -33,7 +33,7 @@ typedef BuildContext3 = {>BuildContext2,
|
||||
|
||||
class BuildCache {
|
||||
|
||||
static var cache = new Map();
|
||||
@:persistent static var cache = new Map();
|
||||
|
||||
static public function getType3(name, ?types, ?pos:Position, build:BuildContext3->TypeDefinition) {
|
||||
if (types == null)
|
||||
@@ -74,7 +74,11 @@ class BuildCache {
|
||||
var compound = ComplexType.TAnonymous([for (i in 0...types.length) {
|
||||
name: 't$i',
|
||||
pos: pos,
|
||||
kind: FVar(types[i].toComplexType()),
|
||||
kind: FVar(switch types[i] {
|
||||
case TInst(_.get().kind => KExpr(e), _):
|
||||
TPath('tink.macro.ConstParam'.asTypePath([TPExpr(e)]));
|
||||
case t: t.toComplex();
|
||||
}),
|
||||
}]).toType();
|
||||
|
||||
return getType(name, compound, pos, function (ctx) return build({
|
||||
@@ -106,22 +110,30 @@ class BuildCache {
|
||||
}));
|
||||
}
|
||||
|
||||
static public function getParams(name:String, ?pos:Position)
|
||||
return
|
||||
switch Context.getLocalType() {
|
||||
case TInst(_.toString() == name => true, v):
|
||||
Success(v);
|
||||
case TInst(_.get() => { pos: pos }, _):
|
||||
pos.makeFailure('Expected $name');
|
||||
case v:
|
||||
pos.makeFailure('$v should be a class');
|
||||
}
|
||||
|
||||
static public function getParam(name:String, ?pos:Position)
|
||||
return
|
||||
getParams(name, pos)
|
||||
.flatMap(function (args:Array<Type>) return switch args {
|
||||
case [v]: Success(v);
|
||||
case []: pos.makeFailure('type parameter expected');
|
||||
default: pos.makeFailure('too many parameters');
|
||||
});
|
||||
|
||||
static public function getType(name, ?type, ?pos:Position, build:BuildContext->TypeDefinition) {
|
||||
|
||||
if (pos == null)
|
||||
pos = Context.currentPos();
|
||||
|
||||
if (type == null)
|
||||
switch Context.getLocalType() {
|
||||
case TInst(_.toString() == name => true, [v]):
|
||||
type = v;
|
||||
case TInst(_.toString() == name => true, _):
|
||||
Context.fatalError('type parameter expected', pos);
|
||||
case TInst(_.get() => { pos: pos }, _):
|
||||
Context.fatalError('Expected $name', pos);
|
||||
default:
|
||||
throw 'assert';
|
||||
}
|
||||
type = getParam(name, pos).sure();
|
||||
|
||||
var forName =
|
||||
switch cache[name] {
|
||||
@@ -129,7 +141,9 @@ class BuildCache {
|
||||
case v: v;
|
||||
}
|
||||
|
||||
return forName.get(type, pos, build);
|
||||
var ret = forName.get(type, pos.sanitize(), build);
|
||||
ret.getFields();// workaround for https://github.com/HaxeFoundation/haxe/issues/7905
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -63,7 +63,9 @@ class ClassBuilder {
|
||||
if (cl.constructor != null) {
|
||||
try {
|
||||
var ctor = cl.constructor.get();
|
||||
var func = Context.getTypedExpr(ctor.expr()).getFunction().sure();
|
||||
var ctorExpr = ctor.expr();
|
||||
if (ctorExpr == null) throw 'Super constructor has no expression';
|
||||
var func = Context.getTypedExpr(ctorExpr).getFunction().sure();
|
||||
|
||||
for (arg in func.args) //this is to deal with type parameter substitutions
|
||||
arg.type = null;
|
||||
@@ -175,6 +177,12 @@ class ClassBuilder {
|
||||
return m;
|
||||
}
|
||||
|
||||
public function addMembers(td:TypeDefinition):Array<Member> {
|
||||
for (f in td.fields)
|
||||
addMember(f);
|
||||
return td.fields;
|
||||
}
|
||||
|
||||
public function addMember(m:Member, ?front:Bool = false):Member {
|
||||
doAddMember(m, front);
|
||||
|
||||
@@ -190,4 +198,4 @@ class ClassBuilder {
|
||||
p(builder);
|
||||
return builder.export(verbose);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
3
src/tink/macro/ConstParam.hx
Normal file
3
src/tink/macro/ConstParam.hx
Normal file
@@ -0,0 +1,3 @@
|
||||
package tink.macro;
|
||||
|
||||
class ConstParam<Const> {}
|
@@ -1,8 +1,10 @@
|
||||
package tink.macro;
|
||||
|
||||
import haxe.macro.Type;
|
||||
import haxe.macro.Expr;
|
||||
import haxe.macro.Context;
|
||||
import tink.core.Pair;
|
||||
using haxe.macro.Tools;
|
||||
using tink.MacroApi;
|
||||
|
||||
enum FieldInit {
|
||||
@@ -62,6 +64,10 @@ class Constructor {
|
||||
default: [].toBlock();
|
||||
}
|
||||
}
|
||||
|
||||
public function getArgList():Array<FunctionArg>
|
||||
return beforeArgs.concat(args).concat(afterArgs);
|
||||
|
||||
public function addStatement(e:Expr, ?prepend)
|
||||
if (prepend)
|
||||
this.nuStatements.unshift(e)
|
||||
@@ -90,13 +96,49 @@ class Constructor {
|
||||
}
|
||||
|
||||
var tmp = MacroApi.tempName();
|
||||
var member = owner.memberByName(name).sure();
|
||||
|
||||
if (options.bypass) {
|
||||
switch owner.memberByName(name) {
|
||||
case Success(member): member.addMeta(':isVar');
|
||||
default:
|
||||
}
|
||||
addStatement(macro @:pos(pos) (cast this).$name = if (true) $e else this.$name, options.prepend);//TODO: this seems to report type errors here rather than at the declaration position
|
||||
if (options.bypass && member.kind.match(FProp(_, 'never' | 'set', _, _))) {
|
||||
|
||||
member.addMeta(':isVar');
|
||||
|
||||
addStatement((function () {
|
||||
var fields = [for (f in (macro this).typeof().sure().getClass().fields.get()) f.name => f];
|
||||
|
||||
function setDirectly(t:TypedExpr) {
|
||||
var direct = null;
|
||||
function seek(t:TypedExpr) {
|
||||
switch t.expr {
|
||||
case TField({ expr: TConst(TThis) }, FInstance(_, _, f)) if (f.get().name == name): direct = t;
|
||||
default: t.iter(seek);
|
||||
}
|
||||
}
|
||||
seek(t);
|
||||
if (direct == null) pos.error('nope');
|
||||
var direct = Context.storeTypedExpr(direct);
|
||||
return macro @:pos(pos) $direct = $e;
|
||||
}
|
||||
|
||||
return switch fields[name] {
|
||||
case null:
|
||||
pos.error('this direct initialization causes the compiler to do really weird things');
|
||||
case f:
|
||||
switch f.kind {
|
||||
case FVar(_, AccNormal | AccNo):
|
||||
macro @:pos(pos) this.$name = $e;
|
||||
case FVar(AccNever, AccNever):
|
||||
macro @:pos(pos) this.$name = $e;
|
||||
case FVar(AccNo | AccNormal, AccNever):
|
||||
setDirectly(Context.typeExpr(macro @:pos(pos) this.$name));
|
||||
case FVar(AccCall, AccNever):
|
||||
setDirectly(fields['get_$name'].expr());
|
||||
case FVar(_, AccCall):
|
||||
setDirectly(fields['set_$name'].expr());
|
||||
default:
|
||||
pos.error('not implemented');
|
||||
}
|
||||
}
|
||||
}).bounce(), options.prepend);
|
||||
}
|
||||
else
|
||||
addStatement(macro @:pos(pos) this.$name = $e, options.prepend);
|
||||
@@ -132,4 +174,4 @@ class Constructor {
|
||||
meta : this.meta,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -43,8 +43,11 @@ class Exprs {
|
||||
}
|
||||
|
||||
static public inline function is(e:Expr, c:ComplexType)
|
||||
return ECheckType(e, c).at(e.pos).typeof().isSuccess();
|
||||
|
||||
return e.as(c).typeof().isSuccess();
|
||||
|
||||
static public inline function as(e:Expr, c:ComplexType)
|
||||
return ECheckType(e, c).at(e.pos);
|
||||
|
||||
static public function finalize(e:Expr, ?nuPos:Position, ?rules:Dynamic<String>, ?skipFields = false, ?callPos:PosInfos) {
|
||||
if (nuPos == null)
|
||||
nuPos = Context.currentPos();
|
||||
@@ -241,7 +244,7 @@ class Exprs {
|
||||
}
|
||||
|
||||
static public inline function iterate(target:Expr, body:Expr, ?loopVar:String = 'i', ?pos:Position)
|
||||
return EFor(EIn(loopVar.resolve(pos), target).at(pos), body).at(pos);
|
||||
return macro @:pos(pos.sanitize()) for ($i{loopVar} in $target) $body;
|
||||
|
||||
static public function toFields(object:Dynamic<Expr>, ?pos:Position)
|
||||
return EObjectDecl([for (field in Reflect.fields(object))
|
||||
@@ -311,17 +314,45 @@ class Exprs {
|
||||
|
||||
static public inline function resolve(s:String, ?pos)
|
||||
return drill(s.split('.'), pos);
|
||||
|
||||
static var scopes = new Array<Array<Var>>();
|
||||
|
||||
static function inScope<T>(a:Array<Var>, f:Void->T) {
|
||||
scopes.push(a);
|
||||
|
||||
inline function leave()
|
||||
scopes.pop();
|
||||
try {
|
||||
var ret = f();
|
||||
leave();
|
||||
return ret;
|
||||
}
|
||||
catch (e:Dynamic) {
|
||||
leave();
|
||||
return Error.rethrow(e);
|
||||
}
|
||||
}
|
||||
|
||||
static public function scoped<T>(f:Void->T)
|
||||
return inScope([], f);
|
||||
|
||||
static public function inSubScope<T>(f:Void->T, a:Array<Var>)
|
||||
return inScope(switch scopes[scopes.length - 1] {
|
||||
case null: a;
|
||||
case v: v.concat(a);
|
||||
}, f);
|
||||
|
||||
static public function typeof(expr:Expr, ?locals)
|
||||
return
|
||||
try {
|
||||
if (locals == null)
|
||||
locals = scopes[scopes.length - 1];
|
||||
if (locals != null)
|
||||
expr = [EVars(locals).at(expr.pos), expr].toMBlock(expr.pos);
|
||||
Success(Context.typeof(expr));
|
||||
}
|
||||
catch (e:Error) {
|
||||
var m:Dynamic = e.message;
|
||||
e.pos.makeFailure(m);
|
||||
catch (e:haxe.macro.Error) {
|
||||
e.pos.makeFailure(e.message);
|
||||
}
|
||||
catch (e:Dynamic) {
|
||||
expr.pos.makeFailure(e);
|
||||
@@ -400,6 +431,22 @@ class Exprs {
|
||||
}
|
||||
}
|
||||
|
||||
static var FIRST = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
||||
static var LATER = FIRST + '0123456789';
|
||||
|
||||
static public function shortIdent(i:Int) {
|
||||
var ret = FIRST.charAt(i % FIRST.length);
|
||||
|
||||
i = Std.int(i / FIRST.length);
|
||||
|
||||
while (i > 0) {
|
||||
ret += LATER.charAt(i % LATER.length);
|
||||
i = Std.int(i / LATER.length);
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
static inline var NOT_AN_INT = "integer constant expected";
|
||||
static inline var NOT_AN_IDENT = "identifier expected";
|
||||
static inline var NOT_A_STRING = "string constant expected";
|
||||
|
@@ -9,7 +9,7 @@ abstract Member(Field) from Field to Field {
|
||||
name: name,
|
||||
pos: pos,
|
||||
access: [APublic],
|
||||
kind: FProp(noread ? 'null' : 'get_' + name, nowrite ? 'null' : ('set_' + name), t),
|
||||
kind: FProp(noread ? 'null' : 'get', nowrite ? 'null' : 'set', t),
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
@@ -32,6 +32,7 @@ abstract Member(Field) from Field to Field {
|
||||
}
|
||||
|
||||
public var name(get, set):String;
|
||||
public var meta(get, set):Metadata;
|
||||
public var doc(get, set):Null<String>;
|
||||
public var kind(get, set):FieldType;
|
||||
public var pos(get, set):Position;
|
||||
@@ -39,6 +40,22 @@ abstract Member(Field) from Field to Field {
|
||||
public var isStatic(get, set):Bool;
|
||||
public var isPublic(get, set):Null<Bool>;
|
||||
public var isBound(get, set):Null<Bool>;
|
||||
#if haxe4
|
||||
/**
|
||||
* Setting this to true will erase any getters/setters.
|
||||
*/
|
||||
public var isFinal(get, set):Bool;
|
||||
function get_isFinal() return hasAccess(AFinal);
|
||||
function set_isFinal(param) {
|
||||
if (setAccess(AFinal, param)) //TODO: perhaps also do something about AInline
|
||||
switch kind {
|
||||
case FProp(_, _, t, e):
|
||||
kind = FVar(t, e);
|
||||
default:
|
||||
}
|
||||
return param;
|
||||
}
|
||||
#end
|
||||
|
||||
public function getFunction()
|
||||
return
|
||||
@@ -76,6 +93,11 @@ abstract Member(Field) from Field to Field {
|
||||
}
|
||||
return pos.makeFailure('missing @$name');
|
||||
}
|
||||
|
||||
public function metaNamed(name)
|
||||
return
|
||||
if (this.meta == null) [];
|
||||
else [for (tag in this.meta) if (tag.name == name) tag];
|
||||
|
||||
public inline function asField():Field return this;
|
||||
public function publish()
|
||||
@@ -86,6 +108,12 @@ abstract Member(Field) from Field to Field {
|
||||
this.access.push(APublic);
|
||||
}
|
||||
|
||||
inline function get_meta() return switch this.meta {
|
||||
case null: this.meta = [];
|
||||
case v: v;
|
||||
}
|
||||
inline function set_meta(param) return this.meta = param;
|
||||
|
||||
inline function get_name() return this.name;
|
||||
inline function set_name(param) return this.name = param;
|
||||
|
||||
@@ -99,21 +127,10 @@ abstract Member(Field) from Field to Field {
|
||||
inline function set_pos(param) return this.pos = param;
|
||||
|
||||
inline function get_overrides() return hasAccess(AOverride);
|
||||
inline function set_overrides(param) {
|
||||
changeAccess(
|
||||
param ? AOverride : null,
|
||||
param ? null : AOverride
|
||||
);
|
||||
return param;
|
||||
}
|
||||
inline function set_overrides(param) return setAccess(AOverride, param);
|
||||
|
||||
inline function get_isStatic() return hasAccess(AStatic);
|
||||
function set_isStatic(param) {
|
||||
changeAccess(
|
||||
param ? AStatic : null,
|
||||
param ? null : AStatic
|
||||
);
|
||||
return param;
|
||||
}
|
||||
inline function set_isStatic(param) return setAccess(AStatic, param);
|
||||
|
||||
function get_isPublic() {
|
||||
if (this.access != null)
|
||||
@@ -167,6 +184,15 @@ abstract Member(Field) from Field to Field {
|
||||
if (x == a) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function setAccess(a:Access, isset:Bool) {
|
||||
changeAccess(
|
||||
isset ? a : null,
|
||||
isset ? null : a
|
||||
);
|
||||
return isset;
|
||||
}
|
||||
|
||||
|
||||
function changeAccess(add:Access, remove:Access) {
|
||||
var i = 0;
|
||||
@@ -190,4 +216,4 @@ abstract Member(Field) from Field to Field {
|
||||
if (add != null)
|
||||
this.access.push(add);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -3,6 +3,7 @@ package tink.macro;
|
||||
import haxe.macro.Expr;
|
||||
|
||||
class Metadatas {
|
||||
static var printer = new haxe.macro.Printer();
|
||||
static public function toMap(m:Metadata) {
|
||||
var ret = new Map<String,Array<Array<Expr>>>();
|
||||
if (m != null)
|
||||
@@ -18,4 +19,8 @@ class Metadatas {
|
||||
return
|
||||
if (m == null) [];
|
||||
else [for (meta in m) if (meta.name == name) meta.params];
|
||||
|
||||
static public inline function toString(m:MetadataEntry) {
|
||||
return printer.printMetadata(m);
|
||||
}
|
||||
}
|
@@ -12,7 +12,7 @@ class Positions {
|
||||
return
|
||||
switch outcome {
|
||||
case Success(d): d;
|
||||
case Failure(f): sanitize(pos).error(f);
|
||||
case Failure(f): pos.error(f);
|
||||
}
|
||||
|
||||
static public function makeBlankType(pos:Position):ComplexType
|
||||
@@ -32,7 +32,17 @@ class Positions {
|
||||
|
||||
|
||||
static public function error(pos:Position, error:Dynamic):Dynamic
|
||||
return errorFunc(sanitize(pos), Std.string(error));
|
||||
return
|
||||
switch Std.instance(error, tink.core.Error) {
|
||||
case null: errorFunc(sanitize(pos), Std.string(error));
|
||||
case error:
|
||||
errorFunc(
|
||||
error.pos,
|
||||
error.message +
|
||||
if (pos == null) ''
|
||||
else ' (referenced from ' + Std.string(pos).substr(5)
|
||||
);
|
||||
}
|
||||
|
||||
static function contextError(pos:Position, error:String):Dynamic
|
||||
return Context.fatalError(error, pos);
|
||||
|
@@ -17,19 +17,28 @@ class Sisyphus {
|
||||
case AccCall: getOrSet;
|
||||
case AccInline: "default";
|
||||
case AccRequire(_, _): "default";
|
||||
default: throw "not implemented";
|
||||
}
|
||||
}
|
||||
if (cf.params.length == 0) {
|
||||
name: cf.name,
|
||||
doc: cf.doc,
|
||||
access: cf.isPublic ? [ APublic ] : [ APrivate ],
|
||||
access:
|
||||
(cf.isPublic ? [ APublic ] : [ APrivate ])
|
||||
#if haxe4 .concat(if (cf.isFinal) [AFinal] else []) #end
|
||||
,
|
||||
kind: switch([ cf.kind, cf.type ]) {
|
||||
#if haxe4
|
||||
case [ FVar(_, _), ret ] if (cf.isFinal):
|
||||
FVar(toComplexType(ret), null);
|
||||
#end
|
||||
case [ FVar(read, write), ret ]:
|
||||
FProp(
|
||||
varAccessToString(read, "get"),
|
||||
varAccessToString(write, "set"),
|
||||
toComplexType(ret),
|
||||
null);
|
||||
null
|
||||
);
|
||||
case [ FMethod(_), TFun(args, ret) ]:
|
||||
FFun({
|
||||
args: [
|
||||
@@ -52,21 +61,33 @@ class Sisyphus {
|
||||
}
|
||||
}
|
||||
|
||||
public static function toComplexType(type : Null<Type>) : Null<ComplexType> return
|
||||
|
||||
public static function toComplexType(type : Null<Type>) : Null<ComplexType> return {
|
||||
inline function direct()
|
||||
return Types.toComplex(type, { direct: true });
|
||||
switch (type) {
|
||||
case null:
|
||||
null;
|
||||
case TMono(_.get() => t):
|
||||
t == null ? Types.toComplex(type, { direct: true }) : toComplexType(t);
|
||||
case TEnum(_.get().isPrivate => true, _): direct();
|
||||
case TInst(_.get().isPrivate => true, _): direct();
|
||||
case TType(_.get().isPrivate => true, _): direct();
|
||||
case TAbstract(_.get().isPrivate => true, _): direct();
|
||||
case TMono(_): direct();
|
||||
case TEnum(_.get() => baseType, params):
|
||||
TPath(toTypePath(baseType, params));
|
||||
case TInst(_.get() => classType, params):
|
||||
switch (classType.kind) {
|
||||
case KTypeParameter(_):
|
||||
TPath({
|
||||
name: classType.name,
|
||||
pack: [],
|
||||
});
|
||||
var ct = Types.asComplexType(classType.name);
|
||||
switch Types.toType(ct) {
|
||||
case Success(TInst(_.get() => cl, _)) if (
|
||||
cl.kind.match(KTypeParameter(_))
|
||||
&& cl.module == classType.module
|
||||
&& cl.pack.join('.') == classType.pack.join('.')
|
||||
): ct;
|
||||
default:
|
||||
direct();
|
||||
}
|
||||
default:
|
||||
TPath(toTypePath(classType, params));
|
||||
}
|
||||
@@ -92,14 +113,23 @@ class Sisyphus {
|
||||
default:
|
||||
throw "Invalid type";
|
||||
}
|
||||
|
||||
}
|
||||
static function toTypePath(baseType : BaseType, params : Array<Type>) : TypePath return {
|
||||
var module = baseType.module;
|
||||
var name = module.substring(module.lastIndexOf(".") + 1);
|
||||
var sub = switch baseType.name {
|
||||
case _ == name => true: null;
|
||||
case v: v;
|
||||
}
|
||||
|
||||
{
|
||||
pack: baseType.pack,
|
||||
name: module.substring(module.lastIndexOf(".") + 1),
|
||||
sub: baseType.name,
|
||||
params: [ for (t in params) TPType(toComplexType(t)) ],
|
||||
name: name,
|
||||
sub: sub,
|
||||
params: [for (t in params) switch t {
|
||||
case TInst(_.get().kind => KExpr(e), _): TPExpr(e);
|
||||
default: TPType(toComplexType(t));
|
||||
}],
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -5,7 +5,6 @@ import haxe.ds.BalancedTree;
|
||||
import haxe.macro.Context;
|
||||
import haxe.macro.Type;
|
||||
|
||||
using haxe.macro.Tools;
|
||||
using tink.MacroApi;
|
||||
|
||||
class TypeMap<V> extends BalancedTree<Type, V> implements IMap<Type, V> {
|
||||
@@ -16,18 +15,7 @@ class TypeMap<V> extends BalancedTree<Type, V> implements IMap<Type, V> {
|
||||
super();
|
||||
}
|
||||
|
||||
override function compare(k1:Type, k2:Type):Int {
|
||||
|
||||
if (follow) {
|
||||
k1 = k1.reduce();
|
||||
k2 = k2.reduce();
|
||||
}
|
||||
|
||||
return switch k1.getIndex() - k2.getIndex() {
|
||||
case 0:
|
||||
Reflect.compare(k1.toString(), k2.toString());//much to my surprise, this actually seems to work (at least with 3.4)
|
||||
case v: v;
|
||||
}
|
||||
}
|
||||
override function compare(k1:Type, k2:Type):Int
|
||||
return k1.compare(k2, follow);
|
||||
|
||||
}
|
@@ -1,196 +1,282 @@
|
||||
package tink.macro;
|
||||
|
||||
import haxe.macro.Printer;
|
||||
import Type in Enums;
|
||||
|
||||
import haxe.macro.Context;
|
||||
import haxe.macro.Expr;
|
||||
import haxe.macro.Type;
|
||||
|
||||
using tink.macro.Exprs;
|
||||
using tink.macro.Positions;
|
||||
using tink.macro.Functions;
|
||||
using tink.CoreApi;
|
||||
|
||||
class Types {
|
||||
|
||||
static public function definedType(typeName:String)
|
||||
return
|
||||
try {
|
||||
Some(Context.getType(typeName));
|
||||
}
|
||||
catch (e:Dynamic)
|
||||
if (Std.string(e) == 'Type not found \'$typeName\'') None;
|
||||
else tink.core.Error.rethrow(e);
|
||||
|
||||
static var types = new Map<Int,Void->Type>();
|
||||
static var idCounter = 0;
|
||||
static public function getID(t:Type, ?reduced = true)
|
||||
return
|
||||
if (reduced)
|
||||
getID(reduce(t), false);
|
||||
else
|
||||
switch (t) {
|
||||
case TAbstract(t, _): t.toString();
|
||||
case TInst(t, _): t.toString();
|
||||
case TEnum(t, _): t.toString();
|
||||
case TType(t, _): t.toString();
|
||||
default: null;
|
||||
}
|
||||
|
||||
static public function accessToName(v:VarAccess, ?read = true)
|
||||
return
|
||||
switch (v) {
|
||||
case AccNormal, AccInline: 'default';
|
||||
case AccNo: 'null';
|
||||
case AccNever: 'never';
|
||||
case AccCall: if (read) 'get' else 'set';
|
||||
default:
|
||||
throw 'not implemented';
|
||||
}
|
||||
|
||||
static public function getMeta(type:Type)
|
||||
return switch type {
|
||||
case TInst(_.get().meta => m, _): [m];
|
||||
case TEnum(_.get().meta => m, _): [m];
|
||||
case TAbstract(_.get().meta => m, _): [m];
|
||||
case TType(_.get() => t, _): [t.meta].concat(getMeta(t.type));
|
||||
case TLazy(f): getMeta(f());
|
||||
default: [];
|
||||
}
|
||||
|
||||
static function getDeclaredFields(t:ClassType, out:Array<ClassField>, marker:Map<String,Bool>) {
|
||||
for (field in t.fields.get())
|
||||
if (!marker.exists(field.name)) {
|
||||
marker.set(field.name, true);
|
||||
out.push(field);
|
||||
}
|
||||
if (t.isInterface)
|
||||
for (t in t.interfaces)
|
||||
getDeclaredFields(t.t.get(), out, marker);
|
||||
else if (t.superClass != null)
|
||||
getDeclaredFields(t.superClass.t.get(), out, marker);
|
||||
}
|
||||
|
||||
static var fieldsCache = new Map();
|
||||
static public function getFields(t:Type, ?substituteParams = true)
|
||||
return
|
||||
switch (reduce(t)) {
|
||||
case TInst(c, params):
|
||||
var id = c.toString(),
|
||||
c = c.get();
|
||||
if (!fieldsCache.exists(id)) {
|
||||
var fields = [];
|
||||
getDeclaredFields(c, fields, new Map());
|
||||
fieldsCache.set(id, Success(fields));
|
||||
}
|
||||
var ret = fieldsCache.get(id);
|
||||
if (substituteParams && ret.isSuccess()) {
|
||||
var fields = Reflect.copy(ret.sure());
|
||||
|
||||
for (field in fields)
|
||||
field.type = haxe.macro.TypeTools.applyTypeParameters(field.type, c.params, params);
|
||||
}
|
||||
fieldsCache.remove(id);//TODO: find a proper solution to avoid stale cache
|
||||
ret;
|
||||
case TAnonymous(anon): Success(anon.get().fields);
|
||||
default: Context.currentPos().makeFailure('type has no fields');
|
||||
}
|
||||
|
||||
static public function getStatics(t:Type)
|
||||
return
|
||||
switch (reduce(t)) {
|
||||
case TInst(t, _): Success(t.get().statics.get());
|
||||
default: Failure('type has no statics');
|
||||
}
|
||||
|
||||
static public function toString(t:ComplexType)
|
||||
return new Printer().printComplexType(t);
|
||||
|
||||
static public function isSubTypeOf(t:Type, of:Type, ?pos)
|
||||
return
|
||||
ECheckType(ECheckType(macro null, toComplex(t)).at(pos), toComplex(of)).at(pos).typeof();
|
||||
|
||||
static public function isDynamic(t:Type)
|
||||
return switch reduce(t) {
|
||||
case TDynamic(_): true;
|
||||
default: false;
|
||||
}
|
||||
|
||||
static public function toType(t:ComplexType, ?pos:Position)
|
||||
return (macro @:pos(pos.sanitize()) {
|
||||
var v:$t = null;
|
||||
v;
|
||||
}).typeof();
|
||||
|
||||
static public inline function instantiate(t:TypePath, ?args, ?pos)
|
||||
return ENew(t, args == null ? [] : args).at(pos);
|
||||
|
||||
static public function asTypePath(s:String, ?params):TypePath {
|
||||
var parts = s.split('.');
|
||||
var name = parts.pop(),
|
||||
sub = null;
|
||||
if (parts.length > 0 && parts[parts.length - 1].charCodeAt(0) < 0x5B) {
|
||||
sub = name;
|
||||
name = parts.pop();
|
||||
if(sub == name) sub = null;
|
||||
}
|
||||
return {
|
||||
name: name,
|
||||
pack: parts,
|
||||
params: params == null ? [] : params,
|
||||
sub: sub
|
||||
};
|
||||
}
|
||||
|
||||
static public inline function asComplexType(s:String, ?params)
|
||||
return TPath(asTypePath(s, params));
|
||||
|
||||
static public inline function reduce(type:Type, ?once)
|
||||
return Context.follow(type, once);
|
||||
|
||||
static public function isVar(field:ClassField)
|
||||
return switch (field.kind) {
|
||||
case FVar(_, _): true;
|
||||
default: false;
|
||||
}
|
||||
|
||||
static public function register(type:Void->Type):Int {
|
||||
types.set(idCounter, type);
|
||||
return idCounter++;
|
||||
}
|
||||
|
||||
static function paramsToComplex(params:Array<Type>):Array<TypeParam>
|
||||
return [for (p in params) TPType(toComplex(p))];
|
||||
|
||||
static function baseToComplex(t:BaseType, params:Array<Type>)
|
||||
return asComplexType(t.module + '.' + t.name, paramsToComplex(params));
|
||||
|
||||
static public function toComplex(type:Type, ?options:{ ?direct: Bool }):ComplexType {
|
||||
var ret =
|
||||
if (options == null || options.direct != true) tink.macro.Sisyphus.toComplexType(type);
|
||||
else null;
|
||||
if (ret == null)
|
||||
ret = lazyComplex(function () return type);
|
||||
return ret;
|
||||
}
|
||||
|
||||
static public function lazyComplex(f:Void->Type)
|
||||
return
|
||||
TPath({
|
||||
pack : ['tink','macro'],
|
||||
name : 'DirectType',
|
||||
params : [TPExpr(register(f).toExpr())],
|
||||
sub : null,
|
||||
});
|
||||
|
||||
static function resolveDirectType()
|
||||
return
|
||||
switch reduce(Context.getLocalType()) {
|
||||
case TInst(_, [TInst(_.get() => { kind: KExpr(e) }, _)]):
|
||||
types[e.getInt().sure()]();//When using compiler server, this call throws on occasion, in which case modifying this file (to update mtime and invalidate the cache) will solve the problem
|
||||
default:
|
||||
throw 'assert';
|
||||
}
|
||||
|
||||
}
|
||||
package tink.macro;
|
||||
|
||||
import haxe.macro.Printer;
|
||||
|
||||
import haxe.macro.Context;
|
||||
import haxe.macro.Expr;
|
||||
import haxe.macro.Type;
|
||||
|
||||
using haxe.macro.Tools;
|
||||
using tink.MacroApi;
|
||||
using tink.CoreApi;
|
||||
|
||||
class Types {
|
||||
|
||||
static public function definedType(typeName:String)
|
||||
return
|
||||
try {
|
||||
Some(Context.getType(typeName));
|
||||
}
|
||||
catch (e:Dynamic)
|
||||
if (Std.string(e) == 'Type not found \'$typeName\'') None;
|
||||
else tink.core.Error.rethrow(e);
|
||||
|
||||
static var types = new Map<Int,Void->Type>();
|
||||
static var idCounter = 0;
|
||||
static public function getID(t:Type, ?reduced = true)
|
||||
return
|
||||
if (reduced)
|
||||
getID(reduce(t), false);
|
||||
else
|
||||
switch (t) {
|
||||
case TAbstract(t, _): t.toString();
|
||||
case TInst(t, _): t.toString();
|
||||
case TEnum(t, _): t.toString();
|
||||
case TType(t, _): t.toString();
|
||||
default: null;
|
||||
}
|
||||
|
||||
static public function accessToName(v:VarAccess, ?read = true)
|
||||
return
|
||||
switch (v) {
|
||||
case AccNormal, AccInline: 'default';
|
||||
case AccNo: 'null';
|
||||
case AccNever: 'never';
|
||||
case AccCall: if (read) 'get' else 'set';
|
||||
default:
|
||||
throw 'not implemented';
|
||||
}
|
||||
|
||||
static public function getMeta(type:Type)
|
||||
return switch type {
|
||||
case TInst(_.get().meta => m, _): [m];
|
||||
case TEnum(_.get().meta => m, _): [m];
|
||||
case TAbstract(_.get().meta => m, _): [m];
|
||||
case TType(_.get() => t, _): [t.meta].concat(getMeta(t.type));
|
||||
case TLazy(f): getMeta(f());
|
||||
default: [];
|
||||
}
|
||||
|
||||
static function getDeclaredFields(t:ClassType, out:Array<ClassField>, marker:Map<String,Bool>) {
|
||||
for (field in t.fields.get())
|
||||
if (!marker.exists(field.name)) {
|
||||
marker.set(field.name, true);
|
||||
out.push(field);
|
||||
}
|
||||
if (t.isInterface)
|
||||
for (t in t.interfaces)
|
||||
getDeclaredFields(t.t.get(), out, marker);
|
||||
else if (t.superClass != null)
|
||||
getDeclaredFields(t.superClass.t.get(), out, marker);
|
||||
}
|
||||
|
||||
static var fieldsCache = new Map();
|
||||
static public function getFields(t:Type, ?substituteParams = true)
|
||||
return
|
||||
switch (reduce(t)) {
|
||||
case TInst(c, params):
|
||||
var id = c.toString(),
|
||||
c = c.get();
|
||||
if (!fieldsCache.exists(id)) {
|
||||
var fields = [];
|
||||
getDeclaredFields(c, fields, new Map());
|
||||
fieldsCache.set(id, Success(fields));
|
||||
}
|
||||
var ret = fieldsCache.get(id);
|
||||
if (substituteParams && ret.isSuccess()) {
|
||||
var fields = Reflect.copy(ret.sure());
|
||||
|
||||
for (field in fields)
|
||||
field.type = haxe.macro.TypeTools.applyTypeParameters(field.type, c.params, params);
|
||||
}
|
||||
fieldsCache.remove(id);//TODO: find a proper solution to avoid stale cache
|
||||
ret;
|
||||
case TAnonymous(anon): Success(anon.get().fields);
|
||||
default: Context.currentPos().makeFailure('type $t has no fields');
|
||||
}
|
||||
|
||||
static public function getStatics(t:Type)
|
||||
return
|
||||
switch (reduce(t)) {
|
||||
case TInst(t, _): Success(t.get().statics.get());
|
||||
default: Failure('type has no statics');
|
||||
}
|
||||
|
||||
|
||||
static public function getPosition(t:Type)
|
||||
return
|
||||
switch t {
|
||||
case TInst(_.get() => {pos: pos}, _)
|
||||
| TAbstract(_.get() => {pos: pos}, _)
|
||||
| TType(_.get() => {pos: pos}, _)
|
||||
| TEnum(_.get() => {pos: pos}, _) : Success(pos);
|
||||
case TMono(_.get() => t) if (t != null): getPosition(t);
|
||||
case TLazy(f): getPosition(f());
|
||||
case TDynamic(v) if(v != null): getPosition(v);
|
||||
default: Failure('type "$t" has no position');
|
||||
}
|
||||
|
||||
|
||||
|
||||
static public function toString(t:ComplexType)
|
||||
return new Printer().printComplexType(t);
|
||||
|
||||
static public function unifiesWith(from:Type, to:Type)
|
||||
return Context.unify(from, to);
|
||||
|
||||
static public function isSubTypeOf(t:Type, of:Type, ?pos)
|
||||
return
|
||||
if (Context.unify(t, of)) ECheckType(ECheckType(macro null, toComplex(t)).at(pos), toComplex(of)).at(pos).typeof();
|
||||
else Failure(new Error(t.toString() + ' should be ' + of.toString(), pos.sanitize()));
|
||||
|
||||
static public function isDynamic(t:Type)
|
||||
return switch reduce(t) {
|
||||
case TDynamic(_): true;
|
||||
default: false;
|
||||
}
|
||||
|
||||
static public function toType(t:ComplexType, ?pos:Position)
|
||||
return (macro @:pos(pos.sanitize()) {
|
||||
var v:$t = null;
|
||||
v;
|
||||
}).typeof();
|
||||
|
||||
static public inline function instantiate(t:TypePath, ?args, ?pos)
|
||||
return ENew(t, args == null ? [] : args).at(pos);
|
||||
|
||||
static public function asTypePath(s:String, ?params):TypePath {
|
||||
var parts = s.split('.');
|
||||
var name = parts.pop(),
|
||||
sub = null;
|
||||
if (parts.length > 0 && parts[parts.length - 1].charCodeAt(0) < 0x5B) {
|
||||
sub = name;
|
||||
name = parts.pop();
|
||||
if(sub == name) sub = null;
|
||||
}
|
||||
return {
|
||||
name: name,
|
||||
pack: parts,
|
||||
params: params == null ? [] : params,
|
||||
sub: sub
|
||||
};
|
||||
}
|
||||
|
||||
static public inline function asComplexType(s:String, ?params)
|
||||
return TPath(asTypePath(s, params));
|
||||
|
||||
static public function reduce(type:Type, ?once) {
|
||||
function rec(t:Type)
|
||||
return if (once) t else reduce(t, false);
|
||||
return switch type {
|
||||
case TAbstract(_.get() => { name: 'Null', pack: [] }, [t]): rec(t);
|
||||
case TLazy(f): rec(f());
|
||||
case TType(_, _): rec(Context.follow(type, once));
|
||||
default: type;
|
||||
}
|
||||
}
|
||||
|
||||
static public function isVar(field:ClassField)
|
||||
return switch (field.kind) {
|
||||
case FVar(_, _): true;
|
||||
default: false;
|
||||
}
|
||||
|
||||
static public function register(type:Void->Type):Int {
|
||||
types.set(idCounter, type);
|
||||
return idCounter++;
|
||||
}
|
||||
|
||||
static function paramsToComplex(params:Array<Type>):Array<TypeParam>
|
||||
return [for (p in params) TPType(toComplex(p))];
|
||||
|
||||
static function baseToComplex(t:BaseType, params:Array<Type>)
|
||||
return asComplexType(t.module + '.' + t.name, paramsToComplex(params));
|
||||
|
||||
static public function toComplex(type:Type, ?options:{ ?direct: Bool }):ComplexType {
|
||||
var ret =
|
||||
if (options == null || options.direct != true) tink.macro.Sisyphus.toComplexType(type);
|
||||
else null;
|
||||
if (ret == null)
|
||||
ret = lazyComplex(function () return type);
|
||||
return ret;
|
||||
}
|
||||
|
||||
static public function intersect(types:Array<ComplexType>, ?pos:Position):Outcome<ComplexType, Error> {
|
||||
|
||||
if (types.length == 1) return Success(types[1]);
|
||||
|
||||
var paths = [],
|
||||
fields = [];
|
||||
|
||||
for (t in types)
|
||||
switch t {
|
||||
case TPath(p): paths.push(p);
|
||||
case TAnonymous(f):
|
||||
|
||||
for (f in f) fields.push(f);
|
||||
|
||||
case TExtend(p, f):
|
||||
|
||||
for (f in f) fields.push(f);
|
||||
for (p in p) paths.push(p);
|
||||
|
||||
default:
|
||||
|
||||
return Failure(new Error(t.toString() + ' cannot be interesected', pos));
|
||||
}
|
||||
|
||||
return Success(TExtend(paths, fields));
|
||||
}
|
||||
|
||||
static public function lazyComplex(f:Void->Type)
|
||||
return
|
||||
TPath({
|
||||
pack : ['tink','macro'],
|
||||
name : 'DirectType',
|
||||
params : [TPExpr(register(f).toExpr())],
|
||||
sub : null,
|
||||
});
|
||||
|
||||
static function resolveDirectType()
|
||||
return
|
||||
switch reduce(Context.getLocalType()) {
|
||||
case TInst(_, [TInst(_.get() => { kind: KExpr(e) }, _)]):
|
||||
types[e.getInt().sure()]();//When using compiler server, this call throws on occasion, in which case modifying this file (to update mtime and invalidate the cache) will solve the problem
|
||||
default:
|
||||
throw 'assert';
|
||||
}
|
||||
|
||||
static public function compare(t1:Type, t2:Type, ?follow:Bool = true) {
|
||||
if (follow) {
|
||||
t1 = t1.reduce();
|
||||
t2 = t2.reduce();
|
||||
}
|
||||
|
||||
return switch t1.getIndex() - t2.getIndex() {
|
||||
case 0:
|
||||
Reflect.compare(t1.toString(), t2.toString());//much to my surprise, this actually seems to work (at least with 3.4)
|
||||
case v: v;
|
||||
}
|
||||
}
|
||||
|
||||
static var SUGGESTIONS = ~/ \(Suggestions?: .*\)$/;
|
||||
|
||||
static public function getFieldSuggestions(type:ComplexType, name:String):String
|
||||
return switch (macro (null : $type).$name).typeof() {
|
||||
case Failure(SUGGESTIONS.match(_.message) => true): SUGGESTIONS.matched(0);
|
||||
default: '';
|
||||
}
|
||||
|
||||
static public function toDecl(p:TypeParameter):TypeParamDecl
|
||||
return {
|
||||
name: p.name,
|
||||
constraints: switch p.t {
|
||||
case TInst(_.get() => { kind: KTypeParameter(c)}, _): [for(c in c) c.toComplex()];
|
||||
case _: throw 'unreachable';
|
||||
}
|
||||
}
|
||||
|
||||
static public function toTypeParam(p:TypeParameter):TypeParam
|
||||
return TPType(p.t.toComplex());
|
||||
|
||||
}
|
||||
|
@@ -1,5 +1,6 @@
|
||||
package ;
|
||||
|
||||
import haxe.macro.Context;
|
||||
import haxe.macro.Expr;
|
||||
using tink.MacroApi;
|
||||
|
||||
@@ -7,6 +8,14 @@ class Exprs extends Base {
|
||||
function exprEq(e1:Expr, e2:Expr) {
|
||||
assertEquals(e1.toString(), e2.toString());
|
||||
}
|
||||
|
||||
function testShort() {
|
||||
for (i in 0...100) {
|
||||
var id = (100 * i).shortIdent();
|
||||
Context.parseInlineString(id, (macro null).pos);
|
||||
assertTrue(id.length <= 3);
|
||||
}
|
||||
}
|
||||
function testGet() {
|
||||
assertEquals('foo', (macro foo).getIdent().sure());
|
||||
assertEquals('foo', (macro "foo").getString().sure());
|
||||
|
10
tests/Misc.hx
Normal file
10
tests/Misc.hx
Normal file
@@ -0,0 +1,10 @@
|
||||
import tink.MacroApi;
|
||||
import haxe.unit.TestCase;
|
||||
|
||||
using tink.CoreApi;
|
||||
|
||||
class Misc extends TestCase {
|
||||
function testMain() {
|
||||
assertEquals('Run', MacroApi.getMainClass().force());
|
||||
}
|
||||
}
|
@@ -12,6 +12,7 @@ class Run {
|
||||
new Types(),
|
||||
new Positions(),
|
||||
new TypeMapTest(),
|
||||
new Misc(),
|
||||
];
|
||||
#end
|
||||
macro static function test() {
|
||||
|
@@ -1,5 +1,6 @@
|
||||
package ;
|
||||
|
||||
#if macro
|
||||
import haxe.macro.Expr;
|
||||
import haxe.macro.Context;
|
||||
|
||||
@@ -20,6 +21,7 @@ class Types extends Base {
|
||||
assertFalse(o.isSuccess());
|
||||
|
||||
function testIs() {
|
||||
|
||||
assertSuccess(resolve('Int').isSubTypeOf(resolve('Float')));
|
||||
assertFailure(resolve('Float').isSubTypeOf(resolve('Int')));
|
||||
}
|
||||
@@ -41,7 +43,27 @@ class Types extends Base {
|
||||
var bool = type(macro : Bool);
|
||||
assertTrue(blank().isSubTypeOf(bool).isSuccess());
|
||||
assertTrue(bool.isSubTypeOf(blank()).isSuccess());
|
||||
|
||||
MacroApi.pos().makeBlankType().toString();
|
||||
}
|
||||
}
|
||||
|
||||
#if haxe4
|
||||
function testFinal() {
|
||||
var t = macro : {
|
||||
final foo:Int;
|
||||
};
|
||||
switch t.toType().sure() {
|
||||
case TAnonymous(_.get().fields => [f]): assertTrue(f.isFinal);
|
||||
default:
|
||||
}
|
||||
}
|
||||
#end
|
||||
|
||||
function testExpr() {
|
||||
assertEquals('VarChar<255>', (macro : VarChar<255>).toType().sure().toComplex().toString());
|
||||
}
|
||||
|
||||
function testToComplex() {
|
||||
assertEquals('String', Context.getType('String').toComplex().toString());
|
||||
assertEquals('tink.CoreApi.Noise', Context.getType('tink.CoreApi.Noise').toComplex().toString());
|
||||
}
|
||||
}
|
||||
#end
|
1
tests/VarChar.hx
Normal file
1
tests/VarChar.hx
Normal file
@@ -0,0 +1 @@
|
||||
typedef VarChar<Const> = String;
|
Reference in New Issue
Block a user