Skip to content

Commit

Permalink
Add Brainfuck lexer (#1037)
Browse files Browse the repository at this point in the history
This adds support for the Brainfuck language.
  • Loading branch information
espositoandrea authored and pyrmont committed Jun 16, 2019
1 parent de91c27 commit 004b6f4
Show file tree
Hide file tree
Showing 4 changed files with 105 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/rouge/demos/brainfuck
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[
This is a sample
comment.
]
.[>+<-]>,
53 changes: 53 additions & 0 deletions lib/rouge/lexers/brainfuck.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# -*- coding: utf-8 -*- #
# frozen_string_literal: true

module Rouge
module Lexers
class Brainfuck < RegexLexer
tag 'brainfuck'
filenames '*.b', '*.bf'
mimetypes 'text/x-brainfuck'

title "Brainfuck"
desc "The Brainfuck programming language"

start { push :bol }

state :bol do
rule /\s+/m, Text
rule /\[/, Comment::Multiline, :comment_multi
rule(//) { pop! }
end

state :root do
rule /\]/, Error
rule /\[/, Punctuation, :loop

mixin :comment_single
mixin :commands
end

state :comment_multi do
rule /\[/, Comment::Multiline, :comment_multi
rule /\]/, Comment::Multiline, :pop!
rule /[^\[\]]+?/m, Comment::Multiline
end

state :comment_single do
rule /[^><+\-.,\[\]]+/, Comment::Single
end

state :loop do
rule /\[/, Punctuation, :loop
rule /\]/, Punctuation, :pop!
mixin :comment_single
mixin :commands
end

state :commands do
rule /[><]+/, Name::Builtin
rule /[+\-.,]+/, Name::Function
end
end
end
end
27 changes: 27 additions & 0 deletions spec/lexers/brainfuck_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# -*- coding: utf-8 -*- #
# frozen_string_literal: true

describe Rouge::Lexers::Brainfuck do
let(:subject) { Rouge::Lexers::Brainfuck.new }

describe 'guessing' do
include Support::Guessing

it 'guesses by filename' do
assert_guess :filename => 'foo.b'
assert_guess :filename => 'FOO.bf', :source => 'foo'
end

it 'guesses by mimetype' do
assert_guess :mimetype => 'text/x-brainfuck'
end
end

describe 'lexing' do
include Support::Lexing

it 'recognizes one-line comments not followed by a newline (#796)' do
assert_tokens_equal 'comment', ['Comment.Single', 'comment']
end
end
end
20 changes: 20 additions & 0 deletions spec/visual/samples/brainfuck
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[
This program will print "Hello world!"
]
++++++++++
[
>+++++++>++++++++++>+++>+<<<<-
]
>++. Initial loop (it will be printed an H)
>+. e
+++++++. l
. l
+++. o
>++. space
<<+++++++++++++++. W
>. o
+++. r
------. l
--------. d
>+. !
>.

0 comments on commit 004b6f4

Please sign in to comment.