1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- module Chervil
- class Parser def initialize(lexer)
- @lexer = lexer
- @tree = Array.new
- @current_token = @lexer.get_next_token
- end
-
- def parse
- until @current_token.type == :eof
- @tree << expr
- end
- @tree
- end
-
- def expr
- if [:string, :number].include?(@current_token.type)
- constant
- elsif @current_token.type == :identifier
- identifier
- elsif @current_token.type == :lparen
- application
- end
- end
-
- def application
- eat(:lparen)
-
- if @current_token.type == :identifier && @current_token.value == 'define'
- eat(:identifier)
- name = identifier
- value = expr
- eat(:rparen)
- return AST::Definition.new(name, value)
- end
-
- expression = expr
-
- args = Array.new
- until @current_token.type == :rparen
- args << expr
- end
-
- eat(:rparen)
-
- AST::Application.new(expression, args)
- end
-
- def identifier
- identifier = eat(:identifier)
- AST::Identifier.new(identifier.value)
- end
-
- def constant
- case @current_token.type
- when :number
- token = eat(:number)
- AST::Number.new(token.value.to_f)
- when :string
- token = eat(:string)
- AST::String.new(token.value)
- end
- end
-
- def eat(type)
- if @current_token.type == type
- token = @current_token
- @current_token = @lexer.get_next_token
- token
- else
- raise "Expected #{type} but got #{@current_token.type}"
- end
- end
- end
- end
|