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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
require_relative "error"
require_relative "expr"
require_relative "stmt"

module Lox
  class Parser

    def initialize(tokens)
      @tokens = tokens
      @current = 0
    end

    def parse!
      statements = []
      until eot?
        statements << declaration
      end
      statements
    rescue ParseError => e
      $stderr.puts e.message
      synchronize!
    end

    private

    def declaration
      return class_decl if match?(:CLASS)
      return function("function") if match?(:FUN)
      return var_declaration if match?(:VAR)

      statement
    end

    def class_decl
      name = consume!(:IDENTIFIER, "Expect class name.")

      superclass = if match?(:LESS)
                     consume!(:IDENTIFIER, "Expect superclass name.")
                     Expr::Variable.new(prev)
                   else
                     nil
                   end

      consume!(:LEFT_BRACE, "Expect '{' before class body.")

      methods = []
      until check?(:RIGHT_BRACE) || eot?
        methods << function("method")
      end

      consume!(:RIGHT_BRACE, "Expect '}' after class body.")

      Stmt::Class.new(name, superclass, methods)
    end

    def var_declaration
      name = consume!(:IDENTIFIER, "Expect variable name.")
      initializer = match?(:EQUAL) ? expression : nil
      consume!(:SEMICOLON, "Expect ';' after variable declaration.")

      Stmt::Var.new(name, initializer)
    end

    def while_stmt
      consume!(:LEFT_PAREN, "Expect '(' after 'if'.")
      cond = expression
      consume!(:RIGHT_PAREN, "Expect ')' after 'if'.")
      body = statement

      Stmt::While.new(cond, body)
    end

    def statement
      return for_stmt if match?(:FOR)
      return if_stmt if match?(:IF)
      return print if match?(:PRINT)
      return return_stmt if match?(:RETURN)
      return while_stmt if match?(:WHILE)
      return Stmt::Block.new(block) if match?(:LEFT_BRACE)

      expression_stmt
    end

    def for_stmt
      consume!(:LEFT_PAREN, "Expect '(' after 'if'.")

      initializer = if match?(:SEMICOLON)
                      nil
                    elsif match?(:VAR)
                      var_declaration
                    else
                      expression_stmt
                    end

      condition = check?(:SEMICOLON) ? Expr::Literal.new(true) : expression
      consume!(:SEMICOLON, "Expect ';' after loop condition.")

      increment = check?(:RIGHT_PAREN) ? nil : expression
      consume!(:RIGHT_PAREN, "Expect ')' after for clauses.")

      body = statement

      if increment
        body = Stmt::Block.new([
          body,
          Stmt::Expr.new(increment),
        ])
      end

      body = Stmt::While.new(condition, body);

      if initializer
        body = Stmt::Block.new([
          initializer,
          body,
        ])
      end

      body
    end

    def if_stmt
      consume!(:LEFT_PAREN, "Expect '(' after 'if'.")
      cond = expression
      consume!(:RIGHT_PAREN, "Expect ')' after 'if'.")

      then_stmt = statement
      else_stmt = match?(:ELSE) ? statement : nil

      Stmt::If.new(cond, then_stmt, else_stmt)
    end

    def print
      value = expression
      consume!(:SEMICOLON, "Expect ';' after value.")
      Stmt::Print.new(value)
    end

    def return_stmt
      keyword = prev
      value = check?(:SEMICOLON) ? nil : expression
      consume!(:SEMICOLON, "Expect ';' after return value.")
      Stmt::Return.new(keyword, value)
    end

    def expression_stmt
      value = expression
      consume!(:SEMICOLON, "Expect ';' after value.")
      Stmt::Expr.new(value)
    end

    def function(kind)
      name = consume!(:IDENTIFIER, "Expect #{kind} name.")
      consume!(:LEFT_PAREN, "Expect '(' after #{kind} name.")
      params = []
      unless check?(:RIGHT_PAREN)
        loop do
          raise ParseError.new(peek, "Can't have more than 255 parameters.") if params.size >= 255

          params << consume!(:IDENTIFIER, "Expect parameter name.")
          break unless match?(:COMMA)
        end
      end
      consume!(:RIGHT_PAREN, "Expect ')' after parameters.")

      consume!(:LEFT_BRACE, "Expect '{' before #{kind} body.")
      body = block

      Stmt::Function.new(name, params, body)
    end

    def block
      statements = []
      until check?(:RIGHT_BRACE) || eot?
        statements << declaration
      end
      consume!(:RIGHT_BRACE, "Expect '}' after block.")
      statements
    end

    def assignment
      expr = or_

      return expr unless match?(:EQUAL)

      eq = prev
      value = assignment

      case expr
      when Expr::Variable
        Expr::Assign.new(expr.name, value)
      when Expr::Get
        Expr::Set.new(expr.object, expr.name, value)
      else
        raise ParseError.new(eq, "Invalid assignment target.")
      end
    end

    def or_
      expr = and_

      while match?(:OR)
        op = prev
        right = and_
        expr = Expr::Logical.new(expr, op, right)
      end

      expr
    end

    def and_
      expr = equality

      while match?(:AND)
        op = prev
        right = equality
        expr = Expr::Logical.new(expr, op, right)
      end

      expr
    end

    def expression = assignment

    def equality
      expr = comparison

      while match?(:BANG_EQUAL, :EQUAL_EQUAL)
        op = prev
        right = comparison
        expr = Expr::Binary.new(expr, op, right)
      end

      expr
    end

    def comparison
      expr = term

      while match?(:GREATER, :GREATER_EQUAL, :LESS, :LESS_EQUAL)
        op = prev
        right = term
        expr = Expr::Binary.new(expr, op, right)
      end

      expr
    end

    def term
      expr = factor

      while match?(:MINUS, :PLUS)
        op = prev
        right = factor
        expr = Expr::Binary.new(expr, op, right)
      end

      expr
    end

    def factor
      expr = unary

      while match?(:SLASH, :STAR)
        op = prev
        right = unary
        expr = Expr::Binary.new(expr, op, right)
      end

      expr
    end

    def unary
      return call unless match?(:BANG, :MINUS)

      op = prev
      right = unary
      Expr::Unary.new(op, right)
    end

    def call
      expr = primary

      loop do
        if match?(:LEFT_PAREN)
          expr = finish_call(expr)
        elsif match?(:DOT)
          name = consume!(:IDENTIFIER, "Expect property name after '.'.")
          expr = Expr::Get.new(expr, name)
        else
          break
        end
      end

      expr
    end

    def finish_call(callee)
      args = []
      if !check?(:RIGHT_PAREN)
        loop do
          raise ParseError.new(peek,  "Can't have more than 255 arguments.") if args.size >= 255

          args << expression
          break unless match?(:COMMA)
        end
      end

      paren = consume!(:RIGHT_PAREN, "Expect ')' after arguments.")

      Expr::Call.new(callee, paren, args)
    end

    def primary
      return Expr::Literal.new(false) if match?(:FALSE)
      return Expr::Literal.new(true) if match?(:TRUE)
      return Expr::Literal.new(nil) if match?(:NIL)
      return Expr::Literal.new(prev.literal) if match?(:NUMBER, :STRING)

      if match?(:SUPER)
        keyword = prev
        consume!(:DOT, "Expect '.' after 'super'.")
        method = consume!(:IDENTIFIER, "Expect superclass method name.")
        return Expr::Super.new(keyword, method)
      end

      return Expr::This.new(prev) if match?(:THIS)
      return Expr::Variable.new(prev) if match?(:IDENTIFIER)

      if match?(:LEFT_PAREN)
        expr = expression
        consume!(:RIGHT_PAREN, "Expect ')' after expression.")
        return Expr::Grouping.new(expr)
      end

      raise ParseError.new(peek, "Expect expression.")
    end

    private

    def match?(*types)
      return false unless check?(*types)

      advance!
      return true
    end

    def consume!(type, message)
      raise ParseError.new(peek, message) unless check?(type)

      advance!
    end

    def check?(*types)
      return false if eot?

      types.include?(peek.type)
    end

    def advance!
      @current += 1 unless eot?
      prev
    end

    def eot? = peek.type === :EOF
    def peek = @tokens.fetch(@current)
    def prev = @tokens.fetch(@current - 1)

    def synchronize!
      advance!

      until eot?
        return if prev.type == :SEMICOLON
        return if %i[CLASS FUN VAR FOR IF WHILE PRINT RETURN].include?(peek.type)

        advance!
      end
    end

  end
end