Add an experiment reading out a JSDoc comment

This commit is contained in:
Jos de Jong 2023-08-18 17:39:57 +02:00
parent 16eb09fe61
commit 3653077c95
7 changed files with 148 additions and 71 deletions

View file

@ -0,0 +1,16 @@
// @ts-check
/**
* Function square
*
* Description of function square bla bla bla
*
* @param {{
* multiply: (a: number, b: number) => number,
* unaryMinus: (x: number) => number
* }} dep
* @return {(a: number) => number}
*/
export function square3 (dep) {
return z => dep.multiply(z, z)
}

View file

@ -1,4 +1,4 @@
export function infer<T>(arg: T) : T {
console.error('infer should be replace with runtime type information by a magic TypeScript plugin')
console.error('infer should be replaced with runtime type information by a magic TypeScript plugin')
return arg
}

View file

@ -27,7 +27,7 @@ export function infer(sourceFile: ts.SourceFile) {
// z => dep.multiply(z, z)
// )
if (node?.['name']?.kind === ts.SyntaxKind.Identifier && node?.['name']['escapedText'] === 'dep') {
console.log('dep', getType(node['type'].kind), node)
// console.log('dep', getType(node['type'].kind), node)
node['type']?.members?.forEach(member => {
console.log('member', {

67
src/plugins/infer3.ts Normal file
View file

@ -0,0 +1,67 @@
import { readFileSync } from "fs";
import * as ts from "typescript";
import { inspect } from 'util'
export function infer3(sourceFile: ts.SourceFile) {
recurse(sourceFile);
function getType(kind: number) {
switch(kind) {
case ts.SyntaxKind.NumberKeyword: return 'number'
case ts.SyntaxKind.StringKeyword: return 'string'
case ts.SyntaxKind.BooleanKeyword: return 'boolean'
case ts.SyntaxKind.JSDoc: return 'jsdoc'
default: return String(ts.SyntaxKind[kind]) // TODO: work out all types
}
}
function recurse(node: ts.Node) {
if (node.kind === ts.SyntaxKind.Identifier) {
console.log('Identifier', node['escapedText'], ts.SyntaxKind[node.kind])
}
if (node['jsDoc']) {
console.log('Found a JSDoc comment:')
// console.log(inspect(node['jsDoc'], { depth: null, colors: true }))
const fullComment = sourceFile.text.slice(node.pos, node.end)
console.log(fullComment)
// TODO: next steps:
// - either get the types from the TypeScript AST,
// or extract them ourselves with regex or anything from the comment text
// - After that, we have to transform the source file and insert the comments
// as string or object that is runtime accessible in JavaScript
}
ts.forEachChild(node, recurse);
}
}
const fileNames = process.argv.slice(2);
console.log('infer files', fileNames)
fileNames.forEach(fileName => {
// Parse a file
const sourceFile = ts.createSourceFile(
fileName,
readFileSync(fileName).toString(),
ts.ScriptTarget.ES2022,
/*setParentNodes */ true
);
console.log('FILE')
console.log(fileName)
console.log()
console.log('SOURCE')
console.log(sourceFile.text)
console.log()
console.log('AST')
console.log(inspect(sourceFile, { depth: null, colors: true }))
console.log()
console.log('INFER')
infer3(sourceFile);
});
console.log('test!!!')