repo_name stringlengths 1 62 | dataset stringclasses 1
value | lang stringclasses 11
values | pr_id int64 1 20.1k | owner stringlengths 2 34 | reviewer stringlengths 2 39 | diff_hunk stringlengths 15 262k | code_review_comment stringlengths 1 99.6k |
|---|---|---|---|---|---|---|---|
promptfoo | github_2023 | typescript | 669 | promptfoo | anthonyivn2 | @@ -20,13 +20,49 @@ import type {
EvaluateTestSuite,
ProviderOptions,
PromptFunction,
+ Assertion,
} from './types';
import { readPrompts } from './prompts';
export * from './types';
export { generateTable } from './table';
+export async function evaluateMetrics(
+ data: (string | { vars: Record<st... | would this still make evaluate() run the `callApi` function? |
promptfoo | github_2023 | typescript | 915 | promptfoo | underyx | @@ -73,96 +168,225 @@ interface IBedrockModel {
output: (responseJson: any) => any;
}
+function addConfigParam(
+ params: any,
+ key: string,
+ configValue: any,
+ envValue?: string | undefined,
+ defaultValue?: any,
+) {
+ if (configValue !== undefined || envValue !== undefined) { | this is missing a `|| defaultValue !== undefined`
|
promptfoo | github_2023 | others | 876 | promptfoo | typpo | @@ -10,9 +10,11 @@ concurrency:
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
- OPENAI_API_KEY: xxx
- AZURE_OPENAI_API_HOST: xxx
ANTHROPIC_API_KEY: xxx
+ AZURE_OPENAI_API_HOST: xxx
+ NEXT_PUBLIC_SUPABASE_ANON_KEY: xxx
+ NEXT_PUBLIC_SUPABASE_URL: https://placeholder.promptfoo.dev
+ O... | I prefer to preserve the original order, as the vast majority of people need to replace the OpenAI key more so than the other API keys. |
promptfoo | github_2023 | typescript | 830 | promptfoo | scottfavre | @@ -477,6 +486,31 @@ export class OpenAiChatCompletionProvider extends OpenAiGenericProvider {
(logProbObj: { token: string; logprob: number }) => logProbObj.logprob,
);
+ // Handle function tool callbacks
+ const functionCalls = message.function_call ? [message.function_call] || message.too... | ```suggestion
const functionCalls = message.function_call ? [message.function_call] : message.tool_calls;
``` |
promptfoo | github_2023 | typescript | 873 | promptfoo | typpo | @@ -209,32 +213,6 @@ function EvalOutputCell({
let text = typeof output.text === 'string' ? output.text : JSON.stringify(output.text);
let node: React.ReactNode | undefined;
- let chunks: string[] = [];
- let hasImageLightbox = false;
- if (text.startsWith('![')) {
- const imageUrlRegex = /^!\[.*?\]\((.*?... | We should preserve this "chunks" behavior - it's what parses out and displays failures nicely.
With split:
<img width="541" alt="image" src="https://github.com/promptfoo/promptfoo/assets/310310/0c996956-6fee-435e-a373-c9a1dea56465">
Without split:
<img width="535" alt="image" src="https://github.com/promptfoo/p... |
promptfoo | github_2023 | typescript | 862 | promptfoo | typpo | @@ -0,0 +1,202 @@
+import dedent from 'dedent';
+import invariant from 'tiny-invariant';
+import { OpenAiChatCompletionProvider } from '../providers/openai';
+import { getNunjucksEngine } from '../util';
+import { SYNTHESIS_MODEL } from './constants';
+import type { TestCase } from '../types';
+
+/**
+ * Generates a te... | We don't have to include `name` as a var, since it is placed directly in the prompt text by nunjucks |
promptfoo | github_2023 | typescript | 745 | promptfoo | mikkoh | @@ -49,7 +49,7 @@ import type {
} from './types';
import { generateTable } from './table';
import { createShareableUrl } from './share';
-import {filterTests} from './commands/eval/filterTests';
+import { filterTests } from './commands/eval/filterTests'; | Sorry about this.
Could add `bracketSpacing: true` to `.prettierrc.yaml` I use Prettier format on save. Surprised it didn't pick this up. |
promptfoo | github_2023 | typescript | 742 | promptfoo | typpo | @@ -585,9 +586,10 @@ async function main() {
);
}
- testSuite.tests = filterTests(testSuite.tests, {
+ testSuite.tests = await filterTests(testSuite, {
firstN: cmdObj.firstN,
pattern: cmdObj.pattern,
+ failing: cmdObj.failing, | I support this |
promptfoo | github_2023 | typescript | 742 | promptfoo | typpo | @@ -0,0 +1,26 @@
+import {TestSuite} from "../../types";
+import {readOutput, resultIsForTestCase} from "../../util";
+
+type Tests = NonNullable<TestSuite['tests']>;
+
+export async function filterFailingTests(testSuite: TestSuite, outputPath: string): Promise<Tests> {
+ if (!testSuite.tests) {
+ return [];
+ }
+... | Should be safe to remove this check :+1: |
promptfoo | github_2023 | typescript | 742 | promptfoo | typpo | @@ -1228,3 +1244,26 @@ export function getStandaloneEvals(): StandaloneEval[] {
});
return flatResults;
}
+
+export function providerToIdentifier(provider: TestCase['provider']): string | undefined { | Really appreciate you adding these helper functions. I'm aware that ApiProvider vs ProviderOptions and similar variations are some of the ugliest parts of the code :( |
promptfoo | github_2023 | typescript | 742 | promptfoo | typpo | @@ -552,8 +552,9 @@ async function main() {
'Run providers interactively, one at a time',
defaultConfig?.evaluateOptions?.interactiveProviders,
)
- .option('-n, --first-n <number>', 'Only run the first N tests')
- .option('--pattern <pattern>', 'Only run tests whose description matches the regu... | My selfish preference is to keep `-n` because it feels familiar, like `head -n` :). Open to other short forms but I don't think it's necessary. If we find ourselves getting tired of typing everything out let's add it separately.
I do version bumps manually - since we're pre-1.0 I've included breaking changes in mi... |
promptfoo | github_2023 | others | 728 | promptfoo | typpo | @@ -39,19 +39,20 @@ assert:
'pass': True,
'score': 0.5,
}
- else:
- return {
- 'pass': False,
- 'score': 0,
- }
+ return {
+ 'pass': False,
+ 'score': 0,
+ }
```
## Using test context
A `context` object is a... | Yeah, I think you're right on both counts |
promptfoo | github_2023 | typescript | 683 | promptfoo | typpo | @@ -523,9 +523,15 @@ export async function matchesAnswerRelevance(
const candidateQuestions: string[] = [];
for (let i = 0; i < 3; i++) {
// TODO(ian): Parallelize
+ const promptText = nunjucks.renderString(ANSWER_RELEVANCY_GENERATE['content'], | Looks like we can simplify `ANSWER_RELEVANCY_GENERATE` to just be a string |
promptfoo | github_2023 | typescript | 455 | promptfoo | typpo | @@ -0,0 +1,194 @@
+import logger from '../logger';
+import { fetchWithCache } from '../cache';
+
+import {
+ ApiProvider,
+ EnvOverrides,
+ ProviderResponse,
+ TokenUsage,
+} from '../types';
+import { REQUEST_TIMEOUT_MS, parseChatPrompt } from './shared';
+
+interface MistralChatCompletionOptions {
+ apiKey?: str... | I think this is ok for now if it's a common problem that everyone is working around. If it's more niche, then it would be better handled using the [`transform` testcase option](https://promptfoo.dev/docs/configuration/guide/#transforming-outputs) |
promptfoo | github_2023 | typescript | 350 | promptfoo | typpo | @@ -30,6 +30,8 @@ type OpenAiCompletionOptions = OpenAiSharedOptions & {
best_of?: number;
functions?: OpenAiFunction[];
function_call?: 'none' | 'auto' | { name: string };
+ tools?: OpenAiTool[];
+ tool_choice?: 'none' | 'auto' | { name: string }; | According to the [OpenAI docs](https://platform.openai.com/docs/api-reference/chat/create#chat-create-tools), should this be
```ts
{
// ...
tools_choice?: 'none' | 'auto' | { type: 'function'; function?: { name: string }}
}
```
|
promptfoo | github_2023 | typescript | 350 | promptfoo | typpo | @@ -8,6 +8,11 @@ export interface OpenAiFunction {
parameters: any;
}
+export interface OpenAiTool {
+ type: string;
+ function: any; | Maybe we can type this as
```ts
export interface OpenAiTool {
type: string;
function: OpenAiFunction;
}
``` |
promptfoo | github_2023 | typescript | 325 | promptfoo | typpo | @@ -170,6 +170,7 @@ export async function readConfigs(configPaths: string[]): Promise<UnifiedConfig>
(prev, curr) => ({ ...prev, ...curr.commandLineOptions }),
{},
),
+ sharing: configs.at(-1)?.sharing, | Would it make sense to do something like
```ts
sharing: !configs.some(config => config.sharing === false),
```
So that if _any_ config has sharing disabled, the merged config won't have sharing either? |
promptfoo | github_2023 | typescript | 296 | promptfoo | fabioxgn | @@ -101,7 +106,15 @@ export async function loadApiProvider(
config: options.config,
env,
};
- if (providerPath?.startsWith('exec:')) {
+ if (providerPath.startsWith('file://')) {
+ const filePath = providerPath.slice('file://'.length);
+ const yamlContent = yaml.load(fs.readFileSync(filePath, 'utf8... | Is this console.log intentional? |
promptfoo | github_2023 | typescript | 69 | promptfoo | typpo | @@ -137,6 +137,11 @@ async function main() {
});
await telemetry.send();
+ if (!defaultConfig.sharing) {
+ logger.error('Sharing is not enabled. Add `sharing: true` to your promptfooconfig.yaml');
+ process.exit(1);
+ }
+ | Rather than requiring the user to edit their config after they've explicitly run `promptfoo share`, it might be smoother to just always include a confirmation "Are you sure you want to create a public URL?"
Happy to add this separately if that saves you some trouble. |
promptfoo | github_2023 | typescript | 69 | promptfoo | typpo | @@ -246,6 +251,7 @@ async function main() {
prompts: cmdObj.prompts || fileConfig.prompts || defaultConfig.prompts,
providers: cmdObj.providers || fileConfig.providers || defaultConfig.providers,
tests: cmdObj.tests || cmdObj.vars || fileConfig.tests || defaultConfig.tests,
+ sharing: ... | nit - `PROMPTFOO_DISABLE_SHARING` for consistency with other envars, and let's check `fileConfig` too (this is used when the user explicitly sets a config with the `-c` option)
something like this -
```js
sharing: process.env.PROMPTFOO_DISABLE_SHARING === "1" ? false : (fileConfig.sharing ?? defaultConfig.sharing... |
promptfoo | github_2023 | typescript | 3,468 | promptfoo | ellipsis-dev[bot] | @@ -13,12 +13,25 @@ export function createTogetherAiProvider(
} = {},
): ApiProvider {
const splits = providerPath.split(':');
+
+ // Build the passthrough object with max_tokens if available
+ const existingPassthrough = (options.config as any)?.passthrough || {}; | Consider using proper optional chaining (e.g. `options.config?.passthrough`) instead of casting to any. This improves type-safety.
```suggestion
const existingPassthrough = options.config?.passthrough || {};
``` |
promptfoo | github_2023 | typescript | 3,468 | promptfoo | ellipsis-dev[bot] | @@ -13,13 +19,23 @@ export function createTogetherAiProvider(
} = {},
): ApiProvider {
const splits = providerPath.split(':');
+
+ // Get the configuration from options
+ const config = options.config?.config || {}; | The use of a nested property named `config` (i.e. `options.config?.config`) can be confusing. Consider renaming the inner config (e.g. to `params` or `togetherAiParams`) for clarity. |
promptfoo | github_2023 | typescript | 3,558 | promptfoo | ellipsis-dev[bot] | @@ -43,21 +45,29 @@ const ReportDownloadButton: React.FC<ReportDownloadButtonProps> = ({
const handlePdfDownload = async () => {
setIsDownloading(true);
handleClose();
+ setNavbarVisible(false);
- setTimeout(async () => {
- const element = document.documentElement;
- const canvas = await ... | The try/catch block around `setTimeout` won’t catch errors thrown inside its async callback. Consider wrapping the async function within `setTimeout` in its own try/catch (or using an await-based delay) to properly handle errors. |
promptfoo | github_2023 | typescript | 3,554 | promptfoo | mldangelo | @@ -129,7 +129,7 @@ export default function Navigation({
<NavSection>
<Logo />
<Dropdown />
- <NavLink href="/eval" label="Evals" />
+ <NavLink href="/evals" label="Evals" /> | Should think through the default behavior when we open promptfoo view and whether or want we want /eval to remain in the top nav. This may confuse people |
promptfoo | github_2023 | typescript | 3,554 | promptfoo | ellipsis-dev[bot] | @@ -73,10 +73,13 @@
<EvalSelectorDialog
open={dialogOpen}
onClose={handleCloseDialog}
- recentEvals={recentEvals}
- onRecentEvalSelected={handleEvalSelected}
+ onEvalSelected={(evalId) => {
+ handleEvalSelected(evalId);
+ setDialogOpen(false); | Remove redundant dialog closing; `handleEvalSelected` already calls `handleCloseDialog`.
```suggestion
``` |
promptfoo | github_2023 | typescript | 3,554 | promptfoo | ellipsis-dev[bot] | @@ -0,0 +1,177 @@
+import { useMemo, useEffect, useState } from 'react';
+import { callApi } from '@app/utils/api';
+import { Box, Typography } from '@mui/material';
+import {
+ DataGrid,
+ type GridColDef,
+ GridToolbarContainer,
+ GridToolbarColumnsButton,
+ GridToolbarFilterButton,
+ GridToolbarDensitySelector... | Consider syncing `rowSelectionModel` with changes in `focusedEvalId` via `useEffect` if it may update after mount. |
promptfoo | github_2023 | others | 3,554 | promptfoo | mldangelo | @@ -167,6 +167,7 @@
"@anthropic-ai/sdk": "^0.39.0",
"@apidevtools/json-schema-ref-parser": "^11.9.3",
"@googleapis/sheets": "^9.6.0",
+ "@mui/x-data-grid": "^7.28.2", | should be in src/app/package.json instead |
promptfoo | github_2023 | typescript | 3,550 | promptfoo | ellipsis-dev[bot] | @@ -0,0 +1,33 @@
+import React, { useEffect } from 'react';
+import { useTheme } from '@mui/material/styles';
+import Layout from '@theme/Layout';
+
+export default function ApiReference() {
+ const theme = useTheme();
+ useEffect(() => { | Add a cleanup function to remove the dynamically appended script when the component unmounts. |
promptfoo | github_2023 | others | 3,547 | promptfoo | ellipsis-dev[bot] | @@ -30,27 +33,39 @@ npx promptfoo@latest init --example redteam-multi-modal
# Navigate to the example directory
cd redteam-multi-modal
-# Install dependencies
-npm install sharp
+# Install dependencies for image and audio strategies
+npm install sharp # Image
+npm instsall node-gtts # Audio | Typo: 'instsall' should be 'install'.
```suggestion
npm install node-gtts # Audio
``` |
promptfoo | github_2023 | typescript | 3,533 | promptfoo | ellipsis-dev[bot] | @@ -172,12 +172,33 @@ export async function readStandaloneTestsFile(
feature: 'json tests file',
});
rows = yaml.load(fs.readFileSync(resolvedVarsPath, 'utf-8')) as unknown as any;
+ }
+ // Handle .jsonl files
+ else if (fileExtension === 'jsonl') {
+ telemetry.recordAndSendOnce('feature_used', {... | Consider wrapping the `JSON.parse` call in a `try/catch` so that if a line is malformed, a clear error message indicating the offending line (and its index) can be provided for debugging. |
promptfoo | github_2023 | others | 3,533 | promptfoo | ellipsis-dev[bot] | @@ -0,0 +1,2 @@
+{"vars": {"target_language": "French", "text": "Hello, world!" }, "assert": [{"type": "equals", "value": "Translate the following text to French: Hello, world!"}]}
+{"vars": {"target_language": "Spanish", "text": "Hello, world!" }, "assert": [{"type": "equals", "value": "Translate the following text to... | Best practice: add a newline at the end of the file. |
promptfoo | github_2023 | others | 3,542 | promptfoo | ellipsis-dev[bot] | @@ -0,0 +1,6 @@
+prompt,label
+"Tell me about {{topic}}","Basic Query"
+"Explain {{topic}} in simple terms as if I'm 5 years old","ELI5"
+"[{""role"":""system"",""content"":""You are a helpful assistant that provides academic-level explanations.""}, {""role"":""user"",""content"":""Provide a detailed academic explanati... | Trailing whitespace detected at the end of line 6. Please remove the extra whitespace.
```suggestion
"Create a bullet-point list of 5 interesting facts about {{topic}}","Facts"
``` |
promptfoo | github_2023 | others | 3,539 | promptfoo | ellipsis-dev[bot] | @@ -324,36 +326,56 @@ The SageMaker provider supports various model types to properly format requests
```yaml
# In provider ID
providers:
- - id: sagemaker:openai:my-endpoint
+ - id: sagemaker:huggingface:my-endpoint
# Or in config
providers:
- id: sagemaker:my-endpoint
config:
- modelType: 'opena... | Typo: In the Supported model types table, `'LLama-compatible interface models'` should be `'Llama-compatible interface models'` for consistency.
```suggestion
| `llama` | Llama-compatible interface models | Standard format |
``` |
promptfoo | github_2023 | typescript | 3,540 | promptfoo | ellipsis-dev[bot] | @@ -0,0 +1,106 @@
+import fs from 'fs';
+import yaml from 'js-yaml';
+import path from 'path';
+import { importModule } from '../esm';
+import logger from '../logger';
+import { runPython } from '../python/pythonUtils';
+import { isJavascriptFile } from './file';
+
+/**
+ * Loads the content from a file reference
+ * @... | Using `fs.readFileSync` inside an async function can be blocking. Consider using an async version where possible for better performance.
```suggestion
const content = await fs.promises.readFile(resolvedPath, 'utf8');
``` |
promptfoo | github_2023 | typescript | 3,540 | promptfoo | ellipsis-dev[bot] | @@ -45,23 +47,58 @@ export class PythonProvider implements ApiProvider {
return `python:${this.scriptPath}:${this.functionName || 'default'}`;
}
+ /**
+ * Process any file:// references in the configuration
+ * This should be called after initialization
+ * @returns A promise that resolves when all fil... | Consider whether swallowing errors during file reference processing is acceptable. Rethrow or propagate the error if unresolved file references should halt execution. |
promptfoo | github_2023 | typescript | 3,540 | promptfoo | ellipsis-dev[bot] | @@ -45,23 +47,53 @@ export class PythonProvider implements ApiProvider {
return `python:${this.scriptPath}:${this.functionName || 'default'}`;
}
+ /**
+ * Process any file:// references in the configuration
+ * This should be called after initialization
+ * @returns A promise that resolves when all fil... | Consider memoizing the promise in `initialize()` to avoid race conditions if multiple calls happen concurrently. This ensures `processConfigFileReferences` is only invoked once. |
promptfoo | github_2023 | others | 3,531 | promptfoo | ellipsis-dev[bot] | @@ -0,0 +1,204 @@
+---
+sidebar_label: How to red team foundation models
+sidebar_position: 10000
+---
+
+# How to red team foundation models
+
+LLM security starts at the foundation model level. Assessing the security of foundation models is the first step to building secure Generative AI applications. This baseline w... | YAML list formatting issue: The dash before `'id: openai:gpt-4o-mini'` is not properly indented. It should be nested under `'targets'` like the previous item. |
promptfoo | github_2023 | others | 3,531 | promptfoo | ellipsis-dev[bot] | @@ -0,0 +1,204 @@
+---
+sidebar_label: How to red team foundation models
+sidebar_position: 10000
+---
+
+# How to red team foundation models
+
+LLM security starts at the foundation model level. Assessing the security of foundation models is the first step to building secure Generative AI applications. This baseline w... | Update button instruction language: change 'Select on' to 'Click on' and 'You will prompted' to 'You will be prompted'.
```suggestion
Click on the "New Config" button to create a new scan. You will be prompted to either create a new config or use an existing YAML file. Click on "New Config" and then choose the target t... |
promptfoo | github_2023 | others | 3,531 | promptfoo | typpo | @@ -0,0 +1,204 @@
+---
+sidebar_label: How to red team foundation models | nit: would name this `foundation-models` for SEO |
promptfoo | github_2023 | typescript | 3,517 | promptfoo | ellipsis-dev[bot] | @@ -566,6 +567,17 @@ export const providerMap: ProviderFactory[] = [
});
},
},
+ {
+ test: (providerPath: string) => providerPath.startsWith('litellm:'),
+ create: async (
+ providerPath: string,
+ providerOptions: ProviderOptions,
+ context: LoadApiProviderContext,
+ ) => {
+ ... | Consider validating that the `providerPath` contains a model name. Splitting on `:` might return undefined if the format is incorrect. Adding an invariant check would improve robustness.
```suggestion
const modelName = providerPath.split(':')[1] || (() => { throw new Error('Invalid providerPath format: missing mo... |
promptfoo | github_2023 | typescript | 3,494 | promptfoo | mldangelo | @@ -26,6 +26,9 @@ export const STRATEGY_PROBE_MULTIPLIER: Record<Strategy, number> = {
'best-of-n': 1,
pandamonium: 5,
hex: 1,
+ audio: 1, | nit, can you sort these? |
promptfoo | github_2023 | typescript | 3,494 | promptfoo | ellipsis-dev[bot] | @@ -582,9 +582,8 @@ export const ADDITIONAL_STRATEGIES = [
] as const;
export type AdditionalStrategy = (typeof ADDITIONAL_STRATEGIES)[number];
-export const ALL_STRATEGIES = [
- ...['default', ...DEFAULT_STRATEGIES, ...ADDITIONAL_STRATEGIES].sort(),
-] as const;
+const _ALL_STRATEGIES = ['default', ...DEFAULT_STR... | Sorting `_ALL_STRATEGIES` loses the literal types provided by `as const`. This turns `ALL_STRATEGIES` into a `string[]` rather than a readonly tuple of literals. Consider either not sorting or using a type-safe sort that preserves literal types.
```suggestion
export const ALL_STRATEGIES = [..._ALL_STRATEGIES];
``` |
promptfoo | github_2023 | typescript | 3,486 | promptfoo | ellipsis-dev[bot] | @@ -13,17 +13,16 @@ export function handleRougeScore({
const fnName = baseType[baseType.length - 1] as 'n' | 'l' | 's';
const rougeMethod = rouge[fnName];
const score = rougeMethod(outputString, renderedValue, {});
- const pass = score >= (assertion.threshold || 0.75) != inverse;
+ const threshold = assertio... | Consider adding explicit parentheses to clarify the evaluation order in `score >= threshold != inverse` (e.g. `((score >= threshold) != inverse)`) for better clarity.
```suggestion
const pass = ((score >= threshold) != inverse);
``` |
promptfoo | github_2023 | typescript | 3,478 | promptfoo | ellipsis-dev[bot] | @@ -0,0 +1,253 @@
+import { fetchWithProxy } from '../../../src/fetch';
+import { matchesLlmRubric } from '../../../src/matchers';
+import { PlinyGrader, PlinyPlugin, PLUGIN_ID } from '../../../src/redteam/plugins/pliny';
+import { isBasicRefusal, isEmptyResponse } from '../../../src/redteam/util';
+import type { ApiPr... | Avoid using the non-null assertion operator. Instead, add a check to ensure metadata exists.
```suggestion
if (mockTest.metadata) mockTest.metadata.entities = ['Entity1', 'Entity2'];
``` |
promptfoo | github_2023 | typescript | 3,478 | promptfoo | typpo | @@ -73,6 +74,59 @@ export class PlinyPlugin extends RedteamPluginBase {
[this.injectVar]: ' ' + text,
},
assert: this.getAssertions(text),
+ metadata: {
+ // Store the original text separately in metadata
+ jailbreakContent: text, | Is this actually used anywhere? |
promptfoo | github_2023 | others | 3,485 | promptfoo | mldangelo | @@ -6,6 +6,7 @@ You can use it by specifying one of the [available models](https://ai.google.dev
## Available Models
+- `google:gemini-2.5-pro-exp-03-25` - Latest thinking model, designed to tackle increasingly complex problems with enhanced reasoning capabilities.
- `google:gemini-2.0-flash-exp` - Latest multimo... | ```suggestion
- `google:gemini-2.0-flash-exp` - Multimodal model with next generation features
``` |
promptfoo | github_2023 | typescript | 3,476 | promptfoo | ellipsis-dev[bot] | @@ -106,4 +106,73 @@ describe('Entities Extractor', () => {
expect(result).toEqual([]);
});
+
+ it('should ignore Nunjucks template variables in double curly braces', async () => {
+ process.env.PROMPTFOO_DISABLE_REDTEAM_REMOTE_GENERATION = 'true';
+ jest.mocked(provider.callApi).mockResolvedValue({
+ ... | Update comment to reflect that filtering of template variables is now implemented, as the comment suggests it isn’t yet fixed.
```suggestion
// Our extraction now filters out template variables and returns real entities
``` |
promptfoo | github_2023 | others | 3,477 | promptfoo | mldangelo | @@ -54,23 +54,25 @@ First, install [Node 18 or later](https://nodejs.org/en/download/package-manager
Then create a new project for your red teaming needs:
```sh
-npx promptfoo@latest redteam init my-redteam-project
-cd my-redteam-project
+npx promptfoo@latest redteam init my-redteam-project --no-gui
```
-The `in... | NICE! |
promptfoo | github_2023 | others | 3,474 | promptfoo | mldangelo | @@ -1,13 +1,35 @@
-This example shows how you can use promptfoo to generate a side-by-side eval of multiple prompts to compare gpt-4o and gpt-4o-mini outputs.
+# gpt-4o-vs-4o-mini (Comparing GPT-4o and GPT-4o-Mini)
-Configure in `promptfooconfig.yaml`. Run with:
+## Quick Start
+1. Initialize this example by runnin... | good except they should just run `promptfoo view`. the output.html file -> browser is old and barely supported |
promptfoo | github_2023 | typescript | 3,473 | promptfoo | ellipsis-dev[bot] | @@ -37,7 +37,7 @@ const AboutPageContent = () => {
<Box mb={8}>
<Grid container spacing={4}>
- <Grid item xs={12} md={6}>
+ <Grid size={{ xs: 12, md: 6 }}> | Consider using Grid2’s breakpoint props directly (e.g. `xs={12} md={6}`) instead of wrapping them in a `size` object. This follows the standard MUI Grid2 API.
```suggestion
<Grid xs={12} md={6}>
``` |
svg-to-compose | github_2023 | others | 123 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,29 @@
+package dev.tonholo.s2c.lexer.css.token.consumer
+
+import dev.tonholo.s2c.lexer.Token
+import dev.tonholo.s2c.lexer.TokenIterator
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+
+internal class FunctionTokenConsumer(
+ iterator: TokenIterator<CssTokenKind>,
+) : TokenConsumer(iterator) {
+ ove... | _:warning: Potential issue_
**Function name validation is too restrictive.**
The current validation only allows letters and hyphens, but CSS function names can contain numbers and underscores. For example, `scale3d()` and `my_function()` are valid CSS function names.
Apply this diff to fix the validation:
```diff
-... |
svg-to-compose | github_2023 | others | 123 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,29 @@
+package dev.tonholo.s2c.lexer.css.token.consumer
+
+import dev.tonholo.s2c.lexer.Token
+import dev.tonholo.s2c.lexer.TokenIterator
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+
+internal class FunctionTokenConsumer(
+ iterator: TokenIterator<CssTokenKind>,
+) : TokenConsumer(iterator) {
+ ove... | _:warning: Potential issue_
**Add EOF and whitespace handling.**
The current implementation has two issues:
1. No handling of EOF before open parenthesis.
2. No handling of whitespace between function name and open parenthesis.
Apply this diff to fix both issues:
```diff
while (iterator.hasNext()) {
val char ... |
svg-to-compose | github_2023 | others | 123 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,29 @@
+package dev.tonholo.s2c.lexer.css.token.consumer
+
+import dev.tonholo.s2c.lexer.Token
+import dev.tonholo.s2c.lexer.TokenIterator
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+
+internal class FunctionTokenConsumer(
+ iterator: TokenIterator<CssTokenKind>,
+) : TokenConsumer(iterator) {
+ ove... | _:warning: Potential issue_
**Add missing edge case handling.**
The current implementation needs improvements to handle several edge cases:
1. Empty function names
2. EOF before open parenthesis
3. Whitespace between function name and open parenthesis
Apply this diff to add the missing validations:
```diff
overrid... |
svg-to-compose | github_2023 | others | 111 | rafaeltonholo | coderabbitai[bot] | @@ -254,16 +254,16 @@ sealed class ImageParser(
*
* The function accepts a [FileManager] parameter for file management and
* then employs it in the creation of specific parser objects:
- * SVG ([SvgParser]) and Android Vector ([AndroidVectorParser]). Upon populating
+ * SVG ([SvgImageParser]) ... | _:warning: Potential issue_
**Fix outdated documentation mentioning singleton.**
The documentation still refers to returning a "singleton instance" which contradicts the new transient instance approach implemented in this PR.
```diff
- Upon populating the parsers object, the method returns the singleton instance of ... |
svg-to-compose | github_2023 | others | 107 | rafaeltonholo | coderabbitai[bot] | @@ -169,7 +169,7 @@ private fun SvgCircleNode.createDashedCircle(minified: Boolean): ImageVectorNode
minified = minified,
override = ImageVectorNode.Path.Params(
fill = fillBrush(nodes),
- fillAlpha = fillOpacity,
... | _:warning: Potential issue_
**Inconsistent opacity fallback implementation**
While the opacity fallback is correctly implemented for the fill path at line 172, there's an inconsistency in the dash path at line 187 where `strokeOpacity` is used without the fallback mechanism. This could lead to unexpected rendering wh... |
svg-to-compose | github_2023 | others | 107 | rafaeltonholo | coderabbitai[bot] | @@ -19,8 +19,8 @@ private fun main() {
AppConfig.debug = true
AppConfig.stackTrace = true
AppConfig.silent = false
- val suffix = "101"
- val (pkg, path, output) = SampleFile.Svg.GithubIssue(
+ val suffix = "css/flower.svg"
+ val (pkg, path, output) = SampleFile.Svg.File( | _:bulb: Codebase verification_
**Consider testing with more complex gradient scenarios**
The current test uses `flower.svg` which only contains a simple radial gradient with two color stops. Given that the PR addresses gradient viewport translation fixes, it would be beneficial to test with more complex gradient scen... |
svg-to-compose | github_2023 | others | 107 | rafaeltonholo | coderabbitai[bot] | @@ -8,7 +8,7 @@ import kotlin.jvm.JvmInline
@JvmInline
value class SvgColor private constructor(val value: String) {
companion object {
- val Default = SvgColor("#FF000000")
+ val Default = SvgColor("Color.Transparent") | _:warning: Potential issue_
**Update documentation to reflect the new default color.**
The documentation for `orDefault()` extension function states it returns "black color", but the default is now transparent. Please update the documentation to maintain consistency.
<!-- This is an auto-generated comment by CodeRab... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,44 @@
+package dev.tonholo.s2c.parser.ast.css.selectors
+
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+import dev.tonholo.s2c.parser.ast.css.CssCombinator
+import dev.tonholo.s2c.parser.ast.css.CssComponent
+import dev.tonholo.s2c.parser.ast.css.CssRootNode
+import dev.tonholo.s2c.parser.ast.css.terminalT... | _:bulb: Codebase verification_
**Missing test coverage for CSS selector parsing**
Based on the verification results, there are several concerns:
- No dedicated test cases for `AggregateSelectorParser` functionality
- Existing CSS tests only cover basic class rules
- Missing test cases for complex selector combination... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,372 @@
+package dev.tonholo.s2c.parser.ast.css.elements
+
+import dev.tonholo.s2c.lexer.Token
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+import dev.tonholo.s2c.parser.ast.css.CssRootNode
+import dev.tonholo.s2c.parser.ast.css.PropertyValue
+import dev.tonholo.s2c.parser.ast.iterator.AstParserIterator
+
... | _:warning: Potential issue_
**Ensure complete parsing of hex color values**
The `parseHexColorValue` method currently captures only a single hex digit after the '#' token. This may not correctly parse full hex color values like `#FF5733`. Modify the method to collect all consecutive hex digits to capture the entire h... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,80 @@
+package dev.tonholo.s2c.parser.ast.css
+
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+import dev.tonholo.s2c.parser.ast.Element
+
+sealed interface CssElement : Element
+
+data class CssRootNode(
+ val rules: List<CssRule>,
+) : CssElement
+
+sealed interface CssRule : CssElement {
+ val comp... | _:warning: Potential issue_
**Rename data classes `String` and `Number` to avoid naming conflicts**
Using class names that match Kotlin standard classes (`String`, `Number`) can lead to confusion and potential issues with name resolution. Consider renaming them for clarity.
Apply this diff to rename the data class... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,94 @@
+package dev.tonholo.s2c.parser.ast.css.elements
+
+import dev.tonholo.s2c.parser.ast.css.CssComponent
+import dev.tonholo.s2c.parser.ast.css.CssComponentType
+import dev.tonholo.s2c.parser.ast.css.CssQualifiedRule
+
+data class CssSpecificity(
+ val a: Int = 0,
+ val b: Int = 0,
+ val c: Int ... | _:warning: Potential issue_
**Prevent potential exception when computing specificity with `maxOf` on an empty collection**
Using `.maxOf { it }` on an empty collection will throw a `NoSuchElementException`. To safely handle empty parameter lists in pseudo-classes, use `.maxOfOrNull { it } ?: CssSpecificity()`.
App... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,481 @@
+package dev.tonholo.s2c.lexer.css
+
+import dev.tonholo.s2c.lexer.Token
+import kotlin.test.Test
+import kotlin.test.assertEquals
+
+class CssLexerTest {
+ @Test
+ fun `create tokens for a class css rule`() {
+ val input = """
+ |.my-rule {
+ | background: #f0f;
... | _:hammer_and_wrench: Refactor suggestion_
**Add test cases for error handling.**
The test suite thoroughly covers valid CSS constructs but lacks tests for malformed input.
Add test cases for:
1. Invalid CSS syntax
2. Unclosed strings
3. Invalid escape sequences
4. Malformed media queries
Example:
```kotlin
@Test
fu... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,1075 @@
+package dev.tonholo.s2c.parser.ast.css
+
+import dev.tonholo.s2c.lexer.Token
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+import kotlin.test.Test
+import kotlin.test.assertContains
+import kotlin.test.assertEquals
+import kotlin.test.assertFailsWith
+import kotlin.test.assertNotNull
+
+class CssA... | _:hammer_and_wrench: Refactor suggestion_
**Enhance the assert helper method for better error messages.**
The current assert method makes it hard to identify what exactly failed in the AST comparison.
Consider enhancing the assert method:
```kotlin
private fun assert(
content: String,
tokens: List<Token<out... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,1075 @@
+package dev.tonholo.s2c.parser.ast.css
+
+import dev.tonholo.s2c.lexer.Token
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+import kotlin.test.Test
+import kotlin.test.assertContains
+import kotlin.test.assertEquals
+import kotlin.test.assertFailsWith
+import kotlin.test.assertNotNull
+
+class CssA... | _:hammer_and_wrench: Refactor suggestion_
**Add more test cases for error handling.**
The error handling test is good but could be expanded.
Add more test cases for:
1. Invalid CSS properties
2. Malformed selectors
3. Invalid `@media` queries
4. CSS custom properties
5. Nested rules errors
Example:
``... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -13,8 +13,18 @@ import dev.tonholo.s2c.domain.xml.XmlNode
import dev.tonholo.s2c.domain.xml.XmlParentNode
import dev.tonholo.s2c.domain.xml.XmlRootNode
+/**
+ * Represents a node in the SVG tree.
+ */
sealed interface SvgNode : XmlNode {
+ /**
+ * The transform attribute of the node.
+ */
val tr... | _:warning: Potential issue_
**Fix potential infinite recursion in `normalizedId` extension function**
The extension function `fun String.normalizedId()` within `SvgNode` calls itself recursively, which can lead to a `StackOverflowError`. This occurs because, within the `with(SvgNode)` block, calling `normalizedId()` ... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,259 @@
+package dev.tonholo.s2c.domain.svg
+
+import dev.tonholo.s2c.domain.delegate.attribute
+import dev.tonholo.s2c.domain.svg.SvgNode.Companion.ATTR_HEIGHT
+import dev.tonholo.s2c.domain.svg.SvgNode.Companion.ATTR_TRANSFORM
+import dev.tonholo.s2c.domain.svg.SvgNode.Companion.ATTR_VIEW_BOX
+import dev.to... | _:warning: Potential issue_
**Preserve existing `transform` attributes when applying viewport offset**
In the `transform` property, if `viewportX` or `viewportY` is not zero, the code overwrites any existing `transform` attribute with a translation. This means any transformations specified in the SVG root node will b... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,144 @@
+package dev.tonholo.s2c.domain.svg
+
+import app.cash.burst.Burst
+import app.cash.burst.burstValues
+import dev.tonholo.s2c.domain.xml.XmlRootNode
+import kotlin.test.Test
+import kotlin.test.assertContentEquals
+import kotlin.test.assertEquals
+
+class SvgViewBoxTest {
+ @Test
+ @Burst
+ f... | _:warning: Potential issue_
**Test case appears to be identical to the missing viewBox test.**
The test case for incomplete viewBox is exactly the same as the missing viewBox test, but it doesn't actually test an incomplete viewBox scenario. The test should include a malformed viewBox attribute to properly test the h... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -14,6 +14,9 @@ plugins {
kotlin {
useNative()
useJvm()
+ compilerOptions {
+ freeCompilerArgs.add("-Xwhen-guards")
+ } | _:bulb: Codebase verification_
**Experimental feature enabled without proper documentation**
The `-Xwhen-guards` compiler flag is being added alongside other experimental features in the project:
- The plugin module uses `-Xcontext-receivers`
- The buildSrc uses `-Xcontext-receivers` and experimental Gradle API opt-i... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,49 @@
+package dev.tonholo.s2c.parser.ast.css.syntax.node
+
+import dev.tonholo.s2c.extensions.prependIndent
+import dev.tonholo.s2c.parser.ast.Element
+
+/**
+ * The base interface for all CSS nodes.
+ */
+sealed interface CssNode : Element {
+ val location: CssLocation
+ fun toString(indent: Int = 0)... | _:warning: Potential issue_
**Review the inheritance hierarchy.**
The `CssStatementNode` currently extends `CssComponentValueNode`, but according to CSS specifications, statements (like rulesets and at-rules) are not component values. Consider having both interfaces extend `CssNode` directly instead.
```diff
-sealed... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -1,23 +1,48 @@
package dev.tonholo.s2c.extensions
import kotlin.math.max
-import kotlin.math.roundToInt
private const val PERCENT = 100f
+/**
+ * Replaces dividers in the string with empty strings and capitalizes the following letter.
+ *
+ * Dividers are considered to be any of the following characters: '_... | _:bulb: Codebase verification_
**Update usages of deprecated `indented` function in multiple files**
The deprecated `indented` function is actively used across several files in the codebase:
- `ComposeBrush.kt`: Multiple usages for formatting brush-related code generation
- `PathNodes.kt`: Used for path node indenta... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,68 @@
+package dev.tonholo.s2c.lexer.css.token.consumer
+
+import dev.tonholo.s2c.lexer.Token
+import dev.tonholo.s2c.lexer.TokenIterator
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+
+internal class UrlTokenConsumer(
+ iterator: TokenIterator<CssTokenKind>,
+) : TokenConsumer(iterator) {
+ override... | _:warning: Potential issue_
**Add bounds checking to whitespace consumption**
The whitespace consumption loop should check for iterator bounds to prevent potential infinite loops.
```diff
// § 4.3.6. Consume as much whitespace as possible.
var char = iterator.peek(contentOffset)
- while (cha... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,68 @@
+package dev.tonholo.s2c.lexer.css.token.consumer
+
+import dev.tonholo.s2c.lexer.Token
+import dev.tonholo.s2c.lexer.TokenIterator
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+
+internal class UrlTokenConsumer(
+ iterator: TokenIterator<CssTokenKind>,
+) : TokenConsumer(iterator) {
+ override... | _:warning: Potential issue_
**Enhance URL validation according to CSS spec**
The URL consumption is missing several key validations:
1. Handling of escape sequences
2. Detection of invalid URL characters
3. Proper bad URL state handling
Consider implementing the following validation:
```diff
while (iterat... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,72 @@
+package dev.tonholo.s2c.parser.ast.css.syntax
+
+import dev.tonholo.s2c.lexer.Token
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+import dev.tonholo.s2c.parser.ast.iterator.AstParserIterator
+
+/**
+ * An iterator for parsing CSS tokens.
+ *
+ * This iterator wraps a list of CSS tokens and provides ... | _:warning: Potential issue_
**Add bounds checking to prevent negative offset**
The `rewind` method could set `offset` to a negative value, potentially causing `IndexOutOfBoundsException` in subsequent operations.
```diff
override fun rewind(steps: Int) {
- offset -= steps
+ offset = (offset - steps).coerceAtL... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,72 @@
+package dev.tonholo.s2c.parser.ast.css.syntax
+
+import dev.tonholo.s2c.lexer.Token
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+import dev.tonholo.s2c.parser.ast.iterator.AstParserIterator
+
+/**
+ * An iterator for parsing CSS tokens.
+ *
+ * This iterator wraps a list of CSS tokens and provides ... | _:hammer_and_wrench: Refactor suggestion_
**Improve readability of the trim function**
The whitespace handling logic is complex and could benefit from several improvements:
1. Extract the whitespace significance check into a separate function
2. Use more descriptive variable names
3. Add detailed comments explaining ... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,75 @@
+package dev.tonholo.s2c.parser.ast.css.consumer
+
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+import dev.tonholo.s2c.parser.ast.css.CssCombinator
+import dev.tonholo.s2c.parser.ast.css.syntax.node.CssLocation
+import dev.tonholo.s2c.parser.ast.css.syntax.node.Selector
+import dev.tonholo.s2c.parse... | _:warning: Potential issue_
**Possible `NoSuchElementException` when `selectors` list is empty**
In the `return` statement, `selectors.last()` is called without checking if `selectors` is not empty. If `selectors` is empty, this will result in a `NoSuchElementException`.
Consider adding a check or handling the cas... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,54 @@
+package dev.tonholo.s2c.parser.ast.css.syntax.node
+
+import dev.tonholo.s2c.extensions.prependIndent
+
+/**
+ * Represents the prelude of a [Rule], which can be either
+ * a selector list or an at-rule prelude.
+ *
+ * @param T The type of component value nodes within the prelude.
+ */
+sealed interf... | _:hammer_and_wrench: Refactor suggestion_
**Reduce code duplication in toString() implementations.**
The toString() implementation is identical between Selector and AtRule classes. Consider extracting this to a shared utility function.
```diff
+ private companion object {
+ private fun componentToString(
+... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,54 @@
+package dev.tonholo.s2c.parser.ast.css.syntax.node
+
+import dev.tonholo.s2c.extensions.prependIndent
+
+/**
+ * Represents the prelude of a [Rule], which can be either
+ * a selector list or an at-rule prelude.
+ *
+ * @param T The type of component value nodes within the prelude.
+ */
+sealed interf... | _:bulb: Codebase verification_
**Add unit tests for the Prelude implementations in the CSS syntax package**
Based on the codebase analysis, I can see that CSS-related tests are organized under `svg-to-compose/src/commonTest/kotlin/dev/tonholo/s2c/parser/ast/css/`. The project follows a consistent testing pattern with... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,163 @@
+package dev.tonholo.s2c.parser.ast.css.syntax
+
+import dev.tonholo.s2c.extensions.prependIndent
+import dev.tonholo.s2c.lexer.Token
+import dev.tonholo.s2c.lexer.TokenKind
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+import dev.tonholo.s2c.parser.ast.iterator.AstParserIterator
+import kotlin.cont... | _:warning: Potential issue_
**Ensure safe index calculations in message formatting**
In the `message` property, calculations for `prev`, `next`, and `indent` could potentially result in negative values, leading to exceptions when used in substring and repeat operations. Verify that these calculations handle edge case... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,58 @@
+package dev.tonholo.s2c.lexer.css.token.consumer
+
+import dev.tonholo.s2c.extensions.EMPTY
+import dev.tonholo.s2c.lexer.Token
+import dev.tonholo.s2c.lexer.TokenIterator
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+
+internal class HashTokenConsumer(
+ iterator: TokenIterator<CssTokenKind>,
+)... | _:warning: Potential issue_
**Fix type mismatch in condition**
At line 26, there's a comparison between a `Char` and `CssTokenKind`, which are incompatible types. The `peek` method returns a `Char`, but `CssTokenKind.Colon` is an enum value.
Suggested fix:
```diff
-if (iterator.peek(backwardLookupOffset) in CssTo... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,58 @@
+package dev.tonholo.s2c.lexer.css.token.consumer
+
+import dev.tonholo.s2c.extensions.EMPTY
+import dev.tonholo.s2c.lexer.Token
+import dev.tonholo.s2c.lexer.TokenIterator
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+
+internal class HashTokenConsumer(
+ iterator: TokenIterator<CssTokenKind>,
+)... | _:warning: Potential issue_
**Simplify and correct the backward lookup logic**
The backward lookup loop can be simplified and corrected for clarity and correctness. The current condition inside the loop may not function as intended due to redundant or contradictory checks.
Suggested fix:
```diff
var backwardLook... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,54 @@
+package dev.tonholo.s2c.lexer.css
+
+import dev.tonholo.s2c.lexer.Token
+import dev.tonholo.s2c.lexer.TokenIterator
+import dev.tonholo.s2c.lexer.Tokenizer
+import dev.tonholo.s2c.lexer.css.token.consumer.AtKeywordTokenConsumer
+import dev.tonholo.s2c.lexer.css.token.consumer.DirectTokenConsumer
+impo... | _:warning: Potential issue_
**Handle unsupported token kinds gracefully**
In the tokenization process, if none of the consumers accept a token kind, it could throw a `NoSuchElementException`.
Consider adding a fallback or error handling to manage unsupported token kinds:
```kotlin
val consumer = consumers.firstOr... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,67 @@
+package dev.tonholo.s2c.parser.ast.css.consumer
+
+import dev.tonholo.s2c.lexer.Token
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+import dev.tonholo.s2c.parser.ast.css.syntax.node.CssLocation
+import dev.tonholo.s2c.parser.ast.css.syntax.node.Declaration
+import dev.tonholo.s2c.parser.ast.css.synt... | _:warning: Potential issue_
**Infinite loop risk due to unhandled tokens**
The `while` loop may result in an infinite loop if none of the conditions match and the iterator doesn't advance.
Ensure the iterator advances in each loop iteration to prevent infinite loops:
```kotlin
while (iterator.hasNext()) {
val... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,102 @@
+package dev.tonholo.s2c.parser.ast.css.syntax.node
+
+/**
+ * A CSS property value.
+ */
+sealed interface Value : CssComponentValueNode {
+ /**
+ * Represents a color value.
+ */
+ data class Color(
+ override val location: CssLocation,
+ val value: kotlin.String,
+ ) ... | _:hammer_and_wrench: Refactor suggestion_
**Avoid using names that collide with Kotlin's built-in types**
Defining a data class named `String` can cause confusion and requires fully qualifying `kotlin.String` throughout the code. Consider renaming the data class `String` to `StringValue` or similar to improve clarity... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,102 @@
+package dev.tonholo.s2c.parser.ast.css.syntax.node
+
+/**
+ * A CSS property value.
+ */
+sealed interface Value : CssComponentValueNode {
+ /**
+ * Represents a color value.
+ */
+ data class Color(
+ override val location: CssLocation,
+ val value: kotlin.String,
+ ) ... | _:hammer_and_wrench: Refactor suggestion_
**Avoid using names that collide with Kotlin's built-in types**
Similarly, using `Number` as a data class name can lead to confusion and necessitates fully qualifying `kotlin.String`. Renaming the data class `Number` to `NumberValue` would enhance clarity and prevent potentia... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,112 @@
+package dev.tonholo.s2c.lexer
+
+import dev.tonholo.s2c.extensions.EMPTY
+
+/**
+ * An iterator for tokens.
+ *
+ * It provides methods to navigate and analyze the input string.
+ *
+ * @param T The type of token kind this iterator produces.
+ */
+internal abstract class TokenIterator<out T : TokenKi... | _:warning: Potential issue_
**Potential off-by-one error in `next()` method**
The `next()` method increments `offset` before accessing `content`, which might skip the first character and cause unintended behavior. Consider incrementing `offset` after accessing `content` to ensure correct iteration over the characters... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,132 @@
+package dev.tonholo.s2c.parser.ast.css.consumer
+
+import dev.tonholo.s2c.lexer.Token
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+import dev.tonholo.s2c.parser.ast.css.CssCombinator
+import dev.tonholo.s2c.parser.ast.css.syntax.node.CssLocation
+import dev.tonholo.s2c.parser.ast.css.syntax.node.S... | _:warning: Potential issue_
**Prevent potential infinite loop in 'buildParameters' method**
In the `buildParameters` method, if `consume(iterator)` does not consume any tokens, the `while` loop may become infinite. Ensure that `consume(iterator)` advances the iterator for every iteration, and consider adding safety c... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,132 @@
+package dev.tonholo.s2c.parser.ast.css.consumer
+
+import dev.tonholo.s2c.lexer.Token
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+import dev.tonholo.s2c.parser.ast.css.CssCombinator
+import dev.tonholo.s2c.parser.ast.css.syntax.node.CssLocation
+import dev.tonholo.s2c.parser.ast.css.syntax.node.S... | _:warning: Potential issue_
**Undefined variable: 'selectorTokens'**
The variable `selectorTokens` used in `iterator.expectToken(selectorTokens)` is not defined within the scope of this class or its imports. This will result in a compilation error.
Apply this diff to define `selectorTokens` or import it if it's de... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,262 @@
+package dev.tonholo.s2c.parser.ast.css.consumer
+
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+import dev.tonholo.s2c.parser.ast.css.syntax.node.CssLocation
+import dev.tonholo.s2c.parser.ast.css.syntax.node.Value
+import dev.tonholo.s2c.parser.ast.css.syntax.parserError
+
+private val colorFuncti... | _:hammer_and_wrench: Refactor suggestion_
**Improve unit extraction in 'parseDimensionToken'**
The current method of extracting the unit using `takeLastWhile { char.isLetter() }` may not handle all valid CSS units, especially those containing non-letter characters (e.g., `fr`, `deg`). It may also incorrectly parse va... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,1692 @@
+package dev.tonholo.s2c.parser.ast.css
+
+import app.cash.burst.Burst
+import app.cash.burst.burstValues
+import dev.tonholo.s2c.lexer.Token
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+import dev.tonholo.s2c.parser.ast.css.syntax.CssParserException
+import dev.tonholo.s2c.parser.ast.css.syntax.n... | _:hammer_and_wrench: Refactor suggestion_
**Correct usage of the 'Burst' library for parameterized tests**
The use of `burstValues` within the parameter default value is incorrect. When using the 'Burst' library, you should not assign default values to parameters. Instead, declare the parameter without a default valu... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,25 @@
+package dev.tonholo.s2c.lexer.css.token.consumer
+
+import dev.tonholo.s2c.lexer.Token
+import dev.tonholo.s2c.lexer.TokenIterator
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+
+internal class AtKeywordTokenConsumer(
+ iterator: TokenIterator<CssTokenKind>,
+) : TokenConsumer(iterator) {
+ ov... | _:warning: Potential issue_
**Critical: Incorrect @-keyword parsing logic**
The current implementation has several issues:
1. CSS @-keywords don't necessarily end with a space (they can end with '{', ';', etc.)
2. No validation of the keyword format
3. Potential infinite loop if no space is found
Consider this impl... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,30 @@
+package dev.tonholo.s2c.lexer.css
+
+import dev.tonholo.s2c.lexer.TokenIterator
+
+/**
+ * Iterator for CSS tokens.
+ */
+internal class CssTokenIterator : TokenIterator<CssTokenKind>() {
+ /**
+ * Gets the kind of the current token.
+ * @return The kind of the current token.
+ */
+ ... | _:warning: Potential issue_
**Add support for common CSS token types**
The fallback to Ident is too broad. Many common CSS token types are missing:
- Colors (#RGB, #RRGGBB)
- String literals
- Important tokens
- Functions
- Delimiters
Consider this approach:
```diff
-else -> {
- CssTokenKind.fromChar(char) ?: C... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,30 @@
+package dev.tonholo.s2c.lexer.css
+
+import dev.tonholo.s2c.lexer.TokenIterator
+
+/**
+ * Iterator for CSS tokens.
+ */
+internal class CssTokenIterator : TokenIterator<CssTokenKind>() {
+ /**
+ * Gets the kind of the current token.
+ * @return The kind of the current token.
+ */
+ ... | _:warning: Potential issue_
**Enhance number token detection**
Current number detection is too simplistic. CSS numbers can include:
- Decimal points
- Scientific notation
- Negative values
- Units (px, em, etc.)
Consider this approach:
```diff
-char in '0'..'9' -> {
- CssTokenKind.Number
-}
+char.isDigit() || (... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,30 @@
+package dev.tonholo.s2c.lexer.css
+
+import dev.tonholo.s2c.lexer.TokenIterator
+
+/**
+ * Iterator for CSS tokens.
+ */
+internal class CssTokenIterator : TokenIterator<CssTokenKind>() {
+ /**
+ * Gets the kind of the current token.
+ * @return The kind of the current token.
+ */
+ ... | _:warning: Potential issue_
**Improve URL token detection**
The current URL detection is fragile and doesn't handle:
- Quoted URLs: `url("example.com")`
- URLs with spaces: `url(http://example.com)`
- Data URLs: `url(data:image/png;base64,...)`
Consider this approach:
```diff
-char == 'u' && peek(1) == 'r' && peek... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,27 @@
+package dev.tonholo.s2c.lexer.css.token.consumer
+
+import dev.tonholo.s2c.lexer.Token
+import dev.tonholo.s2c.lexer.TokenIterator
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+
+internal class WhitespaceTokenConsumer(
+ iterator: TokenIterator<CssTokenKind>,
+) : TokenConsumer(iterator) {
+ o... | _:hammer_and_wrench: Refactor suggestion_
**Improve whitespace handling efficiency**
The current implementation has inefficiencies:
1. Uses `get()` instead of `next()`, requiring explicit offset management
2. No distinction between different types of whitespace (space, tab, newline)
Consider this approach:
```diff... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,34 @@
+package dev.tonholo.s2c.lexer.css.token.consumer
+
+import dev.tonholo.s2c.lexer.Token
+import dev.tonholo.s2c.lexer.TokenIterator
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+
+internal class StringTokenConsumer(
+ iterator: TokenIterator<CssTokenKind>,
+) : TokenConsumer(iterator) {
+ overr... | _:warning: Potential issue_
**Add EOF check and escape sequence handling**
The while loop has several issues:
1. No EOF check in peek operation
2. No handling of escape sequences (e.g., `\"` or `\'`)
3. Mixing of char literals with CssTokenKind
Consider this safer implementation:
```diff
while (iterator.hasNext()) ... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,34 @@
+package dev.tonholo.s2c.lexer.css.token.consumer
+
+import dev.tonholo.s2c.lexer.Token
+import dev.tonholo.s2c.lexer.TokenIterator
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+
+internal class StringTokenConsumer(
+ iterator: TokenIterator<CssTokenKind>,
+) : TokenConsumer(iterator) {
+ overr... | _:hammer_and_wrench: Refactor suggestion_
**Add validation before creating token**
The method should validate that a proper string terminator was found before creating the token.
```diff
+ // Ensure we found a closing quote
+ if (!iterator.hasNext()) {
+ return listOf() // Unterminated string
+ }
... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,41 @@
+package dev.tonholo.s2c.domain.svg
+
+import dev.tonholo.s2c.domain.xml.XmlNode
+import dev.tonholo.s2c.domain.xml.XmlParentNode
+import dev.tonholo.s2c.domain.xml.XmlTextNode
+import dev.tonholo.s2c.extensions.firstInstanceOf
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+import dev.tonholo.s2c.lexe... | _:hammer_and_wrench: Refactor suggestion_
**Add content validation before parsing**
The `resolveTree` method should validate the CSS content before attempting to parse it. Consider adding basic validation or error handling.
```diff
internal fun resolveTree(parser: AstParser<CssTokenKind, StyleSheet>) {
+ if (con... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,41 @@
+package dev.tonholo.s2c.domain.svg
+
+import dev.tonholo.s2c.domain.xml.XmlNode
+import dev.tonholo.s2c.domain.xml.XmlParentNode
+import dev.tonholo.s2c.domain.xml.XmlTextNode
+import dev.tonholo.s2c.extensions.firstInstanceOf
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+import dev.tonholo.s2c.lexe... | _:warning: Potential issue_
**Implement toJsString method**
The `toJsString` method is empty. It should generate a JavaScript string representation of the style node.
```diff
- override fun toString(): String = toJsString {
- }
+ override fun toString(): String = toJsString {
+ append("const style = ... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,41 @@
+package dev.tonholo.s2c.domain.svg
+
+import dev.tonholo.s2c.domain.xml.XmlNode
+import dev.tonholo.s2c.domain.xml.XmlParentNode
+import dev.tonholo.s2c.domain.xml.XmlTextNode
+import dev.tonholo.s2c.extensions.firstInstanceOf
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+import dev.tonholo.s2c.lexe... | _:hammer_and_wrench: Refactor suggestion_
**Consider thread-safety for tree resolution**
The `_tree` property might have thread-safety issues if `resolveTree` is called from multiple threads. Consider using `@Volatile` or synchronization.
```diff
- private var _tree: StyleSheet? = null
+ @Volatile
+ private... |
svg-to-compose | github_2023 | others | 99 | rafaeltonholo | coderabbitai[bot] | @@ -0,0 +1,41 @@
+package dev.tonholo.s2c.domain.svg
+
+import dev.tonholo.s2c.domain.xml.XmlNode
+import dev.tonholo.s2c.domain.xml.XmlParentNode
+import dev.tonholo.s2c.domain.xml.XmlTextNode
+import dev.tonholo.s2c.extensions.firstInstanceOf
+import dev.tonholo.s2c.lexer.css.CssTokenKind
+import dev.tonholo.s2c.lexe... | _:warning: Potential issue_
**Add error handling for missing text nodes**
The `content` property assumes there will always be a text node child. Consider handling the case when no text node is found.
```diff
val content: String by lazy {
children
.firstInstanceOf<XmlTextNode>()
+ ?.content
+ ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.