Node.js get застрял в цикле while, и я не знаю почему

#javascript #node.js #loops #while-loop

#javascript #node.js #циклы #цикл while

Вопрос:

Итак, я недавно работал над интерпретатором для очень маленького пользовательского языка программирования для выполнения операций с файловой системой. В настоящее время я работаю над каким-то лексером, и у меня возникла проблема, когда он застревает в цикле while, и через некоторое время, очевидно, приводит к ошибке нехватки памяти. Вот код:

 const fs = require('fs')

const tt_comma = 'comma'
const tt_string = 'string'
const tt_keywords = ['delete', 'write', 'append', 'copy', 'rename', 'move']

class Token {
    constructor(type, value) {
        this.type = type
        if (value) {
            this.value = value
        }
    }


}

class Lexer {

    constructor(src) {
        this.pos = -1
        this.currentCharacter = ''
        this.src = src
        this.advance(1)
        console.log(this.tokenize())
    }

    advance(amount) {
        this.pos  = amount
        console.log(`Advanced ${amount} characters`)
        this.currentCharacter = this.src[this.pos]
        console.log(`Current character: '${this.pos}:${this.currentCharacter}'`)
    }

    tokenize() {
        let tokens = []
        while (this.pos < this.src.length) {
            if (this.currentCharacter === ' ' || this.currentCharacter === 't') {
                this.advance(1)
            }
            if (this.currentCharacter === '"') {
                let str = '';
                while (this.currentCharacter !== '"') {
                    this.advance()
                    str  = this.currentCharacter
                }
                tokens.push(new Token(tt_string, str))
            }
            else {
                for (let i = 0; i < tt_keywords.length; i  ) {
                    if (typeof this.src.indexOf(tt_keywords[i], this.src.length) == 'number') {
                        tokens.push(new Token(tt_keywords[i]))
                        this.advance(tt_keywords[i].length)
                        break
                    }
                    else {
                        throw new Error('Lazy error')
                    }
                }
            }
        }
        return tokens
    }

}

let lexer = new Lexer(fs.readFileSync('main.fss',"ascii"))

 

Комментарии:

1. while (this.currentCharacter !== '"') { this.advance() Здесь вы не перемещаете позицию. Undefined преобразуется в ноль, когда вы используете его в математических операциях

2. @Darth большое спасибо. Не могу поверить, что я допустил такую глупую ошибку…

3. Это выглядит недостижимым. Возможно, я что-то упускаю.