improv: transform autocomplete edge cases

This commit is contained in:
tomasz-io 2024-11-06 13:51:07 +07:00
parent dca5927bcf
commit aa6cebe9f0
16 changed files with 636 additions and 187 deletions

View file

@ -1,4 +1,8 @@
import { LineFilter } from "../filtering/streamTransforms/lineStream";
import { BracketMatchingService } from "../filtering/BracketMatchingService";
import {
CharacterFilter,
LineFilter,
} from "../filtering/streamTransforms/lineStream";
export interface AutocompleteLanguageInfo {
name: string;
@ -7,6 +11,7 @@ export interface AutocompleteLanguageInfo {
endOfLine: string[];
stopWords?: string[];
lineFilters?: LineFilter[];
charFilters?: CharacterFilter[];
useMultiline?: (args: { prefix: string; suffix: string }) => boolean;
}
@ -277,6 +282,25 @@ export const YAML: AutocompleteLanguageInfo = {
],
};
export const Json: AutocompleteLanguageInfo = {
name: "JSON",
topLevelKeywords: [],
singleLineComment: "//",
endOfLine: [",", "}", "]"],
charFilters: [
function matchBrackets({ chars, prefix, suffix, filepath, multiline }) {
const bracketMatchingService = new BracketMatchingService();
return bracketMatchingService.stopOnUnmatchedClosingBracket(
chars,
prefix,
suffix,
filepath,
multiline,
);
},
],
};
export const Markdown: AutocompleteLanguageInfo = {
name: "Markdown",
topLevelKeywords: [],
@ -306,6 +330,7 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = {
ts: Typescript,
js: Typescript,
tsx: Typescript,
json: Json,
jsx: Typescript,
ipynb: Python,
py: Python,

View file

@ -1,6 +1,5 @@
import { streamLines } from "../../../diff/util";
import { HelperVars } from "../../util/HelperVars";
import { BracketMatchingService } from "../BracketMatchingService";
import { stopAtStopTokens } from "./charStream";
import {
avoidEmptyComments,
@ -14,8 +13,6 @@ import {
} from "./lineStream";
export class StreamTransformPipeline {
private bracketMatchingService = new BracketMatchingService();
async *transform(
generator: AsyncGenerator<string>,
prefix: string,
@ -28,13 +25,16 @@ export class StreamTransformPipeline {
let charGenerator = generator;
charGenerator = stopAtStopTokens(generator, stopTokens);
// charGenerator = this.bracketMatchingService.stopOnUnmatchedClosingBracket(
// charGenerator,
// prefix,
// suffix,
// helper.filepath,
// multiline,
// );
for (const charFilter of helper.lang.charFilters ?? []) {
debugger;
charGenerator = charFilter({
chars: charGenerator,
prefix,
suffix,
filepath: helper.filepath,
multiline,
});
}
let lineGenerator = streamLines(charGenerator);

View file

@ -7,6 +7,14 @@ export type LineFilter = (args: {
fullStop: () => void;
}) => LineStream;
export type CharacterFilter = (args: {
chars: AsyncGenerator<string>;
prefix: string;
suffix: string;
filepath: string;
multiline: boolean;
}) => AsyncGenerator<string>;
function isBracketEnding(line: string): boolean {
return line
.trim()

View file

@ -1,70 +0,0 @@
##### Prompt #####
class Calculator {
constructor() {
this.result = 0;
}
add(number) {
this.result += number;
return this;
}
subtract(number) {
this.result -= number;
return this;
}
multiply(number) {
this.result *= number;
return this;
}
divide(number) {
if (number === 0) {
throw new Error("Cannot divide by zero");
}
this.result /= number;
return this;
}
<FIM>
getResult() {
return this.result;
}
reset() {
this.result = 0;
return this;
}
}
==========================================================================
==========================================================================
Completion:
getResult() {
return this.result;
}
reset() {
this.result = 0;
return this;
}
}
// Example usage:
const calculator = new Calculator();
calculator.add(5).subtract(3).multiply(2).divide(4);
console.log(calculator.getResult()); // Output: 2
calculator.reset().add(10).divide(2);
console.log(calculator.getResult()); // Output: 5
calculator.reset().add(8).multiply(0);
console.log(calculator.getResult()); // Output: 0
calculator.reset().add(6).divide(0); // Throws an error: Cannot divide by zero

View file

@ -0,0 +1,60 @@
##### Prompt #####
{
"active": true,
"department": "Product Development",
"location": {
"country": "USA",
"state": "California",
"city": "San BERNARDINO",
"coordinates": {
<FIM>
}
},
"employees": [
{
"name": "John Doe",
"age": 30,
"position": "Developer",
"skills": ["JavaScript", "React", "Node.js"],
"remote": false,
"salary": {
"currency": "USD",
"amount": 95000
}
},
{
"name": "Jane Smith",
"age": 25,
"position": "Designer",
"skills": ["Photoshop", "Illustrator"],
"remote": true,
"salary": {
"currency": "USD",
"amount": 70000
}
},
{
"name": "Emily Johnson",
"age": 35,
"position": "Manager",
"teamSize": 8,
"remote": true,
"skills": ["Leadership", "Project Management"],==========================================================================
==========================================================================
Completion:
"latitude": 34.10834,
"longitude": -117.28977
}
},
"employeeCount": 2,
"averageAge": 30,
"remoteFriendly": true,
"salaryRange": {
"min": 70000,
"max": 95000,
"currency": "USD"
},
"skills": {
"required": ["JavaScript", "React", "Node.js", "Leadership", "Project Management"],
"optional": ["Photoshop", "Illustrator"]

View file

@ -0,0 +1,128 @@
##### Prompt #####
}`,
},
{
description: "Should autocomplete Vue computed property",
filename: "UserComponent.vue",
input: `<template>
<div>
<p>User Full Name: {{ fullName }}</p>
</div>
</template>
<script>
export default {
data() {
return {
firstName: 'John',
lastName: 'Doe',
};
},
computed: {
fullName<|fim|>
},
};
</script>
`,
llmOutput: `() {
return this.firstName + ' ' + this.lastName;
}`,
expectedCompletion: `() {
return this.firstName + ' ' + this.lastName;
}`,
},
{
description: "Should autocomplete Vue method using props",
filename: "TodoItem.vue",
input: `<template>
<li>
<p>{{ title }}</p>
<button @click="completeTodo">Complete</button>
</li>
</template>
<script>
export default {
props: {
title: String,
completed: Boolean,
},
methods: {
completeTodo() {
<|fim|> = true;
}
},
};
</script>
`,
llmOutput: `this.completed`,
expectedCompletion: `this.completed`,
},
{
description: "Should autocomplete Svelte reactive statement",
filename: "Counter.svelte",
input: `
<script>
let count = 0;
$: <|fim|>
function handleClick() {
count += 1;
}
</script>
<button on:click={handleClick}>
Clicked {count} times
</button>
`,
llmOutput: `doubledCount = count * 2`,
expectedCompletion: `doubledCount = count * 2`,
},
{
description: "Should autocomplete Svelte component inside HTML",
filename: "NestedComponent.svelte",
input: `
<script>
import ChildComponent from './ChildComponent.svelte';
</script>
<main>
<h1>Hello Svelte</h1>
<ChildComponent <|fim|> />
</main>
`,
llmOutput: `name="World"`,
expectedCompletion: `name="World"`,
},
{
description: "Should handle autocomplete in Svelte each block",
filename: "List.svelte",
input: `
<script>
let items = ["Apple", "Banana", "Cherry"];
</script>
<ul>
{#each items as item}
<li>{item}</li>
{/each<|fim|>
</ul>
`,
llmOutput: `}`,
expectedCompletion: `}`,
},
<FIM>
];
==========================================================================
==========================================================================
Completion:
export default {
components: {
ChildComponent,
},

View file

@ -0,0 +1,20 @@
##### Prompt #####
{
"employees": [
{ "name": "John Doe", "age": 30, "position": "Developer" },
{ "name": "Jane Smith", "age": 25, "position": "Designer" },
{ "name": "Emily Johnson", "age": 35, "position": "Manager" }<FIM>
],
"active": true
}
==========================================================================
==========================================================================
Completion:
}
{
"employees": [
{ "name": "John Doe", "age": 30 },
{ "name": "Jane Smith", "age": 25 }

View file

@ -0,0 +1,29 @@
##### Prompt #####
class Calculator:
def __init__(self):
self.result = 0
def add(self, number):
self.result += number
return self
def divid<FIM>
def subtract(self, number):
self.result -= number
return self
def reset(self):
self.result = 0
return self
def get_result(self):
return self.result
==========================================================================
==========================================================================
Completion:
self.result /= number
return self

View file

@ -0,0 +1,41 @@
##### Prompt #####
class Calculator
attr_accessor :result
def initialize
@result = 0
end
def add(number)
@result += number
self
end
def subtract(number)
@result -= number
self
end
def power(ne<FIM>
def get_result
@result
end
def reset
@result = 0
self
end
end
calc = Calculator.new
calc.add(5).subtract(3)
puts "Result: #{calc.get_result}"
==========================================================================
==========================================================================
Completion:
@result ** number
self
end

View file

@ -0,0 +1,73 @@
##### Prompt #####
use std::io;
fn main() {
println!("Welcome to the Calculator!");
loop {
println!("Please enter an operator (+, -, *, /) or 'q' to quit:");
let operator = read_input();
if operator == "q" {
break;
}
println!("Please enter the first number:");
let num1 = read_input().parse::<f64>().unwrap();
println!("Please enter the second number:");
let num2 = read_input().parse::<f64>().unwrap();
let result = match operator.as_str() {
"+" => num1 + num2,
"-" => num1 - num2,
"*" => num1 * num2,
"/" => num1 / num2,
<FIM>
_ => {
println!("Invalid operator. Please try again.");
continue;
}
};
println!("Result: {}", result);
}
}
fn read_input() -> String {
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("Failed to read input");
input.trim().to_string()
}
==========================================================================
==========================================================================
Completion:
=> {
println!("Invalid operator. Please try again.");
continue;
}
};
println!("Result: {}", result);
}
println!("Goodbye!");
}
fn main2() {
println!("Welcome to the Calculator!");
loop {
println!("Please enter an operator (+, -, *, /) or 'q' to quit:");
let operator = read_input();
if operator == "q" {
break;
}
match operator.as_str() {
"+" | "-" | "*" | "/" => (),

View file

@ -1,53 +0,0 @@
##### Prompt #####
class Calculator {
constructor() {
this.result = 0;
}
add(number) {
this.result += number;
return this;
}
subtract(number) {
this.result -= number;
return this;
}
multiply(number) {
this.result *= number;
return this;
}
divide(number) {
if (number === 0) {
throw new Error("Cannot divide by zero");
}
<FIM>
this.result /= number;
return this;
}
getResult() {
return this.result;
}
reset() {
this.result = 0;
return this;
}
}
==========================================================================
==========================================================================
Completion:
this.result /= number;
return this;
}
}
module.exports = Calculator;
------------------------------------------------------------------------

View file

@ -172,6 +172,69 @@ public class Calculator {
expectedCompletion: ` - Subitem 2
- Subitem 3`,
},
{
description: "Should enforce bracket matching in JSON files",
filename: "test.json",
input: `{
"active": true,
"department": "Product Development",
"location": {
"country": "USA",
"state": "California",
"city": "San BERNARDINO",
"coordinates": {
<FIM>
}
},
"employees": [
{
"name": "John Doe",
"age": 30,
"position": "Developer",
"skills": ["JavaScript", "React", "Node.js"],
"remote": false,
"salary": {
"currency": "USD",
"amount": 95000
}
},
{
"name": "Jane Smith",
"age": 25,
"position": "Designer",
"skills": ["Photoshop", "Illustrator"],
"remote": true,
"salary": {
"currency": "USD",
"amount": 70000
}
},
{
"name": "Emily Johnson",
"age": 35,
"position": "Manager",
"teamSize": 8,
"remote": true,
"skills": ["Leadership", "Project Management"],`,
llmOutput: `"latitude": 34.10834,
"longitude": -117.28977
}
},
"employeeCount": 2,
"averageAge": 30,
"remoteFriendly": true,
"salaryRange": {
"min": 70000,
"max": 95000,
"currency": "USD"
},
"skills": {
"required": ["JavaScript", "React", "Node.js", "Leadership", "Project Management"],
"optional": ["Photoshop", "Illustrator"]`,
expectedCompletion: `"latitude": 34.10834,
"longitude": -117.28977
`,
},
];
export const TEST_CASES_WITHOUT_DIFF: AutocompleteFileringTestInput[] = [
@ -670,6 +733,36 @@ func main() {
llmOutput: `8.5)`,
expectedCompletion: `8.5)`,
},
{
description:
"Should autocomplete SQL script with employee and product tables",
filename: "database.sql",
input: `
CREATE TABLE employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
age INT NOT NULL,
position VARCHAR(100)
);
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
price DECIMAL(8,2) NOT NULL<FIM> '0.00',
quantity INT NOT NULL DEFAULT '0'
);
INSERT INTO employees (name, age, position) VALUES ('John Doe', 30, 'Developer');
INSERT INTO products (name, price, quantity) VALUES ('Apple', '1.99', '47');
SELECT * FROM products ORDER BY name DESC LIMIT 3;
SELECT * FROM products WHERE price > '0';
SELECT * FROM products WHERE quantity > '100';
SELECT * FROM employees WHERE age > 25;
`,
llmOutput: " DEFAULT",
expectedCompletion: " DEFAULT",
},
{
description:
"Should autocomplete SQL query with subquery and alias in SELECT clause",
@ -838,40 +931,6 @@ public class App {
llmOutput: `, { "id": 3, "name": "Charlie" }`,
expectedCompletion: `, { "id": 3, "name": "Charlie" }`,
},
{
description: "Should autocomplete nested JSON objects",
filename: "config.json",
input: `{
"server": {
"host": "localhost",
"port": 8080,
"features": {
"enableLogging": true,
"maxConnections": 100
<|fim|>
}
}`,
llmOutput: `,
"timeout": 5000
}`,
expectedCompletion: `,
"timeout": 5000
}`,
},
{
description: "Should autocomplete JSON object with missing bracket",
filename: "settings.json",
input: `{
"theme": "dark",
"language": "en"<|fim|>
`,
llmOutput: `,
"notifications": true
}`,
expectedCompletion: `,
"notifications": true
}`,
},
{
description: "Should autocomplete within a CSV record",
filename: "test.csv",

View file

@ -0,0 +1,64 @@
import React, { useState } from "react";
const AdvancedPage = () => {
const [isDarkMode, setIsDarkMode] = useState(false);
const [counter, setCounter] = useState(0);
const toggleDarkMode = () => {
setIsDarkMode((prevMode) => !prevMode);
};
return (
<div
className={`${isDarkMode ? "bg-gray-800 text-white" : "bg-white text-black"} min-h-screen p-4`}
>
<header className="mb-4 flex items-center justify-between border-b-2 pb-4">
<h1 className="text-3xl font-bold">Welcome to the Advanced Page</h1>
<button
className="rounded bg-blue-500 px-4 py-2 text-white"
onClick={toggleDarkMode}
>
Toggle Dark Mode
</button>
</header>
<main className="flex flex-col items-center">
<div className="mb-4">
<p className="text-xl">
Counter: <span className="font-bold">{counter}</span>
</p>
<button
className="mt-2 rounded bg-green-500 px-4 py-2 text-white"
onClick={() => setCounter(counter + 1)}
>
Increment
</button>
</div>
<div>
<p className="mb-2">Some other interactive elements:</p>
<input
type="text"
placeholder="Type something here..."
className="mb-2 rounded border p-2"
/>
<div>
<select className="rounded border p-2">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
</div>
</div>
</main>
<footer className="mt-4 border-t-2 pt-4">
<p className="text-center">
&copy; 2023 Advanced Page. All rights reserved.
</p>
</footer>
</div>
);
};
export default AdvancedPage;

View file

@ -1,15 +0,0 @@
import React from "react";
export const Button = ({
onClick,
children,
}: {
children: React.ReactNode;
onClick: () => void;
}) => {
return (
<button className="btn btn-primary" onClick={onClick}>
{children}
</button>
);
};

View file

@ -1,8 +1,83 @@
{
"active": true,
"department": "Product Development",
"location": {
"country": "USA",
"state": "California",
"city": "San Francisco",
"coordinates": {
"latitude": 37.7749,
"longitude": -122.4194
}
},
"employees": [
{ "name": "John Doe", "age": 30, "position": "Developer" },
{ "name": "Jane Smith", "age": 25, "position": "Designer" },
{ "name": "Emily Johnson", "age": 35, "position": "Manager" }
{
"name": "John Doe",
"age": 30,
"position": "Developer",
"skills": ["JavaScript", "React", "Node.js"],
"remote": false,
"salary": {
"currency": "USD",
"amount": 95000
}
},
{
"name": "Jane Smith",
"age": 25,
"position": "Designer",
"skills": ["Photoshop", "Illustrator"],
"remote": true,
"salary": {
"currency": "USD",
"amount": 70000
}
},
{
"name": "Emily Johnson",
"age": 35,
"position": "Manager",
"teamSize": 8,
"remote": true,
"skills": ["Leadership", "Project Management"],
"salary": {
"currency": "USD",
"amount": 120000
},
"contact": {
"email": "emily.johnson@company.com",
"phone": "+1-202-555-0163"
}
}
],
"active": true
"projects": [
{
"name": "Project Alpha",
"deadline": "2023-12-31",
"budget": 150000,
"teamMembers": ["John Doe", "Jane Smith"]
},
{
"name": "Project Beta",
"deadline": "2024-06-30",
"budget": 200000,
"teamMembers": ["Emily Johnson"]
}
],
"companyStats": {
"founded": 2010,
"annualRevenue": 2500000,
"clients": [
{
"name": "Client A",
"industry": "Technology",
"engagements": ["Consulting", "Development"]
},
{
"name": "Client B",
"industry": "Finance",
"engagements": ["Design"]
}
]
}
}

View file

@ -19,6 +19,11 @@
</header>
<div class="container">
<p>This is a sample paragraph.</p>
<ol>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ol>
</div>
</body>