Browse Source

Prevent circular/repeated sources of a file, ordering is now important as this essentially creates one complete JS file with all the sources just dumped in wherever a call to `source is made

Matt Coles 9 years ago
parent
commit
b736eb1651
1 changed files with 14 additions and 6 deletions
  1. 14 6
      compiler.js

+ 14 - 6
compiler.js

@@ -1,12 +1,20 @@
1 1
 const fs = require('fs')
2
+const sourcedFiles = []
2 3
 
3
-var preprocess = function (input) {
4
+var preprocess = function (fileNameIn, input) {
4 5
   let inputArr = input.split('\n')
6
+  sourcedFiles.push(fileNameIn)
5 7
   for (i = 0; i < inputArr.length; i++) {
6 8
     line = inputArr[i]
7 9
     if (line.startsWith('`source')) {
8
-      line = fs.readFileSync(line.split(' ')[1], { encoding: 'utf-8' })
9
-      inputArr[i] = preprocess(line)
10
+      let fileName = line.split(' ')[1]
11
+      if (!~sourcedFiles.indexOf(fileName)) {
12
+        line = fs.readFileSync(fileName, { encoding: 'utf-8' })
13
+        inputArr[i] = preprocess(fileName, line)
14
+      } else {
15
+        inputArr[i] = '\n'
16
+        console.log('Already sourced file: ' + fileName + '; Skipping!')
17
+      }
10 18
     }
11 19
   }
12 20
   return inputArr.join('\n')
@@ -37,9 +45,9 @@ var tokenizer = function (input) {
37 45
       pos++
38 46
       continue
39 47
     }
40
-    let whitespace = /[;\s]/
48
+    let whitespace = /[;\s]/ // Include comments as a whitespace character as they are ignored
41 49
     if (whitespace.test(char)) {
42
-      if (char === ';') {
50
+      if (char === ';') { // Rest of line is ignored
43 51
         comment = ''
44 52
         while (char !== '\n') {
45 53
           comment += char
@@ -426,7 +434,7 @@ const fileNameIn = process.argv[2]
426 434
 const fileNameOut = fileNameIn + '.js'
427 435
 const myInput = fs.readFileSync(process.argv[2], { encoding: 'utf-8' })
428 436
 
429
-const preProcessedInput = preprocess(myInput) // Run the preprocessor to evaluate any `source's
437
+const preProcessedInput = preprocess(fileNameIn, myInput) // Run the preprocessor to evaluate any `source's
430 438
 const myTokens = tokenizer(preProcessedInput) // Convert our input into individual tokens
431 439
 const parsedTree = parser(myTokens) // Convert these tokens into a syntax tree
432 440
 const transformedTree = transformer(parsedTree) // Now put the tree into an easily traversable format for our generator