aboutsummaryrefslogtreecommitdiff
path: root/spec/inputs/macro_teal.yue
blob: 0cfd862889c99eab334b243379ea26cb551e81de (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
$ ->
	import "yue" as {:options}
	if options.tl_enabled
		options.target_extension = "tl"
	package.path ..= ";./spec/lib/?.lua"

macro to_lua = (code)->
	"require('yue').to_lua(#{code}, reserve_line_number:false, same_module:true)"

macro trim = (name)->
	"if result := #{name}\\match '[\\'\"](.*)[\\'\"]' then result else #{name}"

export macro local = (decl, value = nil)->
	import "yue" as {options:{:tl_enabled}}
	name, type = ($trim decl)\match "(.-):(.*)"
	if not (name and type)
		error "invalid local varaible declaration for \"#{decl}\""
	value = $to_lua(value)\gsub "^return ", ""
	code = if tl_enabled
		"local #{name}:#{$trim type} = #{value}"
	else
		"local #{name} = #{value}"
	{
		:code
		type: "text"
		locals: {name}
	}

export macro function = (decl, value)->
	import "yue" as {options:{:tl_enabled}}
	import "tl"
	decl = $trim decl
	name, type = decl\match "(.-)(%(.*)"
	if not (name and type)
		error "invalid function declaration for \"#{decl}\""
	tokens = tl.lex "function #{decl}"
	_, node = tl.parse_program tokens,{},"macro-function"
	args = table.concat [arg.tk for arg in *node[1].args],", "
	value = "(#{args})#{value}"
	code = if tl_enabled
		value = $to_lua(value)\match "function%([^\n]*%)(.*)end"
		"local function #{name}#{type}\n#{value}\nend"
	else
		value = $to_lua(value)\gsub "^return ", ""
		"local #{name} = #{value}"
	{
		:code
		type: "text"
		locals: {name}
	}

export macro record = (name, decl)->
	import "yue" as {options:{:tl_enabled}}
	code = if tl_enabled
		"local record #{name}
	#{decl}
end"
	else
		"local #{name} = {}"
	{
		:code
		type: "text"
		locals: {name}
	}

export macro method = (decl, value)->
	import "yue" as {options:{:tl_enabled}}
	import "tl"
	decl = $trim decl
	tab, sym, func, type = decl\match "(.-)([%.:])(.-)(%(.*)"
	if not (tab and sym and func and type)
		error "invalid method declaration for \"#{decl}\""
	tokens = tl.lex "function #{decl}"
	_, node = tl.parse_program tokens,{},"macro-function"
	args = table.concat [arg.tk for arg in *node[1].args],", "
	value = "(#{args})->#{value\match "[%-=]>(.*)"}"
	code = if tl_enabled
		value = $to_lua(value)\match "^return function%(.-%)\n(.*)end"
		"function #{tab}#{sym}#{func}#{type}\n#{value}\nend"
	else
		value = $to_lua(value)\gsub "^return ", ""
		"#{tab}.#{func} = #{value}"
	{
		:code
		type: "text"
	}