summaryrefslogtreecommitdiff
path: root/internal/generated/nqc.raku
blob: 82d2a340be93ca06b3b5dcb31f6de433841d8b16 (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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
#!/usr/bin/env raku
#
# This Raku program takes a list of C struct and constant definitions and converts
# it to valid Go code.

use v6.d;
#use Grammar::Debugger;

# Not quite C
grammar NQC {
    rule TOP { <construct>* }
    rule construct { <constant> | <statement> | <comment> }
    rule constant { '#define' <identifier> <number> }
    rule statement { <struct> ';' }
    rule struct { 'struct' <identifier> '{' <member>+ %% ';' '}' }
    rule member { <type> <identifier> <arraysize>? }
    rule comment { <single-line-comment> | <multi-line-comment> }
    rule single-line-comment { '//' <-[\n]>+ }
    rule multi-line-comment { '/*' .*? '*/' }
    token arraysize { '[' <identifier> ']' }
    token type { 'char' | '__s32' | '__u32' | '__s64' | '__u64' }
    token identifier { <[a..z A..Z 0..9 _]>+ }
    token number { \d+ }
}

class NQCToGoActions {
    has Str @!const-names;
    has Bool $!constant-type-set;

    method TOP($/) {
        make "// This file was generated - don't change manually!\n"
        ~ "package types\n\n"
        ~ self!constant-go-methods ~ "\n"
        ~ $<construct>.map(*.made).join('');
    }

    method construct($/) {
        make $<constant>.made // $<statement>.made // '';
    }

    method statement($/) {
        make "\n" ~ $<struct>.made;
    }

    method constant($/) {
        push @!const-names: ~$<identifier>;
        my $const-type = $<identifier>.starts-with('SYS_') ?? ' SyscallId ' !! '';

        make qq:to/END/;
        const {$<identifier>}$const-type = {$<number>}
        END
    }

    method !constant-go-methods returns Str {
        qq:to/END/;
        type EventType uint32
        type SyscallId uint32

        func (s SyscallId) String() string \{
            switch (s) \{
            {@!const-names.grep(/^SYS_/).map({
                "case $_: return \"{$_.subst('SYS_', '').lc}\""
            }).join('; ')}
            default: panic(fmt.Sprintf("Unknown SyscallId: %d", s))
            \}
        \}

        func (s SyscallId) Name() string \{
            switch (s) \{
            {@!const-names.grep(/^SYS_/).map({
                "case $_: return \"{$_.subst(/'SYS_ENTER_'|'SYS_EXIT_'/, '').lc}\""
            }).join('; ')}
            default: panic(fmt.Sprintf("Unknown SyscallId: %d", s))
            \}
        \}
        END
    }

    method struct($/) {
        make qq:to/END/;
        type {$<identifier>.made} struct \{
            {$<member>.map(*.made).join('; ')} 
        \}
        
        {self!struct-go-methods($/)}
        {($<identifier>.made.ends-with('Event') ?? "\n" ~ self!struct-go-sync-pool($/) !! '')}
        END
    }

    # Generate String() and other methods on the Go struct, for pretty printing.
    method !struct-go-methods($/) returns Str {
        my Str $self-ref = $<identifier>.lc.substr(0,1);
        my Str @format = $<member>.map({ $_.<identifier>.made ~ ':%v' });

        my Str @args = $<member>.map({
            my Str $ref = "$self-ref." ~ $_.<identifier>.made;
            # Need to convert char-arrays into a Go slice, and then convert via string(...) 
            ($_.<type> eq 'char' && $_.<arraysize>) ?? "string({$ref}[:])" !! $ref;
        });

        qq:to/END/;
        func ($self-ref {$<identifier>.made}) String() string \{
            return fmt.Sprintf("{@format.join(' ')}", {@args.join(', ')})
        \}

        func ($self-ref *{$<identifier>.made}) GetEventType() EventType \{
            return $self-ref.EventType
        \}

        func ($self-ref *{$<identifier>.made}) GetSyscallId() SyscallId \{
            return $self-ref.SyscallId
        \}

        func ($self-ref *{$<identifier>.made}) GetPid() uint32 \{
            return $self-ref.Pid
        \}

        func ($self-ref *{$<identifier>.made}) GetTid() uint32 \{
            return $self-ref.Tid
        \}

        func ($self-ref *{$<identifier>.made}) GetTime() uint32 \{
            return $self-ref.Time
        \}
        END
    }

    method !struct-go-sync-pool($/) returns Str {
        my Str $identifier = $/<identifier>.made;
        my Str $self-ref = $identifier.lc.substr(0,1);

        qq:to/END/;
        var poolOf{$identifier}s = sync.Pool\{
            New: func() interface\{\} \{ return &$identifier\{\} \},
        \}

        func New{$identifier}(raw []byte) *$identifier \{
            $self-ref := poolOf{$identifier}s.Get().(*$identifier);
            if err := binary.Read(bytes.NewReader(raw), binary.LittleEndian, $self-ref); err != nil \{
                fmt.Println($self-ref, raw, len(raw), err)
                panic(raw)
            \}
            return $self-ref
        \}

        func ($self-ref *$identifier) Recycle() \{
            poolOf{$identifier}s.Put($self-ref)
        \}
        END
    }

    method member($/) {
        my Str $type = $<identifier>.made eq 'SyscallId' ?? 'SyscallId' !! $<type>.made;
        $type = 'EventType' if $<identifier>.made eq 'EventType';
        make $<identifier>.made ~ ' ' ~ ($<arraysize> // '') ~ $type;
    }

    method type($/) {
        make do given ~$/ {
            when 'char' { 'byte' }
            when '__s32' { 'int32' }
            when '__u32' { 'uint32' }
            when '__s64' { 'int64' }
            when '__u64' { 'uint64' }
        }
    }

    method identifier($/) {
        # Convert identifier from snake_case (C) to CamelCase (Go)
        make $/.Str.split('_').map(*.tc).join('');
    }
}

say NQC.parse($*IN.slurp, actions => NQCToGoActions.new).made;