Class: Lox::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/loxby/parser.rb

Overview

‘Lox::Parser` converts a list of tokens from `Lox::Scanner` to a syntax tree. This tree can be interacted with using the Visitor pattern. (See `Visitor` in lib/visitors/base.rb.)

Instance Method Summary collapse

Constructor Details

#initialize(tokens, interpreter) ⇒ Parser

Returns a new instance of Parser.



13
14
15
16
17
18
# File 'lib/loxby/parser.rb', line 13

def initialize(tokens, interpreter)
  @tokens = tokens
  @interpreter = interpreter
  # Variables for parsing
  @current = 0
end

Instance Method Details

#assignmentObject

rubocop:disable Metrics/MethodLength



238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/loxby/parser.rb', line 238

def assignment # rubocop:disable Metrics/MethodLength
  expr = logical_or

  if matches? :equal
    equals = previous
    value = assignment

    if expr.is_a? Lox::AST::Expression::Variable
      name = expr.name
      return Lox::AST::Expression::Assign.new(name:, value:)
    end

    error equals, 'Invalid assignment target.'
  end

  expr
end

#blockObject



101
102
103
104
105
106
# File 'lib/loxby/parser.rb', line 101

def block
  statements = []
  statements << break_or_declaration until check(:right_brace) || end_of_input?
  consume :right_brace, "Expect '}' after block."
  statements
end

#break_or_declarationObject



93
94
95
96
97
98
99
# File 'lib/loxby/parser.rb', line 93

def break_or_declaration
  if matches? :break
    break_statement
  else
    declaration
  end
end

#break_statementObject



195
196
197
198
# File 'lib/loxby/parser.rb', line 195

def break_statement
  consume :semicolon, "Expect ';' after break."
  Lox::AST::Statement::Break.new
end

#comparisonObject



291
292
293
294
295
296
297
298
299
300
301
# File 'lib/loxby/parser.rb', line 291

def comparison
  expr = term

  while matches?(:greater, :greater_equal, :less, :less_equal)
    operator = previous
    right = term
    expr = Lox::AST::Expression::Binary.new(left: expr, operator:, right:)
  end

  expr
end

#conditionalObject

Ternary operator



219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/loxby/parser.rb', line 219

def conditional
  expr = expression

  if matches? :question
    left_operator = previous
    center = check(:colon) ? Lox::AST::Expression::Literal.new(value: nil) : expression_list
    consume :colon, "Expect ':' after expression: incomplete ternary operator."
    right_operator = previous
    right = conditional # Recurse, right-associative
    expr = Lox::AST::Expression::Ternary.new(left: expr, left_operator:, center:, right_operator:, right:)
  end

  expr
end

#declarationObject



26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/loxby/parser.rb', line 26

def declaration
  if matches? :fun
    function 'function'
  elsif matches? :var
    var_declaration
  else
    statement
  end
rescue Lox::ParseError
  synchronize
  nil
end

#equalityObject



280
281
282
283
284
285
286
287
288
289
# File 'lib/loxby/parser.rb', line 280

def equality
  expr = comparison
  while matches?(:bang_equal, :equal_equal)
    operator = previous
    right = comparison
    # Compose (equality is left-associative)
    expr = Lox::AST::Expression::Binary.new(left: expr, operator:, right:)
  end
  expr
end

#expressionObject



234
235
236
# File 'lib/loxby/parser.rb', line 234

def expression
  assignment
end

#expression_listObject



206
207
208
209
210
211
212
213
214
215
216
# File 'lib/loxby/parser.rb', line 206

def expression_list
  expr = conditional

  while matches? :comma
    operator = previous
    right = conditional
    expr = Lox::AST::Expression::Binary.new(left: expr, operator:, right:)
  end

  expr
end

#expression_statementObject



200
201
202
203
204
# File 'lib/loxby/parser.rb', line 200

def expression_statement
  expr = expression_list
  consume :semicolon, "Expect ';' after expression."
  Lox::AST::Statement::Expression.new(expression: expr)
end

#factorObject



315
316
317
318
319
320
321
322
323
324
325
# File 'lib/loxby/parser.rb', line 315

def factor
  expr = unary

  while matches?(:slash, :star)
    operator = previous
    right = unary
    expr = Lox::AST::Expression::Binary.new(left: expr, operator:, right:)
  end

  expr
end

#finish_call(callee) ⇒ Object



350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/loxby/parser.rb', line 350

def finish_call(callee)
  arguments = []
  unless check :right_paren
    loop do
      error(peek, "Can't have more than 255 arguments.") if arguments.size > 255
      arguments << expression
      break unless matches? :comma
    end
  end
  paren = consume :right_paren, "Expect ')' after arguments."
  Lox::AST::Expression::Call.new(callee:, paren:, arguments:)
end

#for_statementObject

‘for` loops in loxby are syntactic sugar for `while` loops. Yay!



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
# File 'lib/loxby/parser.rb', line 149

