teal-language / tl

The compiler for Teal, a typed dialect of Lua
MIT License
2.03k stars 101 forks source link

tl API, xy values -> char number #676

Closed Frityet closed 11 months ago

Frityet commented 12 months ago

Hello, I would like to convert the Node's x and y fields into the character number in the text

hishamhm commented 12 months ago

There is no automatic way to do it, currently. You'd have to scan the file yourself, count the length of each line and then sum the lengths from lines 1 to y-1, add y-1 to account for the line breaks, then add x.

What is your use case? Tokens used to store this number in older versions, but they weren't propagated to Nodes.

Frityet commented 12 months ago

There is no automatic way to do it, currently. You'd have to scan the file yourself, count the length of each line and then sum the lengths from lines 1 to y-1, add y-1 to account for the line breaks, then add x.

What is your use case? Tokens used to store this number in older versions, but they weren't propagated to Nodes.

I am trying to create a plugin for the lua-language-server to let me use Teal with the server, where the plugin auto-compiles the code into annotations

global function add(x: integer, y: integer): integer
        return x + y;
end

would become

---@param x integer
---@param y integer
---@return integer
function add(x, y)
        return x + y;
end
Frityet commented 12 months ago

I need to use the char count because how how the plugin API works, where

function OnSetText(uri, text)
    if text:sub(1, 4) ~= '--##' then
        return nil
    end
    local diffs = {}
    diffs[#diffs+1] = {
        start  = 1,
        finish = 4,
        text   = '',
    }

    for localPos, colonPos, typeName, finish in text:gmatch '()local%s+[%w_]+()%s*%:%s*([%w_]+)()' do
        diffs[#diffs+1] = {
            start  = localPos,
            finish = localPos - 1,
            text   = ('---@type %s\n'):format(typeName),
        }
        diffs[#diffs+1] = {
            start  = colonPos,
            finish = finish - 1,
            text   = '',
        }
    end

    return diffs
end

would replace all instances of

local var: integer = 4
``` with
```lua
---@type integer
local var = 4