Skip to content

Commit

Permalink
Added extra options to loxfmt
Browse files Browse the repository at this point in the history
  • Loading branch information
Daniel Berezin committed Jun 7, 2019
1 parent 7aab212 commit 27c20da
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions transpilers/lox.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ const {
Condition
} = require('../types')

const condChar = (condition, replacer = ' ') => condition ? replacer : ''

const ASTNodeMap = new Map()

// Declarations
Expand All @@ -38,24 +40,24 @@ ASTNodeMap.set(VarStatement, node => {

ASTNodeMap.set(Condition, ({ condition, thenBranch, elseBranch }, scope, options) => {
const cond = printLoxAST(condition)
const conditionSection = `if (${cond}) `
const conditionSection = `if${condChar(options.spaceBeforeParams)}(${cond}) `
const thenSection = printLoxAST(thenBranch, scope, options, false)
const elseSection = elseBranch && printLoxAST(elseBranch, scope, options, false)
return conditionSection + thenSection + (elseSection ? ` else ${elseSection}` : '')
})

ASTNodeMap.set(LoxFunction, ({ bodyStatements: body, name: { lexeme: name }, params}, scope, options) => {
const parameters = params.map(token => token.lexeme)
const head = `fun ${name}(${parameters.join(', ')}) {`
const head = `fun ${name}${condChar(options.spaceBeforeParams)}(${parameters.join(', ')}) {`
const fnBody = body.map(stmt => printLoxAST(stmt, scope + 1, options))
const tail = options.indent.repeat(scope) + '}'
const tail = options.indent.repeat(scope) + '}' + condChar(options.functionNewlines, '\n')
return [head, ...fnBody, tail].join('\n')
})


const handleWhileLoop = ({ body, condition }, scope, options) => {
const cond = printLoxAST(condition)
const conditionSection = `while (${cond}) `
const conditionSection = `while${condChar(options.spaceBeforeParams)}(${cond}) `
const bodySection = printLoxAST(body, scope, options, false)
return conditionSection + bodySection
}
Expand All @@ -73,7 +75,7 @@ const whileForLoop = ({ body, condition }, scope, options, initializer = ';') =>
}
const bodySection = printLoxAST(realBody, scope, options, false)
const steps = [cond, inc]
return `for (${initializer} ${steps.join('; ')}) ${bodySection}`
return `for${condChar(options.spaceBeforeParams)}(${initializer} ${steps.join('; ')}) ${bodySection}`
}

ASTNodeMap.set(While, (node, scope, options) => {
Expand Down Expand Up @@ -151,7 +153,8 @@ ASTNodeMap.set(Literal, ({ value }) => {
const printLoxAST = (node, scope = 0, optionsOverride = {}, initialIndent = true) => {
const options = Object.assign({}, {
indent: '\t',
spaceBeforeParams: true
spaceBeforeParams: true,
functionNewlines: true
}, optionsOverride)

if (ASTNodeMap.has(node.constructor)) {
Expand Down

0 comments on commit 27c20da

Please sign in to comment.