def for_statement # rubocop:disable Metrics/MethodLength,Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity
  consume :left_paren, "Expect '(' after 'for'."

  initializer =
    if matches? :semicolon
      nil
    elsif matches? :var
      var_declaration
    else
      expression_statement
    end

  condition = nil
  condition = expression unless check :semicolon
  consume :semicolon, "Expect ';' after loop condition."

  increment = nil
  increment = expression unless check :right_paren
  consume :right_paren, "Expect ')' after for clauses."

  body = statement

  unless increment.nil?
    body = Lox::AST::Statement::Block.new(
      statements: [
        body,
        Lox::AST::Statement::Expression.new(expression: increment)
      ]
    )
  end

  condition = Lox::AST::Expression::Literal.new(value: true) if condition.nil?
  body = Lox::AST::Statement::While.new(condition:, body:)

  unless initializer.nil?
    body = Lox::AST::Statement::Block.new(
      statements: [
        initializer,
        body
      ]
    )
  end

  body
end

#function(kind) ⇒ Object

rubocop:disable Metrics/MethodLength



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
# File 'lib/loxby/parser.rb', line 39

def function(kind) # rubocop:disable Metrics/MethodLength
  name = nil
  if check :identifier
    # Named function
    name = consume :identifier, "Expect #{kind} name."
  end
  consume :left_paren, "Expect '(' after #{kind} name."
  parameters = []
  loop do
    break if check :right_paren

    # This is mostly arbitrary but it keeps execution time down
    error(peek, "Can't have more than 255 parameters.") if parameters.size > 255

    parameters << consume(:identifier, 'Expect parameter name.')
    break unless matches? :comma
  end
  consume :right_paren, "Expect ')' after parameters."

  # Have to consume the first part of the block since
  # it assumes it's already been matched
  consume :left_brace, 'Expect block after parameter list.'
  body = block

  Lox::AST::Statement::Function.new(name:, params: parameters, body:)
end

#function_callObject



340
341
342
343
344
345
346
347
348
# File 'lib/loxby/parser.rb', line 340

def function_call
  expr = primary
  loop do
    break unless matches? :left_paren

    expr = finish_call expr
  end
  expr
end

#if_statementObject



123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/loxby/parser.rb', line 123

def if_statement
  consume :left_paren, "Expect '(' after 'if'."
  condition = expression_list
  consume :right_paren, "Expect ')' after if condition."

  # We don't go up to var declaration because variables
  # declared inside an if statement should be inside a
  # *block* inside the if statement.
  then_branch = statement
  else_branch = matches?(:else) ? statement : nil

  Lox::AST::Statement::If.new(condition:, then_branch:, else_branch:)
end

#logical_andObject



268
269
270
271
272
273
274
275
276
277
278
# File 'lib/loxby/parser.rb', line 268

def logical_and
  expr = equality

  while matches? :and
    operator = previous
    right = logical_and
    expr = Lox::AST::Expression::Logical.new(left: expr, operator:, right:)
  end

  expr
end

#logical_orObject



256
257
258
259
260
261
262
263
264
265
266
# File 'lib/loxby/parser.rb', line 256

def logical_or
  expr = logical_and

  while matches? :or
    operator = previous
    right = logical_and
    expr = Lox::AST::Expression::Logical.new(left: expr, operator:, right:)
  end

  expr
end

#parseObject



20
21
22
23
24
# File 'lib/loxby/parser.rb', line 20

def parse
  statements = []
  statements << declaration until end_of_input?
  statements
end

#primaryObject

rubocop:disable Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/MethodLength,Metrics/PerceivedComplexity



363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
# File 'lib/loxby/parser.rb', line 363

