Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

136
Visualizações
How to convert a TemplateLiteral AST node back into template string source code?

So I am working through "normalizing" a JS AST in certain ways to make transpilation easier into a particular target language. So I am having to learn the inner details of the AST. Then for testing, I am converting it back into JS source code, using print functions. I have handled pretty much every case so far, but the TemplateLiteral seems like it's a strange structure.

For example, you have this template string:

const str = 'const b83 = `foo${a100} bar ${b82}`'

Parse that str into an AST and you get this structure:

{
  "type": "TemplateLiteral",
  "start": 2692,
  "end": 2715,
  "expressions": [
    {
      "type": "Identifier",
      "start": 2698,
      "end": 2702,
      "name": "a100"
    },
    {
      "type": "Identifier",
      "start": 2710,
      "end": 2713,
      "name": "b82"
    }
  ],
  "quasis": [
    {
      "type": "TemplateElement",
      "start": 2693,
      "end": 2696,
      "value": {
        "raw": "foo",
        "cooked": "foo"
      },
      "tail": false
    },
    {
      "type": "TemplateElement",
      "start": 2703,
      "end": 2708,
      "value": {
        "raw": " bar ",
        "cooked": " bar "
      },
      "tail": false
    },
    {
      "type": "TemplateElement",
      "start": 2714,
      "end": 2714,
      "value": {
        "raw": "",
        "cooked": ""
      },
      "tail": true
    }
  ]
}

Notice, the "expressions" and "quasis" are not interlaced, they are made into separate arrays. How am I to go back and properly put them in the right order to regenerate the template string source code? Assume this AST node might be part of a larger AST, and the tree might be rewritten, so any information you use regarding the start and end text positions will only be useful from a relative, not absolute, perspective. I am just not quite sure the best way to read the start and end to re-interlace the expressions and quasis.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You're always going to have quasis.length == expressions.length+1. You just take the first quasi, then the first expression, then the next quasi, then the next expression, etc., until the last quasi.

about 4 years ago · Juan Pablo Isaza Relatório

0

function getResultFromTemplateLiteral(ret, path) {


    const { expressions, quasis } = ret

    // 拼接模板
    let str = ''
    for (let i = 0; i < quasis.length; i++) {
        if (i) {
            str += '__' + expressions[i - 1].name + '__'
        }
        str += quasis[i].value.cooked
    }

    // 收集变量引用
    const expMap = new Map()

    for (let i = 0; i < expressions.length; i++) {
        const { name } = expressions[i]

        if (!expMap.has(name)) {
            const ref = path.scope.getBinding(name)
            if (ref) {
                let { init, init: { type, value } } = ref.path.node
                if (type === 'StringLiteral') {
                    expMap.set(name, value)
                } else if (type === 'TemplateLiteral') {
                    expMap.set(name, getResultFromTemplateLiteral(init, path))
                }
            } else {
                expMap.set(name, '')
            }
        }
    }

    return str = str.replace(/__(.*?)__/gim, name => expMap.get(name.replace(/__/g, '')))

    
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda