code-parser.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import { VarType } from '../../types'
  2. import type { OutputVar } from './types'
  3. import { CodeLanguage } from './types'
  4. export const extractFunctionParams = (code: string, language: CodeLanguage) => {
  5. if (language === CodeLanguage.json)
  6. return []
  7. const patterns: Record<Exclude<CodeLanguage, CodeLanguage.json>, RegExp> = {
  8. [CodeLanguage.python3]: /def\s+main\s*\((.*?)\)/,
  9. [CodeLanguage.javascript]: /function\s+main\s*\((.*?)\)/,
  10. }
  11. const match = code.match(patterns[language])
  12. const params: string[] = []
  13. if (match?.[1]) {
  14. params.push(...match[1].split(',')
  15. .map(p => p.trim())
  16. .filter(Boolean)
  17. .map(p => p.split(':')[0].trim()),
  18. )
  19. }
  20. return params
  21. }
  22. export const extractReturnType = (code: string, language: CodeLanguage): OutputVar => {
  23. const codeWithoutComments = code.replace(/\/\*\*[\s\S]*?\*\//, '')
  24. console.log(codeWithoutComments)
  25. const returnIndex = codeWithoutComments.indexOf('return')
  26. if (returnIndex === -1)
  27. return {}
  28. // returnから始まる部分文字列を取得
  29. const codeAfterReturn = codeWithoutComments.slice(returnIndex)
  30. let bracketCount = 0
  31. let startIndex = codeAfterReturn.indexOf('{')
  32. if (language === CodeLanguage.javascript && startIndex === -1) {
  33. const parenStart = codeAfterReturn.indexOf('(')
  34. if (parenStart !== -1)
  35. startIndex = codeAfterReturn.indexOf('{', parenStart)
  36. }
  37. if (startIndex === -1)
  38. return {}
  39. let endIndex = -1
  40. for (let i = startIndex; i < codeAfterReturn.length; i++) {
  41. if (codeAfterReturn[i] === '{')
  42. bracketCount++
  43. if (codeAfterReturn[i] === '}') {
  44. bracketCount--
  45. if (bracketCount === 0) {
  46. endIndex = i + 1
  47. break
  48. }
  49. }
  50. }
  51. if (endIndex === -1)
  52. return {}
  53. const returnContent = codeAfterReturn.slice(startIndex + 1, endIndex - 1)
  54. console.log(returnContent)
  55. const result: OutputVar = {}
  56. const keyRegex = /['"]?(\w+)['"]?\s*:(?![^{]*})/g
  57. const matches = returnContent.matchAll(keyRegex)
  58. for (const match of matches) {
  59. console.log(`Found key: "${match[1]}" from match: "${match[0]}"`)
  60. const key = match[1]
  61. result[key] = {
  62. type: VarType.string,
  63. children: null,
  64. }
  65. }
  66. console.log(result)
  67. return result
  68. }