summaryrefslogtreecommitdiffstats
path: root/lib/puppet/parser/lexer.rb
blob: a7b87e6d18569221acc733288f7f593048279c2f (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
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
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
# the scanner/lexer

require 'strscan'
require 'puppet'


module Puppet
    class LexError < RuntimeError; end
end

module Puppet::Parser; end

class Puppet::Parser::Lexer
    attr_reader :last, :file

    attr_accessor :line, :indefine

    # Our base token class.
    class Token
        attr_accessor :regex, :name, :string, :skip, :incr_line, :skip_text, :accumulate

        def initialize(regex, name)
            if regex.is_a?(String)
                @name, @string = name, regex
                @regex = Regexp.new(Regexp.escape(@string))
            else
                @name, @regex = name, regex
            end
        end

        %w{skip accumulate}.each do |method|
            define_method(method+"?") do
                self.send(method)
            end
        end

        def to_s
            if self.string
                @string
            else
                @name.to_s
            end
        end
    end

    # Maintain a list of tokens.
    class TokenList
        attr_reader :regex_tokens, :string_tokens

        def [](name)
            @tokens[name]
        end

        # Create a new token.
        def add_token(name, regex, options = {}, &block)
            token = Token.new(regex, name)
            raise(ArgumentError, "Token %s already exists" % name) if @tokens.include?(name)
            @tokens[token.name] = token
            if token.string
                @string_tokens << token
                @tokens_by_string[token.string] = token
            else
                @regex_tokens << token
            end

            options.each do |name, option|
                token.send(name.to_s + "=", option)
            end

            token.meta_def(:convert, &block) if block_given?

            token
        end

        def initialize
            @tokens = {}
            @regex_tokens = []
            @string_tokens = []
            @tokens_by_string = {}
        end

        # Look up a token by its value, rather than name.
        def lookup(string)
            @tokens_by_string[string]
        end

        # Define more tokens.
        def add_tokens(hash)
            hash.each do |regex, name|
                add_token(name, regex)
            end
        end

        # Sort our tokens by length, so we know once we match, we're done.
        # This helps us avoid the O(n^2) nature of token matching.
        def sort_tokens
            @string_tokens.sort! { |a, b| b.string.length <=> a.string.length }
        end
    end

    TOKENS = TokenList.new
    TOKENS.add_tokens(
        '[' => :LBRACK,
        ']' => :RBRACK,
        '{' => :LBRACE,
        '}' => :RBRACE,
        '(' => :LPAREN,
        ')' => :RPAREN,
        '=' => :EQUALS,
        '+=' => :APPENDS,
        '==' => :ISEQUAL,
        '>=' => :GREATEREQUAL,
        '>' => :GREATERTHAN,
        '<' => :LESSTHAN,
        '<=' => :LESSEQUAL,
        '!=' => :NOTEQUAL,
        '!' => :NOT,
        ',' => :COMMA,
        '.' => :DOT,
        ':' => :COLON,
        '@' => :AT,
        '<<|' => :LLCOLLECT,
        '|>>' => :RRCOLLECT,
        '<|' => :LCOLLECT,
        '|>' => :RCOLLECT,
        ';' => :SEMIC,
        '?' => :QMARK,
        '\\' => :BACKSLASH,
        '=>' => :FARROW,
        '+>' => :PARROW,
        '+' => :PLUS,
        '-' => :MINUS,
        '/' => :DIV,
        '*' => :TIMES,
        '<<' => :LSHIFT,
        '>>' => :RSHIFT,
        %r{([a-z][-\w]*)?(::[a-z][-\w]*)+} => :CLASSNAME, # Require '::' in the class name, else we'd compete with NAME
        %r{((::){0,1}[A-Z][-\w]*)+} => :CLASSREF
    )

    TOKENS.add_tokens "Whatever" => :DQTEXT, "Nomatter" => :SQTEXT, "alsonomatter" => :BOOLEAN

    TOKENS.add_token :NUMBER, %r{\b(?:0[xX][0-9A-Fa-f]+|0?\d+(?:\.\d+)?(?:[eE]-?\d+)?)\b} do |lexer, value|
        [TOKENS[:NAME], value]
    end

    TOKENS.add_token :NAME, %r{[a-z0-9][-\w]*} do |lexer, value|
        string_token = self
        # we're looking for keywords here
        if tmp = KEYWORDS.lookup(value)
            string_token = tmp
            if [:TRUE, :FALSE].include?(string_token.name)
                value = eval(value)
                string_token = TOKENS[:BOOLEAN]
            end
        end
        [string_token, value]
    end

    TOKENS.add_token :COMMENT, %r{#.*}, :accumulate => true, :skip => true do |lexer,value|
        value.sub!(/# ?/,'')
        [self, value]
    end

    TOKENS.add_token :MLCOMMENT, %r{/\*(.*?)\*/}m, :accumulate => true, :skip => true do |lexer, value|
        lexer.line += value.count("\n")
        value.sub!(/^\/\* ?/,'')
        value.sub!(/ ?\*\/$/,'')
        [self,value]
    end

    TOKENS.add_token :RETURN, "\n", :skip => true, :incr_line => true, :skip_text => true

    TOKENS.add_token :SQUOTE, "'" do |lexer, value|
        value = lexer.slurpstring(value)
        [TOKENS[:SQTEXT], value]
    end

    TOKENS.add_token :DQUOTE, '"' do |lexer, value|
        value = lexer.slurpstring(value)
        [TOKENS[:DQTEXT], value]
    end

    TOKENS.add_token :VARIABLE, %r{\$(\w*::)*\w+} do |lexer, value|
        value = value.sub(/^\$/, '')
        [self, value]
    end

    TOKENS.sort_tokens

    @@pairs = {
        "{" => "}",
        "(" => ")",
        "[" => "]",
        "<|" => "|>",
        "<<|" => "|>>"
    }

    KEYWORDS = TokenList.new

    KEYWORDS.add_tokens(
        "case" => :CASE,
        "class" => :CLASS,
        "default" => :DEFAULT,
        "define" => :DEFINE,
        "import" => :IMPORT,
        "if" => :IF,
        "elsif" => :ELSIF,
        "else" => :ELSE,
        "inherits" => :INHERITS,
        "node" => :NODE,
        "and"  => :AND,
        "or"   => :OR,
        "undef"   => :UNDEF,
        "false" => :FALSE,
        "true" => :TRUE
    )

    def clear
        initvars
    end

    def expected
        return nil if @expected.empty?
        name = @expected[-1]
        raise "Could not find expected token %s" % name unless token = TOKENS.lookup(name)

        return token
    end

    # scan the whole file
    # basically just used for testing
    def fullscan
        array = []

        self.scan { |token, str|
            # Ignore any definition nesting problems
            @indefine = false
            array.push([token,str])
        }
        return array
    end

    # this is probably pretty damned inefficient...
    # it'd be nice not to have to load the whole file first...
    def file=(file)
        @file = file
        @line = 1
        File.open(file) { |of|
            str = ""
            of.each { |line| str += line }
            @scanner = StringScanner.new(str)
        }
    end

    def find_string_token
        matched_token = value = nil

        # We know our longest string token is three chars, so try each size in turn
        # until we either match or run out of chars.  This way our worst-case is three
        # tries, where it is otherwise the number of string chars we have.  Also,
        # the lookups are optimized hash lookups, instead of regex scans.
        [3, 2, 1].each do |i|
            str = @scanner.peek(i)
            if matched_token = TOKENS.lookup(str)
                value = @scanner.scan(matched_token.regex)
                break
            end
        end

        return matched_token, value
    end

    # Find the next token that matches a regex.  We look for these first.
    def find_regex_token
        @regex += 1
        matched_token = nil
        value = ""
        length = 0

        # I tried optimizing based on the first char, but it had
        # a slightly negative affect and was a good bit more complicated.
        TOKENS.regex_tokens.each do |token|
            next unless match_length = @scanner.match?(token.regex) 
            
            # We've found a longer match
            if match_length > length
                value = @scanner.scan(token.regex) 
                length = value.length
                matched_token = token
            end
        end

        return matched_token, value
    end

    # Find the next token, returning the string and the token.
    def find_token
        @find += 1
        matched_token, value = find_regex_token

        unless matched_token
            matched_token, value = find_string_token
        end

        return matched_token, value
    end

    def indefine?
        if defined? @indefine
            @indefine
        else
            false
        end
    end

    def initialize
        @find = 0
        @regex = 0
        initvars()
    end

    def initvars
        @line = 1
        @previous_token = nil
        @scanner = nil
        @file = nil
        # AAARRGGGG! okay, regexes in ruby are bloody annoying
        # no one else has "\n" =~ /\s/
        @skip = %r{[ \t]+}

        @namestack = []
        @indefine = false
        @expected = []
        @commentstack = ['']
    end

    # Make any necessary changes to the token and/or value.
    def munge_token(token, value)
        @line += 1 if token.incr_line

        skip() if token.skip_text

        return if token.skip and not token.accumulate?

        token, value = token.convert(self, value) if token.respond_to?(:convert)

        return unless token

        if token.accumulate?
            @commentstack.last << value + "\n"
        end

        return if token.skip

        return token, value
    end

    # Go up one in the namespace.
    def namepop
        @namestack.pop
    end

    # Collect the current namespace.
    def namespace
        @namestack.join("::")
    end

    # This value might have :: in it, but we don't care -- it'll be
    # handled normally when joining, and when popping we want to pop
    # this full value, however long the namespace is.
    def namestack(value)
        @namestack << value
    end

    def rest
        @scanner.rest
    end

    # this is the heart of the lexer
    def scan
        #Puppet.debug("entering scan")
        raise Puppet::LexError.new("Invalid or empty string") unless @scanner

        # Skip any initial whitespace.
        skip()

        until @scanner.eos? do
            yielded = false
            matched_token, value = find_token

            # error out if we didn't match anything at all
            if matched_token.nil?
                nword = nil
                # Try to pull a 'word' out of the remaining string.
                if @scanner.rest =~ /^(\S+)/
                    nword = $1
                elsif @scanner.rest =~ /^(\s+)/
                    nword = $1
                else
                    nword = @scanner.rest
                end
                raise "Could not match '%s'" % nword
            end

            if matched_token.name == :RETURN
                # this matches a blank line
                if @last_return
                    # eat the previously accumulated comments
                    getcomment
                end
                # since :RETURN skips, we won't survive to munge_token
                @last_return = true
            else
                @last_return = false
            end

            final_token, value = munge_token(matched_token, value)

            next unless final_token

            if match = @@pairs[value] and final_token.name != :DQUOTE and final_token.name != :SQUOTE
                @expected << match
            elsif exp = @expected[-1] and exp == value and final_token.name != :DQUOTE and final_token.name != :SQUOTE
                @expected.pop
            end

            if final_token.name == :LBRACE
                commentpush
            end

            yield [final_token.name, value]

            if @previous_token
                namestack(value) if @previous_token.name == :CLASS

                if @previous_token.name == :DEFINE
                    if indefine?
                        msg = "Cannot nest definition %s inside %s" % [value, @indefine]
                        self.indefine = false
                        raise Puppet::ParseError, msg
                    end

                    @indefine = value
                end
            end
            @previous_token = final_token
            skip()
        end
        @scanner = nil

        # This indicates that we're done parsing.
        yield [false,false]
    end

    # Skip any skipchars in our remaining string.
    def skip
        @scanner.skip(@skip)
    end

    # we've encountered an opening quote...
    # slurp in the rest of the string and return it
    def slurpstring(quote)
        # we search for the next quote that isn't preceded by a
        # backslash; the caret is there to match empty strings
        str = @scanner.scan_until(/([^\\]|^)#{quote}/)
        if str.nil?
            raise Puppet::LexError.new("Unclosed quote after '%s' in '%s'" %
                [self.last,self.rest])
        else
            str.sub!(/#{quote}\Z/,"")
            str.gsub!(/\\#{quote}/,quote)
        end

        # Add to our line count for every carriage return in multi-line strings.
        @line += str.count("\n")

        return str
    end

    # just parse a string, not a whole file
    def string=(string)
        @scanner = StringScanner.new(string)
    end

    # returns the content of the currently accumulated content cache
    def commentpop
        return @commentstack.pop
    end

    def getcomment
        comment = @commentstack.pop
        @commentstack.push('')
        return comment
    end

    def commentpush
        @commentstack.push('')
    end
end