Class: Astrapi::Parser

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

Constant Summary

Constants included from Indent

Indent::INDENT

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Indent

#dedent, #indent, #say

Constructor Details

#initializeParser

Returns a new instance of Parser.



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

def initialize
  @verbose=true
  @lexer=Lexer.new
end

Instance Attribute Details

#lexerObject

Returns the value of attribute lexer.



11
12
13
# File 'lib/parser.rb', line 11

def lexer
  @lexer
end

#tokensObject

Returns the value of attribute tokens.



11
12
13
# File 'lib/parser.rb', line 11

def tokens
  @tokens
end

Instance Method Details

#acceptItObject



26
27
28
29
30
# File 'lib/parser.rb', line 26

def acceptIt
  tok=tokens.shift
  say "consuming #{tok.val} (#{tok.kind})"
  tok
end

#expect(kind) ⇒ Object



36
37
38
39
40
41
42
# File 'lib/parser.rb', line 36

def expect kind
  if (actual=showNext.kind)!=kind
    abort "ERROR at #{showNext.pos}. Expecting #{kind}. Got #{actual}"
  else
    return acceptIt()
  end
end

#parse(filename) ⇒ Object



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

def parse filename
  str=IO.read(filename)
  @tokens=lexer.tokenize(str)
  @tokens=@tokens.select{|tok| tok.kind!=:comment}
  pp @tokens if @verbose
  parseModule
end

#parseAttrObject



74
75
76
77
78
79
80
81
82
# File 'lib/parser.rb', line 74

def parseAttr
  indent "parseAttr"
  expect :attr
  name=Identifier.new(expect :identifier)
  expect :arrow
  type=parseAttrType
  dedent
  Attr.new(name,type)
end

#parseAttrTypeObject



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/parser.rb', line 84

def parseAttrType
  indent "parseAttrType"
  if showNext.is_a? [:IDENT,:FLOAT,:INT,:STRING]
    type=Type.new(Identifier.new(acceptIt))
  else
    type=Type.new(Identifier.new(expect :identifier))
  end
  if showNext.is_a? :lbrack
    acceptIt
    expect :rbrack
    type=ArrayOf.new(type)
  end
  dedent
  return type
end

#parseClassObject



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/parser.rb', line 57

def parseClass
  indent "parseClass"
  expect :class
  name=Identifier.new(expect :identifier)
  if showNext.is_a? :lt
    acceptIt
    inheritance= Identifier.new(expect :identifier)
  end
  attrs=[]
  while showNext.is_a? :attr
    attrs << parseAttr
  end
  expect :end
  dedent
  return Astrapi::Klass.new(name,inheritance,attrs)
end

#parseModuleObject



44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/parser.rb', line 44

def parseModule
  indent "parseModule"
  expect :module
  name=Identifier.new(expect :identifier)
  classes=[]
  while showNext.is_a? :class
    classes << parseClass
  end
  expect :end
  dedent
  return Astrapi::Module.new(name,classes)
end

#showNextObject



32
33
34
# File 'lib/parser.rb', line 32

def showNext
  tokens.first
end