def primary # rubocop:disable Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/MethodLength,Metrics/PerceivedComplexity
  if matches? :false
    Lox::AST::Expression::Literal.new(value: false)
  elsif matches? :true
    Lox::AST::Expression::Literal.new(value: true)
  elsif matches? :nil
    Lox::AST::Expression::Literal.new(value: nil)
  elsif matches? :fun
    function 'inline function'
  elsif matches? :number, :string
    Lox::AST::Expression::Literal.new(value: previous.literal)
  elsif matches? :break
    raise error(previous, "Invalid 'break' not in loop.")
  elsif matches? :identifier
    Lox::AST::Expression::Variable.new(name: previous)
  elsif matches? :left_paren
    expr = expression_list
    consume :right_paren, "Expect ')' after expression."
    Lox::AST::Expression::Grouping.new(expression: expr)
  # Error productions--binary operator without left operand
  elsif matches? :comma
    err = error(previous, "Expect expression before ',' operator.")
    conditional # Parse and throw away
    raise err
  elsif matches? :question
    err = error(previous, 'Expect expression before ternary operator.')
    # Parse and throw away
    expression_list
    consume :colon, "Expect ':' after '?' (ternary operator)."
    conditional
    raise err
  elsif matches? :bang_equal, :equal_equal
    err = error(previous, "Expect value before '#{previous.lexeme}'.")
    comparison
    raise err
  elsif matches? :greater, :greater_equal, :less, :less_equal
    err = error(previous, "Expect value before '#{previous.lexeme}'.")
    term
    raise err
  elsif matches? :plus
    err = error(previous, "Expect value before '+'.")
    factor
    raise err
  elsif matches? :slash, :star
    err = error(previous, "Expect value before '#{previous.lexeme}'.")
    unary
    raise err
  # Base case--no match.
  else
    raise error(peek, 'Expect expression.')
  end
end


108
109
110
111
112
# File 'lib/loxby/parser.rb', line 108

def print_statement
  value = expression_list
  consume :semicolon, "Expect ';' after value."
  Lox::AST::Statement::Print.new(expression: value)
end

#return_statementObject



114
115
116
117
118
119
120
121
# File 'lib/loxby/parser.rb', line 114

def return_statement
  keyword = previous
  value = nil
  value = expression unless check :semicolon

  consume :semicolon, "Expect ';' after return value."
  Lox::AST::Statement::Return.new(keyword:, value:)
end

#statementObject

rubocop:disable Metrics/MethodLength,Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/loxby/parser.rb', line 73

def statement # rubocop:disable Metrics/MethodLength,Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity
  if matches? :for
    for_statement
  elsif matches? :if
    if_statement
  elsif matches? :print
    print_statement
  elsif matches? :return
    return_statement
  elsif matches? :while
    while_statement
  elsif matches? :fun
    function 'function'
  elsif matches? :left_brace
    Lox::AST::Statement::Block.new(statements: block)
  else
    expression_statement
  end
end

#termObject



303
304
305
306
307
308
309
310
311
312
313
# File 'lib/loxby/parser.rb', line 303

def term
  expr = factor

  while matches?(:minus, :plus)
    operator = previous
    right = factor
    expr = Lox::AST::Expression::Binary.new(left: expr, operator:, right:)
  end

  expr
end

#unaryObject



327
328
329
330
331
332
333
334
335
336
337
338
# File 'lib/loxby/parser.rb', line 327

def unary
  # Unary operators are right-associative, so we match
  # first, then recurse.
  if matches?(:bang, :minus)
    operator = previous
    right = unary

    Lox::AST::Expression::Unary.new(operator:, right:)
  else
    function_call
  end
end

#var_declarationObject



66
67
68
69
70
71
# File 'lib/loxby/parser.rb', line 66

def var_declaration
  name = consume :identifier, 'Expect variable name.'
  initializer = matches?(:equal) ? expression : nil
  consume :semicolon, "Expect ';' after variable declaration."
  Lox::AST::Statement::Var.new(name:, initializer:)
end

#while_statementObject



137
138
139
140
141
142
143
144
# File 'lib/loxby/parser.rb', line 137

def while_statement
  consume :left_paren, "Expect '(' after 'while'."
  condition = expression_list
  consume :right_paren, "Expect ')' after condition."
  body = statement

  Lox::AST::Statement::While.new(condition:, body:)
end