-
Notifications
You must be signed in to change notification settings - Fork 27
/
sbn.js
371 lines (335 loc) · 10.1 KB
/
sbn.js
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
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.sbn = factory());
}(this, (function () { 'use strict';
// \s : matches any whitespace character (equal to [\r\n\t\f\v ])
// + : match previous condition for one and unlimited times
function lexer (code) {
var _tokens = code
.replace(/[\n\r]/g, ' *nl* ')
.replace(/\[/g, ' *ob* ')
.replace(/\]/g, ' *cb* ')
.replace(/\{/g, ' *ocb* ')
.replace(/\}/g, ' *ccb* ')
.split(/[\t\f\v ]+/)
var tokens = []
for (var i = 0; i < _tokens.length; i++) {
var t = _tokens[i]
if(t.length <= 0 || isNaN(t)) {
if (t === '*nl*') {
tokens.push({type: 'newline'})
} else if (t === '*ob*') {
tokens.push({type: 'ob'})
} else if (t === '*cb*') {
tokens.push({type: 'cb'})
} else if (t === '*ocb*') {
tokens.push({type: 'ocb'})
} else if (t === '*ccb*') {
tokens.push({type: 'ccb'})
} else if(t.length > 0) {
tokens.push({type: 'word', value: t})
}
} else {
tokens.push({type: 'number', value: t})
}
}
if (tokens.length < 1) {
throw 'No Tokens Found. Try "Paper 10"'
}
return tokens
}
function parser (tokens) {
function expectedTypeCheck (type, expect) {
if(Array.isArray(expect)) {
var i = expect.indexOf(type)
return i >= 0
}
return type === expect
}
function createDot (current_token, currentPosition, node) {
var expectedType = ['ob', 'number', 'number', 'cb']
var expectedLength = 4
currentPosition = currentPosition || 0
node = node || {type: 'dot'}
if (currentPosition < expectedLength - 1) {
if (expectedTypeCheck(current_token.type, expectedType[currentPosition])){
if(currentPosition === 1) {
node.x = current_token.value
}
if(currentPosition === 2) {
node.y = current_token.value
}
currentPosition++
createDot(tokens.shift(), currentPosition, node)
} else {
throw 'Expected ' + expectedType[currentPosition] + ' but found ' + current_token.type + '.'
}
}
return node
}
function findArguments(command, expectedLength, expectedType, currentPosition, currentList) {
currentPosition = currentPosition || 0
currentList = currentList || []
while (expectedLength > currentPosition) {
var token = tokens.shift()
if (!token) {
throw command + ' takes ' + expectedLength + ' argument(s). '
}
if (expectedType){
var expected = expectedTypeCheck(token.type, expectedType[currentPosition])
if (!expected) {
throw command + ' takes ' + JSON.stringify(expectedType[currentPosition]) + ' as argument ' + (currentPosition + 1) + '. ' + (token ? 'Instead found a ' + token.type + ' '+ (token.value || '') + '.' : '')
}
if (token.type === 'number' && (token.value < 0 || token.value > 100)){
throw 'Found value ' + token.value + ' for ' + command + '. Value must be between 0 - 100.'
}
}
var arg = {
type: token.type,
value: token.value
}
if (token.type === 'ob') {
arg = createDot(token)
}
currentList.push(arg)
currentPosition++
}
return currentList
}
var AST = {
type: 'Drawing',
body: []
}
var paper = false
var pen = false
while (tokens.length > 0) {
var current_token = tokens.shift()
if (current_token.type === 'word') {
switch (current_token.value) {
case '{' :
var block = {
type: 'Block Start'
}
AST.body.push(block)
break
case '}' :
var block = {
type: 'Block End'
}
AST.body.push(block)
break
case '//' :
var expression = {
type: 'CommentExpression',
value: ''
}
var next = tokens.shift()
while (next.type !== 'newline') {
expression.value += next.value + ' '
next = tokens.shift()
}
AST.body.push(expression)
break
case 'Paper' :
if (paper) {
throw 'You can not define Paper more than once'
}
var expression = {
type: 'CallExpression',
name: 'Paper',
arguments: []
}
var args = findArguments('Paper', 1)
expression.arguments = expression.arguments.concat(args)
AST.body.push(expression)
paper = true
break
case 'Pen' :
var expression = {
type: 'CallExpression',
name: 'Pen',
arguments: []
}
var args = findArguments('Pen', 1)
expression.arguments = expression.arguments.concat(args)
AST.body.push(expression)
pen = true
break
case 'Line':
if(!paper) {
// throw 'Please make Paper 1st'
// TODO : no error message 'You should make paper first'
}
if(!pen) {
// throw 'Please define Pen 1st'
// TODO : no error message 'You should set pen color first'
}
var expression = {
type: 'CallExpression',
name: 'Line',
arguments: []
}
var args = findArguments('Line', 4)
expression.arguments = expression.arguments.concat(args)
AST.body.push(expression)
break
case 'Set':
var args = findArguments('Set', 2, [['word', 'ob'], 'number'])
var obj = {}
if (args[0].type === 'dot') {
AST.body.push({
type: 'CallExpression',
name: 'Pen',
arguments:[args[1]]
})
obj.type = 'CallExpression',
obj.name = 'Line',
obj.arguments = [
{ type: 'number', value: args[0].x},
{ type: 'number', value: args[0].y},
{ type: 'number', value: args[0].x},
{ type: 'number', value: args[0].y}
]
} else {
obj.type = 'VariableDeclaration'
obj.name = 'Set'
obj.identifier = args[0]
obj.value = args[1]
}
AST.body.push(obj)
break
default:
throw current_token.value + ' is not a valid command'
}
} else if (['newline', 'ocb', 'ccb'].indexOf[current_token.type] < 0 ) {
throw 'Unexpected token type : ' + current_token.type
}
}
return AST
}
function transformer (ast) {
function makeColor (level) {
if (typeof level === 'undefined') {
level = 100
}
level = 100 - parseInt(level, 10) // flip
return 'rgb(' + level + '%, ' + level + '%, ' + level + '%)'
}
function findParamValue (p) {
if (p.type === 'word') {
return variables[p.value]
}
return p.value
}
var elements = {
'Line' : function (param, pen_color_value) {
return {
tag: 'line',
attr: {
x1: findParamValue(param[0]),
y1: 100 - findParamValue(param[1]),
x2: findParamValue(param[2]),
y2: 100 - findParamValue(param[3]),
stroke: makeColor(pen_color_value),
'stroke-linecap': 'round'
},
body: []
}
},
'Paper' : function (param) {
return {
tag : 'rect',
attr : {
x: 0,
y: 0,
width: 100,
height:100,
fill: makeColor(findParamValue(param[0]))
},
body : []
}
}
}
var newAST = {
tag : 'svg',
attr: {
width: 100,
height: 100,
viewBox: '0 0 100 100',
xmlns: 'http://www.w3.org/2000/svg',
version: '1.1'
},
body:[]
}
var current_pen_color
// TODO : warning when paper and pen is same color
var variables = {}
while (ast.body.length > 0) {
var node = ast.body.shift()
if(node.type === 'CallExpression' || node.type === 'VariableDeclaration') {
if(node.name === 'Pen') {
current_pen_color = findParamValue(node.arguments[0])
} else if (node.name === 'Set') {
variables[node.identifier.value] = node.value.value
} else {
var el = elements[node.name]
if (!el) {
throw node.name + ' is not a valid command.'
}
if (typeof !current_pen_color === 'undefined') {
// throw 'Please define Pen before drawing Line.'
// TODO : message 'You should define Pen before drawing Line'
}
newAST.body.push(el(node.arguments, current_pen_color))
}
}
}
return newAST
}
function generator (ast) {
function traverseSvgAst(obj, parent, rest, text) {
parent = parent || []
rest = rest || []
text = text || ''
if (!Array.isArray(obj)) {
obj = [obj]
}
while (obj.length > 0) {
var currentNode = obj.shift()
var body = currentNode.body || ''
var attr = Object.keys(currentNode.attr).map(function (key){
return key + '="' + currentNode.attr[key] + '"'
}).join(' ')
text += parent.map(function(){return '\t'}).join('') + '<' + currentNode.tag + ' ' + attr + '>'
if (currentNode.body && Array.isArray(currentNode.body) && currentNode.body.length > 0) {
text += '\n'
parent.push(currentNode.tag)
rest.push(obj)
return traverseSvgAst(currentNode.body, parent, rest, text)
}
text += body + '</'+ currentNode.tag +'>\n'
}
while (rest.length > 0) {
var next = rest.pop()
var tag = parent.pop()
text += parent.map(function(){return '\t'}).join('') + '</'+ tag +'>\n'
if (next.length > 0) {
traverseSvgAst(next, parent, rest, text)
}
}
return text
}
return traverseSvgAst(ast)
}
var SBN = {}
SBN.VERSION = '0.5.6'
SBN.lexer = lexer
SBN.parser = parser
SBN.transformer = transformer
SBN.generator = generator
SBN.compile = function (code) {
return this.generator(this.transformer(this.parser(this.lexer(code))))
}
return SBN;
})));