summaryrefslogtreecommitdiff
path: root/test/racc/assets/huia.y
blob: de9d45150c9d0b07852fa52605571c11faeae993 (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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# Copyright (c) 2014 James Harton
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class Huia::Parser

  token
    IDENTIFIER EQUAL PLUS MINUS ASTERISK FWD_SLASH COLON FLOAT INTEGER STRING
    EXPO INDENT OUTDENT OPAREN CPAREN DOT SIGNATURE NL EOF PIPE COMMA NIL TRUE
    FALSE EQUALITY CALL SELF CONSTANT CHAR DOUBLE_TICK_STRING
    DOUBLE_TICK_STRING_END INTERPOLATE_START INTERPOLATE_END BOX LSQUARE
    RSQUARE FACES LFACE RFACE BANG TILDE RETURN NOT_EQUALITY OR AND GT LT
    GTE LTE AT

  prechigh
    left EXPO
    left BANG TILDE
    left ASTERISK FWD_SLASH PERCENT
    left PLUS MINUS

    right EQUAL
  preclow

  rule
    statements:   statement
                | statements statement             { return scope }

    statement:  expr eol                           { return scope.append val[0] }
              | expr                               { return scope.append val[0] }
              | eol                                { return scope }

    eol:        NL | EOF
    nlq:        NL |

    expr:        literal
               | grouped_expr
               | binary_op
               | unary_op
               | method_call
               | constant
               | variable
               | array
               | hash
               | return

    return:            return_expr
                     | return_nil
    return_expr:       RETURN expr                      { return n(:Return, val[1]) }
    return_nil:        RETURN                           { return n(:Return, n(:Nil)) }

    array:             empty_array
                     | array_list

    empty_array:       BOX                              { return n :Array }

    array_list:        LSQUARE array_items RSQUARE      { return val[1] }
    array_items:       expr                             { return n :Array, [val[0]] }
                     | array_items COMMA expr           { val[0].append(val[2]); return val[0] }

    hash:              empty_hash
                     | hash_list
    empty_hash:        FACES                            { return n :Hash }
    hash_list:         LFACE hash_items RFACE           { return val[1] }
    hash_items:        hash_item                        { return n :Hash, val[0] }
                     | hash_items COMMA hash_item       { val[0].append(val[2]); return val[0] }
    hash_item:         expr COLON expr                  { return n :HashItem, val[0], val[2] }

    constant:          CONSTANT                         { return constant val[0] }

    indented:          indented_w_stmts
                     | indented_w_expr
                     | indented_wo_stmts
    indented_w_stmts:  indent statements outdent        { return val[0] }
    indented_w_expr:   indent expr outdent              { return val[0].append(val[1]) }
    indented_wo_stmts: indent outdent                   { return val[0] }
    outdent:           OUTDENT { return pop_scope }


    indent_w_args:     indent_pipe indent_args PIPE nlq INDENT { return val[0] }
    indent_pipe:       PIPE   { return push_scope }
    indent_wo_args:    INDENT { return push_scope }
    indent:            indent_w_args
                     | indent_wo_args

    indent_args:       indent_arg
                     | indent_args COMMA indent_arg
    indent_arg:        arg_var                             { return scope.add_argument val[0] }
                     | arg_var EQUAL expr                  { return n :Assignment, val[0], val[2] }
    arg_var:           IDENTIFIER                          { return n :Variable, val[0] }

    method_call:            method_call_on_object
                          | method_call_on_self
                          | method_call_on_closure
    method_call_on_object:  expr DOT call_signature        { return n :MethodCall, val[0], val[2] }
                          | expr DOT IDENTIFIER            { return n :MethodCall, val[0], n(:CallSignature, val[2]) }
    method_call_on_self:    call_signature                 { return n :MethodCall, scope_instance, val[0] }

    method_call_on_closure: AT call_signature              { return n :MethodCall, this_closure, val[1] }
                          | AT IDENTIFIER                  { return n :MethodCall, this_closure, n(:CallSignature, val[1]) }

    call_signature:         call_arguments
                          | call_simple_name
    call_simple_name:       CALL                           { return n :CallSignature, val[0] }
    call_argument:          SIGNATURE call_passed_arg      { return n :CallSignature, val[0], [val[1]] }
    call_passed_arg:        call_passed_simple
                          | call_passed_indented
    call_passed_simple:     expr
                          | expr NL
    call_passed_indented:   indented
                          | indented NL
    call_arguments:         call_argument                  { return val[0] }
                          | call_arguments call_argument   { return val[0].concat_signature val[1] }

    grouped_expr: OPAREN expr CPAREN            { return n :Expression, val[1] }

    variable:  IDENTIFIER                       { return allocate_local val[0] }

    binary_op: assignment
             | addition
             | subtraction
             | multiplication
             | division
             | exponentiation
             | modulo
             | equality
             | not_equality
             | logical_or
             | logical_and
             | greater_than
             | less_than
             | greater_or_eq
             | less_or_eq

    assignment:     IDENTIFIER EQUAL expr  { return allocate_local_assignment val[0], val[2] }
    addition:       expr PLUS expr         { return binary val[0], val[2], 'plus:' }
    subtraction:    expr MINUS expr        { return binary val[0], val[2], 'minus:' }
    multiplication: expr ASTERISK expr     { return binary val[0], val[2], 'multiplyBy:' }
    division:       expr FWD_SLASH expr    { return binary val[0], val[2], 'divideBy:' }
    exponentiation: expr EXPO expr         { return binary val[0], val[2], 'toThePowerOf:' }
    modulo:         expr PERCENT expr      { return binary val[0], val[2], 'moduloOf:' }
    equality:       expr EQUALITY expr     { return binary val[0], val[2], 'isEqualTo:' }
    not_equality:   expr NOT_EQUALITY expr { return binary val[0], val[2], 'isNotEqualTo:' }
    logical_or:     expr OR expr           { return binary val[0], val[2], 'logicalOr:' }
    logical_and:    expr AND expr          { return binary val[0], val[2], 'logicalAnd:' }
    greater_than:   expr GT expr           { return binary val[0], val[2], 'isGreaterThan:' }
    less_than:      expr LT expr           { return binary val[0], val[2], 'isLessThan:' }
    greater_or_eq:  expr GTE expr          { return binary val[0], val[2], 'isGreaterOrEqualTo:' }
    less_or_eq:     expr LTE expr          { return binary val[0], val[2], 'isLessOrEqualTo:' }

    unary_op:  unary_not
             | unary_plus
             | unary_minus
             | unary_complement

    unary_not:        BANG  expr { return unary val[1], 'unaryNot' }
    unary_plus:       PLUS  expr { return unary val[1], 'unaryPlus' }
    unary_minus:      MINUS expr { return unary val[1], 'unaryMinus' }
    unary_complement: TILDE expr { return unary val[1], 'unaryComplement' }

    literal:   integer
             | float
             | string
             | nil
             | true
             | false
             | self

    float:          FLOAT                       { return n :Float,   val[0] }
    integer:        INTEGER                     { return n :Integer, val[0] }
    nil:            NIL                         { return n :Nil }
    true:           TRUE                        { return n :True }
    false:          FALSE                       { return n :False }
    self:           SELF                        { return n :Self }

    string:         STRING                      { return n :String,  val[0] }
                  | interpolated_string
                  | empty_string

    interpolated_string: DOUBLE_TICK_STRING interpolated_string_contents DOUBLE_TICK_STRING_END { return val[1] }
    interpolation:       INTERPOLATE_START expr INTERPOLATE_END { return val[1] }
    interpolated_string_contents:   interpolated_string_chunk   { return n :InterpolatedString, val[0] }
                                  | interpolated_string_contents interpolated_string_chunk { val[0].append(val[1]); return val[0] }
    interpolated_string_chunk:   chars         { return val[0] }
                               | interpolation { return to_string(val[0]) }
    empty_string: DOUBLE_TICK_STRING DOUBLE_TICK_STRING_END { return n :String, '' }

    chars:   CHAR       { return n :String, val[0] }
           | chars CHAR { val[0].append(val[1]); return val[0] }
end

---- inner

attr_accessor :lexer, :scopes, :state

def initialize lexer
  @lexer  = lexer
  @state  = []
  @scopes = []
  push_scope
end

def ast
  @ast ||= do_parse
  @scopes.first
end

def on_error t, val, vstack
  line = lexer.line
  col  = lexer.column
  message = "Unexpected #{token_to_str t} at #{lexer.filename} line #{line}:#{col}:\n\n"

  start = line - 5 > 0 ? line - 5 : 0
  i_size = line.to_s.size
  (start..(start + 5)).each do |i|
    message << sprintf("\t%#{i_size}d: %s\n", i, lexer.get_line(i))
    message << "\t#{' ' * i_size}  #{'-' * (col - 1)}^\n" if i == line
  end

  raise SyntaxError, message
end

def next_token
  nt = lexer.next_computed_token
  # just use a state stack for now, we'll have to do something
  # more sophisticated soon.
  if nt && nt.first == :state
    if nt.last
      state.push << nt.last
    else
      state.pop
    end
    next_token
  else
    nt
  end
end

def push_scope
  new_scope = Huia::AST::Scope.new scope
  new_scope.file   = lexer.filename
  new_scope.line   = lexer.line
  new_scope.column = lexer.column
  scopes.push new_scope
  new_scope
end

def pop_scope
  scopes.pop
end

def scope
  scopes.last
end

def binary left, right, method
  node(:MethodCall, left, node(:CallSignature, method, [right]))
end

def unary left, method
  node(:MethodCall, left, node(:CallSignature, method))
end

def node type, *args
  Huia::AST.const_get(type).new(*args).tap do |n|
    n.file   = lexer.filename
    n.line   = lexer.line
    n.column = lexer.column
  end
end
alias n node

def allocate_local name
  node(:Variable, name).tap do |n|
    scope.allocate_local n
  end
end

def allocate_local_assignment name, value
  node(:Assignment, name, value).tap do |n|
    scope.allocate_local n
  end
end

def this_closure
  allocate_local('@')
end

def scope_instance
  node(:ScopeInstance, scope)
end

def constant name
  return scope_instance if name == 'self'
  node(:Constant, name)
end

def to_string expr
  node(:MethodCall, expr, node(:CallSignature, 'toString'))
end