chore: restore original directory structure (project under code-review-graph-main/)
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
package com.example.kafka;
|
||||
|
||||
import org.springframework.kafka.annotation.KafkaListener;
|
||||
import org.springframework.kafka.annotation.KafkaHandler;
|
||||
import org.springframework.kafka.core.KafkaTemplate;
|
||||
import org.springframework.kafka.core.KafkaOperations;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.stereotype.Component;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import reactor.kafka.receiver.KafkaReceiver;
|
||||
|
||||
// ── Annotation-based consumer ─────────────────────────────────────────────
|
||||
|
||||
@Service
|
||||
class OrderEventConsumer {
|
||||
|
||||
@KafkaListener(topics = "order-events")
|
||||
public void onOrder(String payload) {}
|
||||
|
||||
@KafkaListener(topics = {"order-dlq", "order-retry"})
|
||||
public void onDlq(String payload) {}
|
||||
}
|
||||
|
||||
// ── Annotation-based producer (KafkaTemplate field) ───────────────────────
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
class NotificationProducer {
|
||||
private final KafkaTemplate<String, String> kafkaTemplate;
|
||||
// static field — should NOT produce edge
|
||||
private static final String TOPIC = "notifications";
|
||||
}
|
||||
|
||||
// ── Reactive consumer (KafkaReceiver field) ───────────────────────────────
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
class ReactiveOrderConsumer {
|
||||
private final KafkaReceiver<String, OrderEvent> kafkaReceiver;
|
||||
private final KafkaOperations<String, String> kafkaOps;
|
||||
}
|
||||
|
||||
// ── plain class with no Kafka ─────────────────────────────────────────────
|
||||
|
||||
class OrderEvent {
|
||||
private String id;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export function MarkdownMsg() {
|
||||
return <div />;
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace SampleApp
|
||||
{
|
||||
public interface IRepository
|
||||
{
|
||||
User FindById(int id);
|
||||
void Save(User user);
|
||||
}
|
||||
|
||||
public class User
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Name { get; set; }
|
||||
}
|
||||
|
||||
public class InMemoryRepo : IRepository
|
||||
{
|
||||
private Dictionary<int, User> _users = new();
|
||||
|
||||
public User FindById(int id)
|
||||
{
|
||||
return _users.ContainsKey(id) ? _users[id] : null;
|
||||
}
|
||||
|
||||
public void Save(User user)
|
||||
{
|
||||
_users[user.Id] = user;
|
||||
Console.WriteLine($"Saved user {user.Id}");
|
||||
}
|
||||
}
|
||||
|
||||
public class UserService
|
||||
{
|
||||
private IRepository _repo;
|
||||
|
||||
public UserService(IRepository repo)
|
||||
{
|
||||
_repo = repo;
|
||||
}
|
||||
|
||||
public User GetUser(int id)
|
||||
{
|
||||
return _repo.FindById(id);
|
||||
}
|
||||
}
|
||||
|
||||
// Inheritance coverage for C# base_list clauses.
|
||||
public class CachedRepo : InMemoryRepo, IRepository
|
||||
{
|
||||
public new User FindById(int id) { return base.FindById(id); }
|
||||
}
|
||||
|
||||
public class DisposableService : System.IDisposable
|
||||
{
|
||||
public void Dispose() { }
|
||||
}
|
||||
|
||||
public class UserList : List<User> { }
|
||||
public class ScopedUserList : System.Collections.Generic.List<User> { }
|
||||
|
||||
// A generic constraint is not an inheritance clause.
|
||||
public class ConstrainedHolder<T> where T : IRepository
|
||||
{
|
||||
public T Value { get; set; }
|
||||
}
|
||||
|
||||
public record AuditedUser : User, IRepository
|
||||
{
|
||||
public User FindById(int id) { return null; }
|
||||
public void Save(User user) { }
|
||||
}
|
||||
|
||||
public record TaggedUser(int Id, string Tag) : User { }
|
||||
|
||||
public struct Token : IRepository
|
||||
{
|
||||
public User FindById(int id) { return null; }
|
||||
public void Save(User user) { }
|
||||
}
|
||||
|
||||
// Constructor arguments and enum storage types are not bases.
|
||||
public class SeededRepo(int seed) : InMemoryRepo
|
||||
{
|
||||
public int Seed { get; } = seed;
|
||||
}
|
||||
|
||||
public enum Status : byte
|
||||
{
|
||||
Active,
|
||||
Closed,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.example.auth;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface UserRepository {
|
||||
Optional<User> findById(int id);
|
||||
void save(User user);
|
||||
}
|
||||
|
||||
class User {
|
||||
private int id;
|
||||
private String name;
|
||||
private String email;
|
||||
|
||||
public User(int id, String name, String email) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public int getId() { return id; }
|
||||
public String getName() { return name; }
|
||||
public String getEmail() { return email; }
|
||||
}
|
||||
|
||||
class InMemoryRepo implements UserRepository {
|
||||
private Map<Integer, User> users = new HashMap<>();
|
||||
|
||||
@Override
|
||||
public Optional<User> findById(int id) {
|
||||
return Optional.ofNullable(users.get(id));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(User user) {
|
||||
users.put(user.getId(), user);
|
||||
System.out.println("Saved user " + user.getId());
|
||||
}
|
||||
}
|
||||
|
||||
class UserService {
|
||||
private final UserRepository repo;
|
||||
|
||||
public UserService(UserRepository repo) {
|
||||
this.repo = repo;
|
||||
}
|
||||
|
||||
public User createUser(String name, String email) {
|
||||
User user = new User(1, name, email);
|
||||
repo.save(user);
|
||||
return user;
|
||||
}
|
||||
|
||||
public Optional<User> getUser(int id) {
|
||||
return repo.findById(id);
|
||||
}
|
||||
}
|
||||
|
||||
class CachedRepo extends InMemoryRepo {
|
||||
@Override
|
||||
public void save(User user) {
|
||||
super.save(user);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.example.shop;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
// Plain interface — not a Spring bean
|
||||
public interface OrderRepository {
|
||||
void save(Order order);
|
||||
Order findById(Long id);
|
||||
}
|
||||
|
||||
// @Repository stereotype — Spring-managed bean
|
||||
@Repository
|
||||
class JpaOrderRepository implements OrderRepository {
|
||||
@Override
|
||||
public void save(Order order) {}
|
||||
|
||||
@Override
|
||||
public Order findById(Long id) { return null; }
|
||||
}
|
||||
|
||||
// @Service with @Autowired field injection
|
||||
@Service
|
||||
class NotificationService {
|
||||
@Autowired
|
||||
private OrderRepository orderRepository;
|
||||
|
||||
public void notify(Long orderId) {
|
||||
Order o = orderRepository.findById(orderId);
|
||||
}
|
||||
}
|
||||
|
||||
// @Service with Lombok @RequiredArgsConstructor (constructor injection via final fields)
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
class OrderService {
|
||||
private final OrderRepository orderRepository;
|
||||
private final NotificationService notificationService;
|
||||
private static final String TAG = "OrderService"; // static final — NOT injected
|
||||
|
||||
public void placeOrder(Order order) {
|
||||
orderRepository.save(order);
|
||||
notificationService.notify(order.getId());
|
||||
}
|
||||
}
|
||||
|
||||
// @Component with explicit @Autowired constructor
|
||||
@Component
|
||||
class AuditLogger {
|
||||
private final OrderRepository orderRepository;
|
||||
|
||||
@Autowired
|
||||
public AuditLogger(OrderRepository orderRepository) {
|
||||
this.orderRepository = orderRepository;
|
||||
}
|
||||
|
||||
public void log(String msg) {}
|
||||
}
|
||||
|
||||
// @Configuration with @Bean factory methods
|
||||
@Configuration
|
||||
class AppConfig {
|
||||
@Bean
|
||||
public OrderRepository orderRepository() {
|
||||
return new JpaOrderRepository();
|
||||
}
|
||||
}
|
||||
|
||||
class Order {
|
||||
private Long id;
|
||||
public Long getId() { return id; }
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.example.temporal;
|
||||
|
||||
import io.temporal.workflow.WorkflowInterface;
|
||||
import io.temporal.workflow.WorkflowMethod;
|
||||
import io.temporal.workflow.SignalMethod;
|
||||
import io.temporal.workflow.QueryMethod;
|
||||
import io.temporal.activity.ActivityInterface;
|
||||
import io.temporal.activity.ActivityMethod;
|
||||
|
||||
// ── Interfaces ───────────────────────────────────────────────────────────────
|
||||
|
||||
@WorkflowInterface
|
||||
public interface OrderWorkflow {
|
||||
@WorkflowMethod
|
||||
String processOrder(String orderId);
|
||||
|
||||
@SignalMethod
|
||||
void cancelOrder(String reason);
|
||||
|
||||
@QueryMethod
|
||||
String getStatus();
|
||||
}
|
||||
|
||||
@ActivityInterface
|
||||
public interface PaymentActivity {
|
||||
@ActivityMethod
|
||||
boolean chargeCard(String orderId, double amount);
|
||||
}
|
||||
|
||||
@ActivityInterface
|
||||
public interface ShippingActivity {
|
||||
@ActivityMethod
|
||||
String shipOrder(String orderId);
|
||||
}
|
||||
|
||||
// ── Implementations ──────────────────────────────────────────────────────────
|
||||
|
||||
// Workflow impl holds activity stubs as fields
|
||||
class OrderWorkflowImpl implements OrderWorkflow {
|
||||
|
||||
// These fields are assigned via Workflow.newActivityStub() at runtime
|
||||
private PaymentActivity paymentActivity;
|
||||
private ShippingActivity shippingActivity;
|
||||
|
||||
// Static fields should NOT produce TEMPORAL_STUB edges
|
||||
private static final String TAG = "OrderWorkflowImpl";
|
||||
|
||||
@Override
|
||||
public String processOrder(String orderId) {
|
||||
boolean paid = paymentActivity.chargeCard(orderId, 100.0);
|
||||
if (!paid) return "FAILED";
|
||||
String trackingId = shippingActivity.shipOrder(orderId);
|
||||
return trackingId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancelOrder(String reason) {}
|
||||
|
||||
@Override
|
||||
public String getStatus() { return "OK"; }
|
||||
}
|
||||
|
||||
// Activity impls
|
||||
class PaymentActivityImpl implements PaymentActivity {
|
||||
@Override
|
||||
public boolean chargeCard(String orderId, double amount) { return true; }
|
||||
}
|
||||
|
||||
class ShippingActivityImpl implements ShippingActivity {
|
||||
@Override
|
||||
public String shipOrder(String orderId) { return "TRACK-001"; }
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { UserRepository, UserService } from '../sample_typescript';
|
||||
|
||||
describe('UserService (under __tests__/)', () => {
|
||||
it('constructs a service', () => {
|
||||
const service = new UserService();
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
it('returns undefined for missing user', () => {
|
||||
const service = new UserService();
|
||||
const user = service.getUser(999);
|
||||
expect(user).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,6 @@
|
||||
import { cn } from '@/lib/utils';
|
||||
import { UserService } from './sample_typescript';
|
||||
|
||||
export function formatUser(name: string): string {
|
||||
return cn('user', name);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
"""Fixture that imports and calls functions from sample_python."""
|
||||
|
||||
from sample_python import create_auth_service
|
||||
|
||||
|
||||
def setup_and_run():
|
||||
service = create_auth_service()
|
||||
return service
|
||||
@@ -0,0 +1,12 @@
|
||||
#include "MyWidget.h"
|
||||
|
||||
MyWidget::MyWidget(QWidget* parent) : QMainWindow(parent) {}
|
||||
MyWidget::~MyWidget() {}
|
||||
void MyWidget::doSomething() { onReset(); }
|
||||
int MyWidget::calculateValue(int a, int b) { return a + b; }
|
||||
void MyWidget::onButtonClicked() { Q_EMIT dataReady(calculateValue(1, 2)); }
|
||||
void MyWidget::onDataReceived(int value) {
|
||||
if (value < 0) { Q_EMIT errorOccurred("err"); return; }
|
||||
doSomething();
|
||||
}
|
||||
void MyWidget::onReset() { Q_EMIT dataReady(0); }
|
||||
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
#include <QMainWindow>
|
||||
|
||||
QT_BEGIN_NAMESPACE namespace Ui { class MyWidgetClass; };
|
||||
QT_END_NAMESPACE
|
||||
|
||||
class MyWidget : public QMainWindow {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
MyWidget(QWidget* parent = nullptr);
|
||||
~MyWidget();
|
||||
void doSomething();
|
||||
int calculateValue(int a, int b);
|
||||
|
||||
protected Q_SLOTS:
|
||||
void onButtonClicked();
|
||||
void onDataReceived(int value);
|
||||
|
||||
public Q_SLOTS:
|
||||
void onReset();
|
||||
|
||||
Q_SIGNALS:
|
||||
void dataReady(int result);
|
||||
void errorOccurred(const QString& msg);
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
#include "MyWidgetPlain.h"
|
||||
|
||||
MyWidgetPlain::MyWidgetPlain() {}
|
||||
MyWidgetPlain::~MyWidgetPlain() {}
|
||||
|
||||
void MyWidgetPlain::doSomething() { onReset(); }
|
||||
int MyWidgetPlain::calculateValue(int a, int b) { return a + b; }
|
||||
void MyWidgetPlain::onButtonClicked() { int result = calculateValue(1, 2); }
|
||||
void MyWidgetPlain::onDataReceived(int value) { if (value < 0) return; doSomething(); }
|
||||
void MyWidgetPlain::onReset() {}
|
||||
@@ -0,0 +1,14 @@
|
||||
#pragma once
|
||||
|
||||
class MyWidgetPlain {
|
||||
public:
|
||||
MyWidgetPlain();
|
||||
~MyWidgetPlain();
|
||||
void doSomething();
|
||||
int calculateValue(int a, int b);
|
||||
|
||||
protected:
|
||||
void onButtonClicked();
|
||||
void onDataReceived(int value);
|
||||
void onReset();
|
||||
};
|
||||
@@ -0,0 +1,156 @@
|
||||
{
|
||||
"summary": "Analyzed 2 changed file(s):\n - 3 changed function(s)/class(es)\n - 2 affected flow(s)\n - 1 test gap(s)\n - Overall risk score: 0.72\n - Untested: rotate_token",
|
||||
"risk_score": 0.72,
|
||||
"changed_functions": [
|
||||
{
|
||||
"id": 101,
|
||||
"kind": "Function",
|
||||
"name": "rotate_token",
|
||||
"qualified_name": "auth/session.py::rotate_token",
|
||||
"file_path": "auth/session.py",
|
||||
"line_start": 42,
|
||||
"line_end": 78,
|
||||
"language": "python",
|
||||
"parent_name": null,
|
||||
"is_test": false,
|
||||
"risk_score": 0.72
|
||||
},
|
||||
{
|
||||
"id": 102,
|
||||
"kind": "Function",
|
||||
"name": "validate_session",
|
||||
"qualified_name": "auth/session.py::validate_session",
|
||||
"file_path": "auth/session.py",
|
||||
"line_start": 80,
|
||||
"line_end": 112,
|
||||
"language": "python",
|
||||
"parent_name": null,
|
||||
"is_test": false,
|
||||
"risk_score": 0.41
|
||||
},
|
||||
{
|
||||
"id": 103,
|
||||
"kind": "Function",
|
||||
"name": "format_expiry",
|
||||
"qualified_name": "auth/display.py::format_expiry",
|
||||
"file_path": "auth/display.py",
|
||||
"line_start": 10,
|
||||
"line_end": 18,
|
||||
"language": "python",
|
||||
"parent_name": null,
|
||||
"is_test": false,
|
||||
"risk_score": 0.1
|
||||
}
|
||||
],
|
||||
"affected_flows": [
|
||||
{
|
||||
"id": 7,
|
||||
"name": "login_handler -> rotate_token",
|
||||
"entry_point_id": 90,
|
||||
"depth": 4,
|
||||
"node_count": 6,
|
||||
"file_count": 3,
|
||||
"criticality": 0.83,
|
||||
"path": [90, 95, 101, 102, 110, 111],
|
||||
"steps": [
|
||||
{
|
||||
"node_id": 90,
|
||||
"name": "login_handler",
|
||||
"kind": "Function",
|
||||
"file": "auth/routes.py",
|
||||
"line_start": 12,
|
||||
"line_end": 40,
|
||||
"qualified_name": "auth/routes.py::login_handler"
|
||||
},
|
||||
{
|
||||
"node_id": 101,
|
||||
"name": "rotate_token",
|
||||
"kind": "Function",
|
||||
"file": "auth/session.py",
|
||||
"line_start": 42,
|
||||
"line_end": 78,
|
||||
"qualified_name": "auth/session.py::rotate_token"
|
||||
}
|
||||
],
|
||||
"created_at": "2026-06-01T10:00:00"
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"name": "cli_main -> validate_session",
|
||||
"entry_point_id": 120,
|
||||
"depth": 3,
|
||||
"node_count": 4,
|
||||
"file_count": 2,
|
||||
"criticality": 0.55,
|
||||
"path": [120, 121, 102, 130],
|
||||
"steps": [
|
||||
{
|
||||
"node_id": 120,
|
||||
"name": "cli_main",
|
||||
"kind": "Function",
|
||||
"file": "cli.py",
|
||||
"line_start": 5,
|
||||
"line_end": 60,
|
||||
"qualified_name": "cli.py::cli_main"
|
||||
}
|
||||
],
|
||||
"created_at": "2026-06-01T10:00:00"
|
||||
}
|
||||
],
|
||||
"test_gaps": [
|
||||
{
|
||||
"name": "rotate_token",
|
||||
"qualified_name": "auth/session.py::rotate_token",
|
||||
"file": "auth/session.py",
|
||||
"line_start": 42,
|
||||
"line_end": 78
|
||||
}
|
||||
],
|
||||
"review_priorities": [
|
||||
{
|
||||
"id": 101,
|
||||
"kind": "Function",
|
||||
"name": "rotate_token",
|
||||
"qualified_name": "auth/session.py::rotate_token",
|
||||
"file_path": "auth/session.py",
|
||||
"line_start": 42,
|
||||
"line_end": 78,
|
||||
"language": "python",
|
||||
"parent_name": null,
|
||||
"is_test": false,
|
||||
"risk_score": 0.72
|
||||
},
|
||||
{
|
||||
"id": 102,
|
||||
"kind": "Function",
|
||||
"name": "validate_session",
|
||||
"qualified_name": "auth/session.py::validate_session",
|
||||
"file_path": "auth/session.py",
|
||||
"line_start": 80,
|
||||
"line_end": 112,
|
||||
"language": "python",
|
||||
"parent_name": null,
|
||||
"is_test": false,
|
||||
"risk_score": 0.41
|
||||
},
|
||||
{
|
||||
"id": 103,
|
||||
"kind": "Function",
|
||||
"name": "format_expiry",
|
||||
"qualified_name": "auth/display.py::format_expiry",
|
||||
"file_path": "auth/display.py",
|
||||
"line_start": 10,
|
||||
"line_end": 18,
|
||||
"language": "python",
|
||||
"parent_name": null,
|
||||
"is_test": false,
|
||||
"risk_score": 0.1
|
||||
}
|
||||
],
|
||||
"functions_truncated": false,
|
||||
"context_savings": {
|
||||
"estimated": true,
|
||||
"saved_tokens": 12159,
|
||||
"saved_percent": 94
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Fixture with multiple calls to the same function from one caller."""
|
||||
|
||||
|
||||
async def _internal_request(url: str, data: bytes) -> dict:
|
||||
return {"url": url}
|
||||
|
||||
|
||||
async def process_document(content: bytes) -> str:
|
||||
"""Calls _internal_request twice on different lines."""
|
||||
first = await _internal_request("http://localhost/fast", content)
|
||||
text = first.get("body", "")
|
||||
second = await _internal_request("http://localhost/slow", content)
|
||||
return text or second.get("body", "")
|
||||
@@ -0,0 +1,92 @@
|
||||
---
|
||||
# Sanitized fixture for Ansible parser tests
|
||||
|
||||
- import_playbook: base-setup.yml
|
||||
|
||||
- name: Configure web servers
|
||||
hosts: webservers
|
||||
become: true
|
||||
gather_facts: true
|
||||
vars_files:
|
||||
- vars/common.yml
|
||||
- vars/web.yml
|
||||
pre_tasks:
|
||||
- name: Verify connectivity
|
||||
ansible.builtin.wait_for_connection:
|
||||
timeout: 30
|
||||
roles:
|
||||
- common
|
||||
- role: nginx
|
||||
tags: [nginx]
|
||||
tasks:
|
||||
- name: Install packages
|
||||
ansible.builtin.package:
|
||||
name: "{{ item }}"
|
||||
state: present
|
||||
loop: [curl, rsync]
|
||||
|
||||
- name: Deploy config
|
||||
template:
|
||||
src: app.conf.j2
|
||||
dest: /etc/app/app.conf
|
||||
notify: restart app
|
||||
|
||||
- name: Run deploy tasks
|
||||
ansible.builtin.include_tasks: deploy.yml
|
||||
|
||||
- name: Apply hardening role
|
||||
ansible.builtin.import_role:
|
||||
name: security
|
||||
|
||||
- name: Handle migration
|
||||
block:
|
||||
- name: Run migration script
|
||||
command: /opt/app/migrate.sh
|
||||
- name: Verify migration
|
||||
ansible.builtin.stat:
|
||||
path: /opt/app/.migrated
|
||||
register: migration_stat
|
||||
rescue:
|
||||
- name: Log migration failure
|
||||
debug:
|
||||
msg: "Migration failed, check logs"
|
||||
|
||||
- name: Restart service if needed
|
||||
service:
|
||||
name: app
|
||||
state: restarted
|
||||
when: migration_stat.stat.exists | default(false)
|
||||
|
||||
post_tasks:
|
||||
- name: Smoke test
|
||||
uri:
|
||||
url: http://localhost/health
|
||||
status_code: 200
|
||||
|
||||
handlers:
|
||||
- name: restart app
|
||||
service:
|
||||
name: app
|
||||
state: restarted
|
||||
listen: app restarted
|
||||
|
||||
- name: Configure database servers
|
||||
hosts: dbservers
|
||||
become: true
|
||||
tasks:
|
||||
- name: Install database
|
||||
package:
|
||||
name: postgresql
|
||||
state: present
|
||||
notify:
|
||||
- restart db
|
||||
- run migrations
|
||||
|
||||
handlers:
|
||||
- name: restart db
|
||||
service:
|
||||
name: postgresql
|
||||
state: restarted
|
||||
|
||||
- name: run migrations
|
||||
command: /opt/db/migrate.sh
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
dependencies:
|
||||
- common
|
||||
- role: nginx
|
||||
- name: security.hardening
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
library(dplyr)
|
||||
require(ggplot2)
|
||||
source("utils.R")
|
||||
|
||||
add <- function(x, y) {
|
||||
x + y
|
||||
}
|
||||
|
||||
multiply = function(a, b) {
|
||||
a * b
|
||||
}
|
||||
|
||||
MyClass <- setRefClass("MyClass",
|
||||
fields = list(name = "character", age = "numeric"),
|
||||
methods = list(
|
||||
greet = function() {
|
||||
cat(paste("Hello", name))
|
||||
},
|
||||
get_age = function() {
|
||||
return(age)
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
process_data <- function(data) {
|
||||
result <- dplyr::filter(data, x > 5)
|
||||
summary <- dplyr::summarize(result, mean_x = mean(x))
|
||||
add(1, 2)
|
||||
summary
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
typedef struct {
|
||||
int id;
|
||||
char name[50];
|
||||
} User;
|
||||
|
||||
User* create_user(int id, const char* name) {
|
||||
User* user = malloc(sizeof(User));
|
||||
user->id = id;
|
||||
snprintf(user->name, 50, "%s", name);
|
||||
return user;
|
||||
}
|
||||
|
||||
void print_user(User* user) {
|
||||
printf("User %d: %s\n", user->id, user->name);
|
||||
}
|
||||
|
||||
int main() {
|
||||
User* u = create_user(1, "Alice");
|
||||
print_user(u);
|
||||
free(u);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
class Animal {
|
||||
public:
|
||||
std::string name;
|
||||
int age;
|
||||
|
||||
Animal(std::string n, int a) : name(n), age(a) {}
|
||||
virtual void speak() { std::cout << name << " speaks" << std::endl; }
|
||||
};
|
||||
|
||||
class Dog : public Animal {
|
||||
public:
|
||||
Dog(std::string n, int a) : Animal(n, a) {}
|
||||
void speak() override { std::cout << name << " barks" << std::endl; }
|
||||
void fetch() { std::cout << name << " fetches" << std::endl; }
|
||||
};
|
||||
|
||||
void greet(const Animal& animal) {
|
||||
std::cout << "Hello " << animal.name << std::endl;
|
||||
}
|
||||
|
||||
int main() {
|
||||
Dog d("Rex", 5);
|
||||
d.speak();
|
||||
greet(d);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
abstract class Animal {
|
||||
String get name;
|
||||
void speak();
|
||||
}
|
||||
|
||||
mixin SwimmingMixin {
|
||||
void swim() => print('swimming');
|
||||
}
|
||||
|
||||
enum PetType { dog, cat, bird }
|
||||
|
||||
class Dog extends Animal with SwimmingMixin {
|
||||
final String name;
|
||||
final PetType type;
|
||||
|
||||
Dog(this.name) : type = PetType.dog;
|
||||
|
||||
@override
|
||||
void speak() {
|
||||
print('Woof! I am $name');
|
||||
}
|
||||
|
||||
Future<void> fetch(String item) async {
|
||||
await _run();
|
||||
print('Fetched $item');
|
||||
}
|
||||
|
||||
void _run() {
|
||||
print('running');
|
||||
}
|
||||
|
||||
static Dog create(String name) {
|
||||
return Dog(name);
|
||||
}
|
||||
}
|
||||
|
||||
Dog createDog(String name) {
|
||||
return Dog(name);
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
defmodule Calculator do
|
||||
@moduledoc """
|
||||
Simple calculator module.
|
||||
"""
|
||||
|
||||
def add(a, b) do
|
||||
a + b
|
||||
end
|
||||
|
||||
def subtract(a, b), do: a - b
|
||||
|
||||
defp log(msg) do
|
||||
IO.puts(msg)
|
||||
:ok
|
||||
end
|
||||
|
||||
def compute(a, b) do
|
||||
result = add(a, b)
|
||||
log("result: #{result}")
|
||||
result
|
||||
end
|
||||
end
|
||||
|
||||
defmodule MathHelpers do
|
||||
alias Calculator
|
||||
import Calculator, only: [add: 2]
|
||||
require Logger
|
||||
|
||||
def double(x) do
|
||||
Calculator.compute(x, x)
|
||||
end
|
||||
|
||||
def triple(x) do
|
||||
double(x) + x
|
||||
end
|
||||
end
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
extends Node
|
||||
class_name SampleManager
|
||||
|
||||
const MAX_SIZE = 10
|
||||
const OtherScript = preload("res://scripts/other.gd")
|
||||
|
||||
signal item_added(item: Item)
|
||||
|
||||
@export var speed: float = 2.5
|
||||
@onready var timer: Timer = $Timer
|
||||
|
||||
var items: Array[Item] = []
|
||||
|
||||
|
||||
class Item:
|
||||
var name: String
|
||||
var level: int
|
||||
|
||||
func promote() -> void:
|
||||
level += 1
|
||||
|
||||
|
||||
func _ready() -> void:
|
||||
timer.start()
|
||||
_load_items()
|
||||
OtherScript.register(self)
|
||||
|
||||
|
||||
func _load_items() -> void:
|
||||
for i in range(MAX_SIZE):
|
||||
var item := Item.new()
|
||||
items.append(item)
|
||||
item_added.emit(item)
|
||||
|
||||
|
||||
func get_item(idx: int) -> Item:
|
||||
return items[idx]
|
||||
|
||||
|
||||
static func helper() -> int:
|
||||
return 42
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
#pragma once
|
||||
#include <string>
|
||||
|
||||
class Shape {
|
||||
public:
|
||||
std::string color;
|
||||
|
||||
Shape(std::string c) : color(c) {}
|
||||
virtual double area() const = 0;
|
||||
};
|
||||
|
||||
class Circle : public Shape {
|
||||
public:
|
||||
double radius;
|
||||
|
||||
Circle(std::string c, double r) : Shape(c), radius(r) {}
|
||||
double area() const override { return 3.14159 * radius * radius; }
|
||||
};
|
||||
|
||||
inline double perimeter(const Circle& circle) {
|
||||
return 2.0 * 3.14159 * circle.radius;
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
module SampleModule
|
||||
|
||||
using LinearAlgebra
|
||||
using Statistics: mean, std
|
||||
import Base: show, print
|
||||
import JSON
|
||||
|
||||
export greet, Dog, process
|
||||
public square, add
|
||||
|
||||
@enum Color RED BLUE GREEN
|
||||
|
||||
abstract type AbstractAnimal end
|
||||
|
||||
struct Dog <: AbstractAnimal
|
||||
name::String
|
||||
age::Int
|
||||
end
|
||||
|
||||
mutable struct MutablePoint
|
||||
x::Float64
|
||||
y::Float64
|
||||
end
|
||||
|
||||
function greet(name::String)
|
||||
println("Hello, $name")
|
||||
end
|
||||
|
||||
function Base.show(io::IO, d::Dog)
|
||||
print(io, "Dog($(d.name))")
|
||||
end
|
||||
|
||||
add(a, b) = a + b
|
||||
|
||||
square(x) = x^2
|
||||
|
||||
const MY_CONST = 42
|
||||
|
||||
macro sayhello(name)
|
||||
:(println("Hello, ", $name))
|
||||
end
|
||||
|
||||
function outer()
|
||||
function inner()
|
||||
return 1
|
||||
end
|
||||
x = inner()
|
||||
result = map(v -> v^2, [1,2,3])
|
||||
return x
|
||||
end
|
||||
|
||||
function process(data::Vector{Float64}; verbose=false)
|
||||
if verbose
|
||||
println("Processing...")
|
||||
end
|
||||
normed = data ./ maximum(data)
|
||||
return sum(normed) / length(normed)
|
||||
end
|
||||
|
||||
include("utils.jl")
|
||||
|
||||
@testset "Arithmetic" begin
|
||||
@test add(1, 2) == 3
|
||||
@test square(4) == 16
|
||||
end
|
||||
|
||||
end # module
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.example
|
||||
|
||||
import java.util.UUID
|
||||
|
||||
interface UserRepository {
|
||||
fun findById(id: Int): User?
|
||||
fun save(user: User)
|
||||
}
|
||||
|
||||
data class User(val id: Int, val name: String, val email: String)
|
||||
|
||||
class InMemoryRepo : UserRepository {
|
||||
private val users = mutableMapOf<Int, User>()
|
||||
|
||||
override fun findById(id: Int): User? = users[id]
|
||||
|
||||
override fun save(user: User) {
|
||||
users[user.id] = user
|
||||
println("Saved user ${user.id}")
|
||||
}
|
||||
}
|
||||
|
||||
fun createUser(repo: UserRepository, name: String, email: String): User {
|
||||
val user = User(1, name, email)
|
||||
repo.save(user)
|
||||
return user
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
-- sample.lua - Comprehensive Lua test fixture for tree-sitter parsing
|
||||
-- Exercises all major constructs: functions, methods, classes, imports, tables
|
||||
|
||||
-- Module-level require() imports
|
||||
local json = require("cjson")
|
||||
local utils = require("lib.utils")
|
||||
local log = require("logging").getLogger("sample")
|
||||
|
||||
-- Top-level function declaration
|
||||
function greet(name)
|
||||
print("Hello, " .. name)
|
||||
return name
|
||||
end
|
||||
|
||||
-- Local function declaration
|
||||
local function helper(x, y)
|
||||
return x + y
|
||||
end
|
||||
|
||||
-- Variable assignment creating a function
|
||||
local transform = function(data)
|
||||
return json.encode(data)
|
||||
end
|
||||
|
||||
-- Another variable-assigned function (module-level)
|
||||
local validate = function(input)
|
||||
if input == nil then
|
||||
return false, "input is nil"
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- Table constructor as a "class" using metatable + __index pattern
|
||||
local Animal = {}
|
||||
Animal.__index = Animal
|
||||
|
||||
-- Constructor
|
||||
function Animal.new(name, sound)
|
||||
local self = setmetatable({}, Animal)
|
||||
self.name = name
|
||||
self.sound = sound
|
||||
return self
|
||||
end
|
||||
|
||||
-- Method defined with colon syntax
|
||||
function Animal:speak()
|
||||
log:info(self.name .. " says " .. self.sound)
|
||||
return self.sound
|
||||
end
|
||||
|
||||
-- Another colon-syntax method
|
||||
function Animal:rename(new_name)
|
||||
local old = self.name
|
||||
self.name = new_name
|
||||
return old
|
||||
end
|
||||
|
||||
-- Inheritance pattern
|
||||
local Dog = setmetatable({}, { __index = Animal })
|
||||
Dog.__index = Dog
|
||||
|
||||
function Dog.new(name)
|
||||
local self = Animal.new(name, "Woof")
|
||||
return setmetatable(self, Dog)
|
||||
end
|
||||
|
||||
function Dog:fetch(item)
|
||||
self:speak()
|
||||
print(self.name .. " fetches " .. item)
|
||||
return item
|
||||
end
|
||||
|
||||
-- Nested function calls and method calls
|
||||
local function process_animals()
|
||||
local a = Animal.new("Cat", "Meow")
|
||||
local d = Dog.new("Rex")
|
||||
|
||||
-- Method calls (colon syntax)
|
||||
a:speak()
|
||||
d:speak()
|
||||
d:fetch("ball")
|
||||
|
||||
-- Dot-syntax method call
|
||||
local encoded = json.encode({ animals = { a.name, d.name } })
|
||||
|
||||
-- Nested calls
|
||||
print(string.format("Processed %d animals", 2))
|
||||
utils.log(json.decode(encoded))
|
||||
|
||||
return encoded
|
||||
end
|
||||
|
||||
-- Table constructor with mixed fields
|
||||
local config = {
|
||||
debug = true,
|
||||
version = "1.0.0",
|
||||
max_retries = 3,
|
||||
handlers = {
|
||||
on_error = function(err)
|
||||
log:error(err)
|
||||
end,
|
||||
on_success = function(result)
|
||||
log:info("OK: " .. tostring(result))
|
||||
end,
|
||||
},
|
||||
}
|
||||
|
||||
-- Simple "test" function (test_something pattern)
|
||||
local function test_greet()
|
||||
local result = greet("World")
|
||||
assert(result == "World", "greet should return name")
|
||||
end
|
||||
|
||||
local function test_animal_speak()
|
||||
local a = Animal.new("TestCat", "Mew")
|
||||
local sound = a:speak()
|
||||
assert(sound == "Mew", "speak should return sound")
|
||||
end
|
||||
|
||||
local function test_dog_fetch()
|
||||
local d = Dog.new("TestDog")
|
||||
local item = d:fetch("stick")
|
||||
assert(item == "stick", "fetch should return item")
|
||||
end
|
||||
|
||||
-- Return statement (module pattern)
|
||||
return {
|
||||
greet = greet,
|
||||
helper = helper,
|
||||
transform = transform,
|
||||
validate = validate,
|
||||
Animal = Animal,
|
||||
Dog = Dog,
|
||||
process_animals = process_animals,
|
||||
config = config,
|
||||
test_greet = test_greet,
|
||||
test_animal_speak = test_animal_speak,
|
||||
test_dog_fetch = test_dog_fetch,
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
-- sample.luau - Luau test fixture for tree-sitter parsing
|
||||
-- Exercises Luau-specific features: type annotations, type aliases, and Lua constructs
|
||||
|
||||
-- Module-level require() imports
|
||||
local HttpService = require(game.ReplicatedStorage.HttpService)
|
||||
local utils = require("lib.utils")
|
||||
local log = require("logging").getLogger("sample")
|
||||
|
||||
-- Type alias (Luau-specific)
|
||||
type Vector3 = {
|
||||
x: number,
|
||||
y: number,
|
||||
z: number,
|
||||
}
|
||||
|
||||
type Callback = (input: string) -> string
|
||||
|
||||
-- Top-level function with type annotations
|
||||
function greet(name: string): string
|
||||
print("Hello, " .. name)
|
||||
return name
|
||||
end
|
||||
|
||||
-- Local function with type annotations
|
||||
local function add(a: number, b: number): number
|
||||
return a + b
|
||||
end
|
||||
|
||||
-- Variable assignment creating a function
|
||||
local transform = function(data: any): string
|
||||
return HttpService:JSONEncode(data)
|
||||
end
|
||||
|
||||
-- Table constructor as a "class" using metatable + __index pattern
|
||||
local Animal = {}
|
||||
Animal.__index = Animal
|
||||
|
||||
-- Constructor with type annotations
|
||||
function Animal.new(name: string, sound: string): Animal
|
||||
local self = setmetatable({}, Animal)
|
||||
self.name = name
|
||||
self.sound = sound
|
||||
return self
|
||||
end
|
||||
|
||||
-- Method defined with colon syntax
|
||||
function Animal:speak(): string
|
||||
log:info(self.name .. " says " .. self.sound)
|
||||
return self.sound
|
||||
end
|
||||
|
||||
-- Another colon-syntax method
|
||||
function Animal:rename(new_name: string): string
|
||||
local old = self.name
|
||||
self.name = new_name
|
||||
return old
|
||||
end
|
||||
|
||||
-- Inheritance pattern
|
||||
local Dog = setmetatable({}, { __index = Animal })
|
||||
Dog.__index = Dog
|
||||
|
||||
function Dog.new(name: string): Dog
|
||||
local self = Animal.new(name, "Woof")
|
||||
return setmetatable(self, Dog)
|
||||
end
|
||||
|
||||
function Dog:fetch(item: string): string
|
||||
self:speak()
|
||||
print(self.name .. " fetches " .. item)
|
||||
return item
|
||||
end
|
||||
|
||||
-- Nested function calls and method calls
|
||||
local function process_animals(): string
|
||||
local a = Animal.new("Cat", "Meow")
|
||||
local d = Dog.new("Rex")
|
||||
|
||||
a:speak()
|
||||
d:speak()
|
||||
d:fetch("ball")
|
||||
|
||||
local encoded = HttpService:JSONEncode({ animals = { a.name, d.name } })
|
||||
print(string.format("Processed %d animals", 2))
|
||||
utils.log(encoded)
|
||||
|
||||
return encoded
|
||||
end
|
||||
|
||||
-- Test functions
|
||||
local function test_greet()
|
||||
local result = greet("World")
|
||||
assert(result == "World", "greet should return name")
|
||||
end
|
||||
|
||||
local function test_animal_speak()
|
||||
local a = Animal.new("TestCat", "Mew")
|
||||
local sound = a:speak()
|
||||
assert(sound == "Mew", "speak should return sound")
|
||||
end
|
||||
|
||||
local function test_dog_fetch()
|
||||
local d = Dog.new("TestDog")
|
||||
local item = d:fetch("stick")
|
||||
assert(item == "stick", "fetch should return item")
|
||||
end
|
||||
|
||||
-- Return statement (module pattern)
|
||||
return {
|
||||
greet = greet,
|
||||
add = add,
|
||||
transform = transform,
|
||||
Animal = Animal,
|
||||
Dog = Dog,
|
||||
process_animals = process_animals,
|
||||
test_greet = test_greet,
|
||||
test_animal_speak = test_animal_speak,
|
||||
test_dog_fetch = test_dog_fetch,
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "Logger.h"
|
||||
|
||||
@interface Calculator : NSObject
|
||||
@property(nonatomic) NSInteger result;
|
||||
- (NSInteger)add:(NSInteger)a to:(NSInteger)b;
|
||||
- (void)reset;
|
||||
+ (Calculator *)sharedCalculator;
|
||||
@end
|
||||
|
||||
@implementation Calculator
|
||||
|
||||
- (NSInteger)add:(NSInteger)a to:(NSInteger)b {
|
||||
NSInteger sum = a + b;
|
||||
self.result = sum;
|
||||
[self logResult:sum];
|
||||
return sum;
|
||||
}
|
||||
|
||||
- (void)reset {
|
||||
self.result = 0;
|
||||
NSLog(@"Calculator reset");
|
||||
}
|
||||
|
||||
- (void)logResult:(NSInteger)value {
|
||||
NSLog(@"Result: %ld", (long)value);
|
||||
}
|
||||
|
||||
+ (Calculator *)sharedCalculator {
|
||||
static Calculator *instance = nil;
|
||||
if (instance == nil) {
|
||||
instance = [[Calculator alloc] init];
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
int main(int argc, const char * argv[]) {
|
||||
@autoreleasepool {
|
||||
Calculator *calc = [Calculator sharedCalculator];
|
||||
NSInteger r = [calc add:3 to:4];
|
||||
[calc reset];
|
||||
NSLog(@"Final: %ld", (long)r);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
description = "Sample flake fixture for code-review-graph tests";
|
||||
|
||||
inputs = {
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||
flake-utils.url = "github:numtide/flake-utils";
|
||||
};
|
||||
|
||||
outputs = { self, nixpkgs, flake-utils, ... }:
|
||||
flake-utils.lib.eachDefaultSystem (system:
|
||||
let
|
||||
pkgs = import nixpkgs { inherit system; };
|
||||
in {
|
||||
packages.default = pkgs.callPackage ./default.nix { };
|
||||
devShells.default = import ./shell.nix { inherit pkgs; };
|
||||
});
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Exception;
|
||||
|
||||
interface Repository {
|
||||
public function findById(int $id): ?User;
|
||||
public function save(User $user): void;
|
||||
}
|
||||
|
||||
class User {
|
||||
public int $id;
|
||||
public string $name;
|
||||
|
||||
public function __construct(int $id, string $name) {
|
||||
$this->id = $id;
|
||||
$this->name = $name;
|
||||
}
|
||||
|
||||
public function toString(): string {
|
||||
return "User({$this->id}, {$this->name})";
|
||||
}
|
||||
}
|
||||
|
||||
class InMemoryRepo implements Repository {
|
||||
private array $users = [];
|
||||
|
||||
public function findById(int $id): ?User {
|
||||
return $this->users[$id] ?? null;
|
||||
}
|
||||
|
||||
public function save(User $user): void {
|
||||
$this->users[$user->id] = $user;
|
||||
echo "Saved " . $user->toString() . "\n";
|
||||
}
|
||||
}
|
||||
|
||||
function createUser(Repository $repo, string $name): User {
|
||||
$user = new User(count($repo->users ?? []) + 1, $name);
|
||||
$repo->save($user);
|
||||
return $user;
|
||||
}
|
||||
|
||||
function sqlQuery(string $query): array {
|
||||
return [];
|
||||
}
|
||||
|
||||
function xl(string $value): string {
|
||||
return $value;
|
||||
}
|
||||
|
||||
function text(string $value): string {
|
||||
return $value;
|
||||
}
|
||||
|
||||
class SearchService {
|
||||
public function search(string $term): array {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
class QueryUtils {
|
||||
public static function fetchRecords(): array {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
class EncounterService {
|
||||
public static function create(array $payload): bool {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
class ExtendedRepo extends InMemoryRepo {
|
||||
public function __construct() {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public static function factory(): self {
|
||||
return new self();
|
||||
}
|
||||
|
||||
private function execute(): void {
|
||||
// no-op helper used for call extraction coverage
|
||||
}
|
||||
|
||||
public function runQueries(?SearchService $service): void {
|
||||
sqlQuery("SELECT 1");
|
||||
xl("hello");
|
||||
text("world");
|
||||
$this->execute();
|
||||
$service?->search("blood pressure");
|
||||
QueryUtils::fetchRecords();
|
||||
EncounterService::create([]);
|
||||
parent::__construct();
|
||||
self::factory();
|
||||
\dirname("/tmp");
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
use strict;
|
||||
use warnings;
|
||||
use File::Basename;
|
||||
|
||||
package Animal;
|
||||
|
||||
sub new {
|
||||
my ($class, %args) = @_;
|
||||
return bless \%args, $class;
|
||||
}
|
||||
|
||||
sub speak {
|
||||
my ($self) = @_;
|
||||
return "...";
|
||||
}
|
||||
|
||||
package Dog;
|
||||
|
||||
sub new {
|
||||
my ($class, %args) = @_;
|
||||
my $self = Animal::new($class, %args);
|
||||
return $self;
|
||||
}
|
||||
|
||||
sub fetch {
|
||||
my ($self, $item) = @_;
|
||||
return "Fetched $item";
|
||||
}
|
||||
|
||||
sub bark {
|
||||
my ($self) = @_;
|
||||
print $self->speak() . "\n";
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
require 'json'
|
||||
|
||||
module Auth
|
||||
class User
|
||||
attr_accessor :id, :name, :email
|
||||
|
||||
def initialize(id, name, email)
|
||||
@id = id
|
||||
@name = name
|
||||
@email = email
|
||||
end
|
||||
|
||||
def to_s
|
||||
"User(#{@id}, #{@name})"
|
||||
end
|
||||
end
|
||||
|
||||
class UserRepository
|
||||
def initialize
|
||||
@users = {}
|
||||
end
|
||||
|
||||
def find_by_id(id)
|
||||
@users[id]
|
||||
end
|
||||
|
||||
def save(user)
|
||||
@users[user.id] = user
|
||||
puts "Saved #{user}"
|
||||
end
|
||||
|
||||
def create_user(name, email)
|
||||
user = User.new(@users.size + 1, name, email)
|
||||
save(user)
|
||||
user
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,79 @@
|
||||
// sample.res - Comprehensive ReScript test fixture
|
||||
// Exercises modules, nested modules, let/rec, externals, types, opens,
|
||||
// decorators, function calls, and test-style bindings.
|
||||
|
||||
open Belt
|
||||
include Js.Promise
|
||||
open Belt
|
||||
|
||||
// Module alias (re-export)
|
||||
module IntMap = Belt.Map.Int
|
||||
|
||||
// JS-binding module: only types + externals, should be tagged js_binding
|
||||
module TextEncoder = {
|
||||
type encoder
|
||||
@new external newTextEncoder: unit => encoder = "TextEncoder"
|
||||
@send external encode: (encoder, string) => array<int> = "encode"
|
||||
}
|
||||
|
||||
// Top-level type definition
|
||||
type status = Active | Inactive | Pending
|
||||
|
||||
// Top-level type alias with polymorphic parameter
|
||||
type result<'a> = Ok('a) | Err(string)
|
||||
|
||||
// Top-level let binding
|
||||
let defaultTimeout = 5000
|
||||
|
||||
// let rec + and chain
|
||||
let rec fact = n => n <= 1 ? 1 : n * fact(n - 1)
|
||||
and helper = x => fact(x) + 1
|
||||
|
||||
// External binding with decorator
|
||||
@module("fs") external readFile: string => string = "readFileSync"
|
||||
@val external consoleLog: string => unit = "console.log"
|
||||
|
||||
// Nested module
|
||||
module User = {
|
||||
type t = {name: string, age: int, status: status}
|
||||
|
||||
let make = (~name, ~age) => {name, age, status: Active}
|
||||
|
||||
let greet = (user: t) => consoleLog("Hello " ++ user.name)
|
||||
|
||||
// Nested sub-module
|
||||
module Validator = {
|
||||
let isAdult = (user: t) => user.age >= 18
|
||||
let hasName = (user: t) => user.name != ""
|
||||
}
|
||||
}
|
||||
|
||||
// Another top-level module using the previous one
|
||||
module App = {
|
||||
let start = () => {
|
||||
let u = User.make(~name="Ada", ~age=36)
|
||||
User.greet(u)
|
||||
let valid = User.Validator.isAdult(u)
|
||||
consoleLog(valid ? "ok" : "nope")
|
||||
}
|
||||
}
|
||||
|
||||
// Top-level function calling into modules
|
||||
let main = () => {
|
||||
App.start()
|
||||
let n = fact(5)
|
||||
consoleLog(Belt.Int.toString(n))
|
||||
}
|
||||
|
||||
// JSX rendering — component references across modules
|
||||
let render = () =>
|
||||
<Layout>
|
||||
<User.Badge name="Ada" />
|
||||
<AnalyticsFilterUi.Filter filter="amount" />
|
||||
</Layout>
|
||||
|
||||
// Test-style function (rescript-test convention)
|
||||
let test_fact_base = () => {
|
||||
let r = fact(1)
|
||||
assert(r == 1)
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/* sample.resi - ReScript interface file fixture.
|
||||
Only signatures — no expression bodies. */
|
||||
|
||||
type status = Active | Inactive | Pending
|
||||
|
||||
type result<'a> = Ok('a) | Err(string)
|
||||
|
||||
let defaultTimeout: int
|
||||
|
||||
let fact: int => int
|
||||
|
||||
module User: {
|
||||
type t
|
||||
let make: (~name: string, ~age: int) => t
|
||||
let greet: t => unit
|
||||
|
||||
module Validator: {
|
||||
let isAdult: t => bool
|
||||
let hasName: t => bool
|
||||
}
|
||||
}
|
||||
|
||||
module App: {
|
||||
let start: unit => unit
|
||||
}
|
||||
|
||||
external readFile: string => string = "readFileSync"
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.example.auth
|
||||
|
||||
import scala.collection.mutable
|
||||
import scala.collection.mutable.{HashMap, ListBuffer}
|
||||
import scala.util.Try
|
||||
import scala.concurrent._
|
||||
|
||||
trait Repository[T]:
|
||||
def findById(id: Int): Option[T]
|
||||
def save(entity: T): Unit
|
||||
|
||||
case class User(id: Int, name: String, email: String)
|
||||
|
||||
class InMemoryRepo extends Repository[User] with Serializable:
|
||||
private val users = mutable.HashMap[Int, User]()
|
||||
|
||||
override def findById(id: Int): Option[User] =
|
||||
users.get(id)
|
||||
|
||||
override def save(user: User): Unit =
|
||||
users.put(user.id, user)
|
||||
println(s"Saved user ${user.id}")
|
||||
|
||||
class UserService(repo: Repository[User]):
|
||||
def createUser(name: String, email: String): User =
|
||||
val user = User(1, name, email)
|
||||
repo.save(user)
|
||||
user
|
||||
|
||||
def getUser(id: Int): Option[User] =
|
||||
repo.findById(id)
|
||||
|
||||
object UserService:
|
||||
def apply(repo: Repository[User]): UserService = new UserService(repo)
|
||||
|
||||
enum Color:
|
||||
case Red, Green, Blue
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
#!/bin/bash
|
||||
# Sample shell script exercising the bash parser.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
source ./sample_lib.sh
|
||||
. ./sample_config.sh
|
||||
|
||||
readonly DATA_DIR="/tmp/crg-example"
|
||||
|
||||
log_info() {
|
||||
local msg="$1"
|
||||
echo "[INFO] $msg"
|
||||
}
|
||||
|
||||
log_error() {
|
||||
local msg="$1"
|
||||
echo "[ERROR] $msg" >&2
|
||||
}
|
||||
|
||||
ensure_dir() {
|
||||
local dir="$1"
|
||||
if [ ! -d "$dir" ]; then
|
||||
mkdir -p "$dir"
|
||||
log_info "created $dir"
|
||||
fi
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
rm -rf "$DATA_DIR"
|
||||
log_info "cleaned up $DATA_DIR"
|
||||
}
|
||||
|
||||
main() {
|
||||
log_info "starting"
|
||||
ensure_dir "$DATA_DIR"
|
||||
# Simulate some work
|
||||
echo "processing" > "$DATA_DIR/status"
|
||||
cleanup
|
||||
log_info "done"
|
||||
}
|
||||
|
||||
main "$@"
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
|
||||
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||
import {IERC20, IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
|
||||
|
||||
// ─── Protocol constants ─────────────────────────────────────────────────────
|
||||
|
||||
uint256 constant MAX_SUPPLY = 1_000_000_000 ether;
|
||||
address constant ZERO_ADDRESS = address(0);
|
||||
|
||||
// ─── Types ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/// @notice Staker position tracked per epoch.
|
||||
struct StakerPosition {
|
||||
address wallet;
|
||||
uint256 stakedAmount;
|
||||
uint256 rewardDebt;
|
||||
uint64 epochJoined;
|
||||
bool isActive;
|
||||
}
|
||||
|
||||
/// @notice Pool lifecycle.
|
||||
enum PoolStatus {
|
||||
Active,
|
||||
Paused,
|
||||
Deprecated,
|
||||
EmergencyShutdown
|
||||
}
|
||||
|
||||
/// @notice 18-decimal fixed-point price.
|
||||
type Price is uint256;
|
||||
|
||||
/// @notice Position receipt NFT identifier.
|
||||
type PositionId is uint128;
|
||||
|
||||
// ─── Errors ─────────────────────────────────────────────────────────────────
|
||||
|
||||
error InsufficientStake(uint256 requested, uint256 available);
|
||||
error PoolNotActive();
|
||||
|
||||
// ─── Events ─────────────────────────────────────────────────────────────────
|
||||
|
||||
event Staked(address indexed user, uint256 amount);
|
||||
event Unstaked(address indexed user, uint256 amount);
|
||||
|
||||
// ─── Helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
/// @notice 30 bp protocol fee.
|
||||
function protocolFee(uint256 amount) pure returns (uint256) {
|
||||
return (amount * 30) / 10_000;
|
||||
}
|
||||
|
||||
// ─── Interface ──────────────────────────────────────────────────────────────
|
||||
|
||||
interface IStakingPool {
|
||||
function stake(uint256 amount) external;
|
||||
function unstake(uint256 amount) external returns (uint256);
|
||||
function stakedBalance(address user) external view returns (uint256);
|
||||
}
|
||||
|
||||
// ─── Library ────────────────────────────────────────────────────────────────
|
||||
|
||||
/// @notice Fixed-point math for reward accumulator precision.
|
||||
library RewardMath {
|
||||
uint256 internal constant PRECISION = 1e18;
|
||||
|
||||
function mulPrecise(uint256 a, uint256 b) internal pure returns (uint256) {
|
||||
return (a * b) / PRECISION;
|
||||
}
|
||||
|
||||
function divPrecise(uint256 a, uint256 b) internal pure returns (uint256) {
|
||||
require(b > 0, "RewardMath: division by zero");
|
||||
return (a * PRECISION) / b;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Core pool ──────────────────────────────────────────────────────────────
|
||||
|
||||
/// @title StakingVault
|
||||
/// @notice Liquid staking pool. Deposit the underlying ERC-20, receive
|
||||
/// share tokens 1 : 1, accrue rewards over time.
|
||||
contract StakingVault is ERC20, Ownable, IStakingPool {
|
||||
using RewardMath for uint256;
|
||||
|
||||
// ── Storage ────────────────────────────────────────────────────────
|
||||
|
||||
mapping(address => uint256) public stakes;
|
||||
uint256 public totalStaked;
|
||||
address public guardian;
|
||||
PoolStatus public status;
|
||||
uint256 constant MIN_STAKE = 0.01 ether;
|
||||
uint256 immutable launchTime;
|
||||
Price public assetPrice;
|
||||
uint256 public accRewardPerShare;
|
||||
|
||||
// ── Events ─────────────────────────────────────────────────────────
|
||||
|
||||
event RewardAccrued(uint256 indexed epoch, uint256 amount);
|
||||
event EmergencyExit(address indexed user, uint256 amount);
|
||||
|
||||
// ── Modifiers ──────────────────────────────────────────────────────
|
||||
|
||||
modifier nonZero(uint256 amount) {
|
||||
require(amount > 0, "StakingVault: zero amount");
|
||||
_;
|
||||
}
|
||||
|
||||
modifier whenPoolActive() {
|
||||
require(status == PoolStatus.Active, "StakingVault: pool not active");
|
||||
_;
|
||||
}
|
||||
|
||||
// ── Constructor ────────────────────────────────────────────────────
|
||||
|
||||
constructor(
|
||||
string memory name,
|
||||
string memory symbol
|
||||
) ERC20(name, symbol) Ownable(msg.sender) {
|
||||
guardian = msg.sender;
|
||||
launchTime = block.timestamp;
|
||||
status = PoolStatus.Active;
|
||||
}
|
||||
|
||||
// ── Core operations ────────────────────────────────────────────────
|
||||
|
||||
/// @inheritdoc IStakingPool
|
||||
function stake(uint256 amount)
|
||||
external
|
||||
override
|
||||
nonZero(amount)
|
||||
whenPoolActive
|
||||
{
|
||||
uint256 fee = protocolFee(amount);
|
||||
uint256 net = amount - fee;
|
||||
|
||||
stakes[msg.sender] += net;
|
||||
totalStaked += net;
|
||||
|
||||
_mint(msg.sender, net);
|
||||
emit Staked(msg.sender, net);
|
||||
}
|
||||
|
||||
/// @inheritdoc IStakingPool
|
||||
function unstake(uint256 amount)
|
||||
external
|
||||
override
|
||||
nonZero(amount)
|
||||
returns (uint256)
|
||||
{
|
||||
uint256 staked = stakes[msg.sender];
|
||||
if (staked < amount) {
|
||||
revert InsufficientStake(amount, staked);
|
||||
}
|
||||
|
||||
stakes[msg.sender] = staked - amount;
|
||||
totalStaked -= amount;
|
||||
|
||||
_burn(msg.sender, amount);
|
||||
emit Unstaked(msg.sender, amount);
|
||||
return amount;
|
||||
}
|
||||
|
||||
/// @inheritdoc IStakingPool
|
||||
function stakedBalance(address user) external view returns (uint256) {
|
||||
return stakes[user];
|
||||
}
|
||||
|
||||
// ── Emergency ──────────────────────────────────────────────────────
|
||||
|
||||
function emergencyWithdraw() external nonZero(stakes[msg.sender]) {
|
||||
uint256 amount = stakes[msg.sender];
|
||||
stakes[msg.sender] = 0;
|
||||
totalStaked -= amount;
|
||||
|
||||
_burn(msg.sender, amount);
|
||||
emit EmergencyExit(msg.sender, amount);
|
||||
}
|
||||
|
||||
// ── ETH handling (native staking variant) ──────────────────────────
|
||||
|
||||
receive() external payable {}
|
||||
fallback() external payable {}
|
||||
}
|
||||
|
||||
// ─── Boosted pool ───────────────────────────────────────────────────────────
|
||||
|
||||
/// @title BoostedPool
|
||||
/// @notice Wraps StakingVault with an additional reward layer.
|
||||
/// Depositors earn base yield from the vault plus bonus
|
||||
/// rewards funded by governance.
|
||||
contract BoostedPool is StakingVault {
|
||||
uint256 public bonusRate;
|
||||
|
||||
event BonusClaimed(address indexed user, uint256 reward);
|
||||
|
||||
constructor(
|
||||
string memory name,
|
||||
string memory symbol,
|
||||
uint256 _bonusRate
|
||||
) StakingVault(name, symbol) {
|
||||
bonusRate = _bonusRate;
|
||||
}
|
||||
|
||||
function pendingBonus(address user) public view returns (uint256) {
|
||||
if (totalStaked == 0) return 0;
|
||||
return stakes[user].mulPrecise(bonusRate);
|
||||
}
|
||||
|
||||
function claimBonus() external {
|
||||
uint256 reward = pendingBonus(msg.sender);
|
||||
require(reward > 0, "BoostedPool: nothing to claim");
|
||||
|
||||
_mint(msg.sender, reward);
|
||||
emit BonusClaimed(msg.sender, reward);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
-- Sample SQL fixture for code-review-graph parser tests
|
||||
|
||||
CREATE TABLE users (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
email TEXT UNIQUE
|
||||
);
|
||||
|
||||
CREATE TABLE orders (
|
||||
id INTEGER PRIMARY KEY,
|
||||
user_id INTEGER REFERENCES users(id),
|
||||
total NUMERIC(10, 2),
|
||||
created_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE VIEW active_orders AS
|
||||
SELECT o.id, u.name, o.total
|
||||
FROM orders o
|
||||
JOIN users u ON u.id = o.user_id
|
||||
WHERE o.total > 0;
|
||||
|
||||
CREATE FUNCTION get_user_total(p_user_id INTEGER)
|
||||
RETURNS NUMERIC AS $$
|
||||
SELECT SUM(total)
|
||||
FROM orders
|
||||
WHERE user_id = p_user_id;
|
||||
$$ LANGUAGE sql;
|
||||
|
||||
CREATE OR REPLACE PROCEDURE archive_old_orders(cutoff_date DATE)
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
INSERT INTO orders_archive
|
||||
SELECT * FROM orders WHERE created_at < cutoff_date;
|
||||
|
||||
DELETE FROM orders WHERE created_at < cutoff_date;
|
||||
END;
|
||||
$$;
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
// sample.sv - SystemVerilog fixture for parser tests
|
||||
`timescale 1ns / 1ps
|
||||
|
||||
// File-level package import
|
||||
import utils_pkg::*;
|
||||
|
||||
// Interface declaration
|
||||
interface BusIf #(parameter int WIDTH = 8);
|
||||
logic [WIDTH-1:0] data;
|
||||
logic valid;
|
||||
logic ready;
|
||||
modport master(output data, valid, input ready);
|
||||
modport slave(input data, valid, output ready);
|
||||
endinterface
|
||||
|
||||
// Submodule to be instantiated by FIFOController
|
||||
module Adder #(parameter int WIDTH = 8) (input logic [WIDTH-1:0] a, b, output logic [WIDTH-1:0] sum);
|
||||
assign sum = a + b;
|
||||
endmodule
|
||||
|
||||
// Main module with tasks, functions, always blocks, and module instantiation
|
||||
// Parameters on one line to avoid grammar parse errors
|
||||
module FIFOController #(parameter int DEPTH = 16, parameter int WIDTH = 8) (
|
||||
input logic clk,
|
||||
input logic rst_n,
|
||||
input logic [WIDTH-1:0] data_in,
|
||||
input logic wr_en,
|
||||
input logic rd_en,
|
||||
output logic [WIDTH-1:0] data_out,
|
||||
output logic full,
|
||||
output logic empty
|
||||
);
|
||||
|
||||
// Intra-module package import
|
||||
import arith_pkg::counter_t;
|
||||
|
||||
logic [WIDTH-1:0] mem [0:DEPTH-1];
|
||||
logic [$clog2(DEPTH):0] wr_ptr, rd_ptr, count;
|
||||
|
||||
// Module instantiation - creates CALLS edge from FIFOController to Adder
|
||||
Adder #(.WIDTH(WIDTH)) ptr_adder (.a(wr_ptr[WIDTH-1:0]), .b(rd_ptr[WIDTH-1:0]), .sum());
|
||||
|
||||
// Task declaration
|
||||
task automatic do_write(input logic [WIDTH-1:0] din);
|
||||
mem[wr_ptr] <= din;
|
||||
wr_ptr <= wr_ptr + 1;
|
||||
count <= count + 1;
|
||||
endtask
|
||||
|
||||
// Function declaration
|
||||
function automatic logic is_full();
|
||||
return (count >= DEPTH);
|
||||
endfunction
|
||||
|
||||
// Always block (sequential logic) - flattened to avoid nested begin/end
|
||||
// grammar limitation: if(x) begin..end inside else begin..end causes parse errors
|
||||
always_ff @(posedge clk or negedge rst_n) begin
|
||||
if (!rst_n) begin
|
||||
wr_ptr <= 0;
|
||||
rd_ptr <= 0;
|
||||
count <= 0;
|
||||
end
|
||||
if (rst_n && wr_en && !full) do_write(data_in);
|
||||
if (rst_n && rd_en && !empty) begin
|
||||
data_out <= mem[rd_ptr];
|
||||
rd_ptr <= rd_ptr + 1;
|
||||
count <= count - 1;
|
||||
end
|
||||
end
|
||||
|
||||
// Always block (combinational logic)
|
||||
always_comb begin
|
||||
full = is_full();
|
||||
empty = (count == 0);
|
||||
end
|
||||
|
||||
endmodule
|
||||
@@ -0,0 +1,78 @@
|
||||
import Foundation
|
||||
|
||||
protocol UserRepository {
|
||||
func findById(_ id: Int) -> User?
|
||||
func save(_ user: User)
|
||||
}
|
||||
|
||||
struct User {
|
||||
let id: Int
|
||||
let name: String
|
||||
let email: String
|
||||
}
|
||||
|
||||
class InMemoryRepo: UserRepository {
|
||||
private var users: [Int: User] = [:]
|
||||
|
||||
init(seed: [User]) {
|
||||
for user in seed {
|
||||
save(user)
|
||||
}
|
||||
}
|
||||
|
||||
convenience init() {
|
||||
self.init(seed: [])
|
||||
}
|
||||
|
||||
deinit {
|
||||
users.removeAll()
|
||||
}
|
||||
|
||||
subscript(id: Int) -> User? {
|
||||
return findById(id)
|
||||
}
|
||||
|
||||
func findById(_ id: Int) -> User? {
|
||||
return users[id]
|
||||
}
|
||||
|
||||
func save(_ user: User) {
|
||||
users[user.id] = user
|
||||
print("Saved user \(user.id)")
|
||||
}
|
||||
}
|
||||
|
||||
enum Direction: String {
|
||||
case north
|
||||
case south
|
||||
case east
|
||||
case west
|
||||
}
|
||||
|
||||
actor DataStore {
|
||||
private var cache: [String: User] = [:]
|
||||
|
||||
func get(_ key: String) -> User? {
|
||||
return cache[key]
|
||||
}
|
||||
|
||||
func set(_ key: String, user: User) {
|
||||
cache[key] = user
|
||||
}
|
||||
}
|
||||
|
||||
extension InMemoryRepo: CustomStringConvertible {
|
||||
var description: String {
|
||||
return "InMemoryRepo with \(users.count) users"
|
||||
}
|
||||
|
||||
func clear() {
|
||||
users.removeAll()
|
||||
}
|
||||
}
|
||||
|
||||
func createUser(repo: UserRepository, name: String, email: String) -> User {
|
||||
let user = User(id: 1, name: name, email: email)
|
||||
repo.save(user)
|
||||
return user
|
||||
}
|
||||
+255
@@ -0,0 +1,255 @@
|
||||
# Sample Terraform configuration exercising the HCL parser.
|
||||
#
|
||||
# Covers: resources, data sources, modules, variables, outputs, locals,
|
||||
# providers, the terraform block, cross-resource references, variable
|
||||
# references, local references, data source references, depends_on,
|
||||
# lifecycle blocks, template interpolations, function call arguments,
|
||||
# built-in namespace objects, and dynamic blocks.
|
||||
|
||||
terraform {
|
||||
required_providers {
|
||||
aws = {
|
||||
source = "hashicorp/aws"
|
||||
version = "~> 5.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
provider "aws" {
|
||||
region = var.region
|
||||
}
|
||||
|
||||
variable "region" {
|
||||
type = string
|
||||
default = "us-east-1"
|
||||
}
|
||||
|
||||
variable "instance_type" {
|
||||
type = string
|
||||
default = "t2.micro"
|
||||
}
|
||||
|
||||
locals {
|
||||
name_prefix = "myapp"
|
||||
full_name = "${local.name_prefix}-web"
|
||||
}
|
||||
|
||||
resource "aws_vpc" "main" {
|
||||
cidr_block = "10.0.0.0/16"
|
||||
|
||||
tags = {
|
||||
Name = local.full_name
|
||||
}
|
||||
}
|
||||
|
||||
resource "aws_instance" "web" {
|
||||
ami = data.aws_ami.ubuntu.id
|
||||
instance_type = var.instance_type
|
||||
subnet_id = aws_subnet.main.id
|
||||
|
||||
tags = {
|
||||
Name = local.full_name
|
||||
}
|
||||
|
||||
depends_on = [aws_vpc.main]
|
||||
}
|
||||
|
||||
resource "aws_subnet" "main" {
|
||||
vpc_id = aws_vpc.main.id
|
||||
cidr_block = "10.0.1.0/24"
|
||||
}
|
||||
|
||||
data "aws_ami" "ubuntu" {
|
||||
most_recent = true
|
||||
|
||||
filter {
|
||||
name = "name"
|
||||
values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
|
||||
}
|
||||
|
||||
owners = ["099720109477"]
|
||||
}
|
||||
|
||||
module "security" {
|
||||
source = "./modules/security"
|
||||
|
||||
vpc_id = aws_vpc.main.id
|
||||
environment = "production"
|
||||
}
|
||||
|
||||
output "instance_ip" {
|
||||
value = aws_instance.web.public_ip
|
||||
description = "The public IP of the web instance"
|
||||
}
|
||||
|
||||
output "vpc_id" {
|
||||
value = aws_vpc.main.id
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Variable reference inside a function call argument (count = length(var.x))
|
||||
# and inside an index expression (var.x[count.index]). count.index is a
|
||||
# block-local meta-argument and must not produce a REFERENCES edge.
|
||||
# ---------------------------------------------------------------------------
|
||||
variable "subnet_ids" {
|
||||
type = list(string)
|
||||
}
|
||||
|
||||
resource "aws_instance" "fleet" {
|
||||
count = length(var.subnet_ids)
|
||||
subnet_id = var.subnet_ids[count.index]
|
||||
instance_type = var.instance_type
|
||||
|
||||
tags = {
|
||||
Name = "fleet-${count.index}"
|
||||
}
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Resource-to-resource for_each chaining. The 'each' iterator is block-local
|
||||
# and must not produce a REFERENCES edge.
|
||||
# ---------------------------------------------------------------------------
|
||||
resource "aws_internet_gateway" "gw" {
|
||||
for_each = aws_vpc.main
|
||||
vpc_id = each.value.id
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Variable reference inside a template string interpolation ("${var.x}").
|
||||
# ---------------------------------------------------------------------------
|
||||
resource "aws_s3_bucket" "static" {
|
||||
bucket = "${var.region}-static-assets"
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Terraform built-in namespace objects (path.module, terraform.workspace)
|
||||
# are not resource references and must not produce REFERENCES edges.
|
||||
# ---------------------------------------------------------------------------
|
||||
resource "aws_s3_bucket" "tfstate" {
|
||||
bucket = "tfstate-${terraform.workspace}"
|
||||
|
||||
tags = {
|
||||
Module = path.module
|
||||
}
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Reference inside a lifecycle nested block (replace_triggered_by).
|
||||
# ---------------------------------------------------------------------------
|
||||
resource "aws_autoscaling_group" "web" {
|
||||
min_size = 1
|
||||
max_size = 3
|
||||
|
||||
lifecycle {
|
||||
replace_triggered_by = [aws_launch_template.web.id]
|
||||
}
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Dynamic block with default iterator name ('ingress' = block label).
|
||||
# The for_each variable reference must be extracted; references to
|
||||
# ingress.value.* inside the content block must not produce edges.
|
||||
# ---------------------------------------------------------------------------
|
||||
variable "ingress_rules" {
|
||||
type = list(object({
|
||||
from_port = number
|
||||
to_port = number
|
||||
protocol = string
|
||||
}))
|
||||
}
|
||||
|
||||
resource "aws_security_group" "main" {
|
||||
vpc_id = aws_vpc.main.id
|
||||
|
||||
dynamic "ingress" {
|
||||
for_each = var.ingress_rules
|
||||
content {
|
||||
from_port = ingress.value.from_port
|
||||
to_port = ingress.value.to_port
|
||||
protocol = ingress.value.protocol
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Dynamic block with default iterator name ('setting' = block label).
|
||||
# References to setting.value[...] inside the content block must not
|
||||
# produce REFERENCES edges; var.settings and the resource reference on
|
||||
# 'application' must be extracted.
|
||||
# ---------------------------------------------------------------------------
|
||||
variable "settings" {
|
||||
type = list(object({
|
||||
namespace = string
|
||||
name = string
|
||||
value = string
|
||||
}))
|
||||
}
|
||||
|
||||
resource "aws_elastic_beanstalk_environment" "tfenvtest" {
|
||||
name = "tf-test-name"
|
||||
application = aws_elastic_beanstalk_application.tftest.name
|
||||
|
||||
dynamic "setting" {
|
||||
for_each = var.settings
|
||||
content {
|
||||
namespace = setting.value["namespace"]
|
||||
name = setting.value["name"]
|
||||
value = setting.value["value"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Dynamic block with a custom iterator name set via the 'iterator' argument
|
||||
# ('srv' overrides the default 'condition' label). References to
|
||||
# srv.value[...] inside the content block must not produce REFERENCES edges;
|
||||
# var.server_list must be extracted.
|
||||
# ---------------------------------------------------------------------------
|
||||
variable "server_list" {
|
||||
type = list(object({
|
||||
port = number
|
||||
protocol = string
|
||||
}))
|
||||
}
|
||||
|
||||
resource "aws_lb_listener_rule" "hosts" {
|
||||
dynamic "condition" {
|
||||
for_each = var.server_list
|
||||
iterator = srv
|
||||
content {
|
||||
host_header {
|
||||
values = [srv.value["port"]]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Multi-level nested dynamic blocks. Each level introduces its own iterator
|
||||
# symbol (origin_group, origin). Only var.load_balancer_origin_groups must
|
||||
# produce a REFERENCES edge; all iterator references (origin_group.key,
|
||||
# origin_group.value.origins, origin.value.hostname) must be suppressed.
|
||||
# ---------------------------------------------------------------------------
|
||||
variable "load_balancer_origin_groups" {
|
||||
type = map(object({
|
||||
origins = set(object({
|
||||
hostname = string
|
||||
}))
|
||||
}))
|
||||
}
|
||||
|
||||
resource "aws_cloudfront_distribution" "cdn" {
|
||||
dynamic "origin_group" {
|
||||
for_each = var.load_balancer_origin_groups
|
||||
content {
|
||||
name = origin_group.key
|
||||
|
||||
dynamic "origin" {
|
||||
for_each = origin_group.value.origins
|
||||
content {
|
||||
hostname = origin.value.hostname
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
#include "EXTERN.h"
|
||||
#include "perl.h"
|
||||
#include "XSUB.h"
|
||||
#include <string.h>
|
||||
|
||||
typedef struct {
|
||||
int x;
|
||||
int y;
|
||||
} Point;
|
||||
|
||||
static int
|
||||
_add(int a, int b) {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
static double
|
||||
compute_distance(int x1, int y1, int x2, int y2) {
|
||||
int dx = x2 - x1;
|
||||
int dy = y2 - y1;
|
||||
return _add(dx * dx, dy * dy);
|
||||
}
|
||||
|
||||
MODULE = MyModule PACKAGE = MyModule
|
||||
|
||||
int
|
||||
add(a, b)
|
||||
int a
|
||||
int b
|
||||
CODE:
|
||||
RETVAL = _add(a, b);
|
||||
OUTPUT:
|
||||
RETVAL
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, it, test, expect, beforeEach } from 'bun:test';
|
||||
import { UserRepository, UserService } from './sample_typescript';
|
||||
|
||||
describe('UserService (bun)', () => {
|
||||
let repo: UserRepository;
|
||||
|
||||
beforeEach(() => {
|
||||
repo = new UserRepository();
|
||||
});
|
||||
|
||||
it('constructs a service with a repository', () => {
|
||||
const service = new UserService();
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
it('finds a user by id', () => {
|
||||
const service = new UserService();
|
||||
const user = service.getUser(123);
|
||||
expect(user).toBeUndefined();
|
||||
});
|
||||
|
||||
test('creates a user via the service', () => {
|
||||
const service = new UserService();
|
||||
const created = service.createUser('alice', '[email protected]');
|
||||
expect(created.name).toBe('alice');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Fixture for issue #363: function references in callback positions.
|
||||
|
||||
Each `*_callback` function is passed as a bare-identifier argument to
|
||||
another call. They are never invoked with parens, so without REFERENCES
|
||||
edge tracking they would be flagged as dead code.
|
||||
"""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
|
||||
def executor_callback():
|
||||
return "submitted"
|
||||
|
||||
|
||||
def filter_callback(item):
|
||||
return item > 0
|
||||
|
||||
|
||||
def map_callback(item):
|
||||
return item * 2
|
||||
|
||||
|
||||
def trigger_executor():
|
||||
with ThreadPoolExecutor() as executor:
|
||||
future = executor.submit(executor_callback)
|
||||
return future
|
||||
|
||||
|
||||
def trigger_filter():
|
||||
items = [1, -2, 3, -4]
|
||||
return list(filter(filter_callback, items))
|
||||
|
||||
|
||||
def trigger_map():
|
||||
items = [1, 2, 3]
|
||||
return list(map(map_callback, items))
|
||||
@@ -0,0 +1,37 @@
|
||||
# Databricks notebook source
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def load_config():
|
||||
return {"env": os.getenv("ENV", "dev")}
|
||||
|
||||
# COMMAND ----------
|
||||
|
||||
# MAGIC %sql
|
||||
# MAGIC SELECT * FROM bronze.events
|
||||
# MAGIC JOIN silver.users ON events.user_id = users.id
|
||||
|
||||
# COMMAND ----------
|
||||
|
||||
# MAGIC %r
|
||||
# MAGIC summarize_data <- function(df) {
|
||||
# MAGIC summary(df)
|
||||
# MAGIC }
|
||||
|
||||
# COMMAND ----------
|
||||
|
||||
# MAGIC %md
|
||||
# MAGIC ## Analysis Notes
|
||||
# MAGIC This section documents the analysis.
|
||||
|
||||
# COMMAND ----------
|
||||
|
||||
def process_events(config):
|
||||
path = Path(config["env"])
|
||||
return load_config()
|
||||
|
||||
# COMMAND ----------
|
||||
|
||||
# MAGIC %sql
|
||||
# MAGIC CREATE TABLE gold.summary AS SELECT * FROM silver.processed
|
||||
@@ -0,0 +1,59 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": ["# Databricks Notebook"],
|
||||
"metadata": {}
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": ["%python\n", "def transform_data(df):\n", " return df.dropna()\n"],
|
||||
"metadata": {},
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": ["%sql\n", "SELECT * FROM catalog.schema.raw_data\n", "JOIN catalog.schema.lookup ON raw_data.id = lookup.id\n"],
|
||||
"metadata": {},
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": ["%r\n", "clean_data <- function(x) {\n", " na.omit(x)\n", "}\n"],
|
||||
"metadata": {},
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": ["%scala\n", "val x = 1\n"],
|
||||
"metadata": {},
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": ["%md\n", "## Results section\n"],
|
||||
"metadata": {},
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": ["def process_results(data):\n", " result = transform_data(data)\n", " return result\n"],
|
||||
"metadata": {},
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": ["%sql\n", "CREATE TABLE catalog.schema.output AS SELECT * FROM catalog.schema.raw_data\n"],
|
||||
"metadata": {},
|
||||
"outputs": []
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"language": "python",
|
||||
"display_name": "Python 3"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/* Fixture for testing C/C++ dead-guard detection on CALLS edges.
|
||||
*
|
||||
* #if 0 / #elif 0 blocks are dead code -- calls inside them should be
|
||||
* omitted, even when a function definition sits inside the block.
|
||||
* #else and #elif branches of #if 0 are live -- their calls are kept.
|
||||
*/
|
||||
|
||||
extern void live_helper(void);
|
||||
extern void dead_in_if0(void);
|
||||
extern void live_in_else(void);
|
||||
extern void dead_in_elifblock(void);
|
||||
extern void live_in_elif(void);
|
||||
extern void dead_in_wrapped(void);
|
||||
extern void live_in_if1(void);
|
||||
extern void dead_in_elif0(void);
|
||||
|
||||
/* #if 0 wrapping a whole function: the preprocessor removes the
|
||||
* function entirely, so the call inside it is dead too. */
|
||||
#if 0
|
||||
void dead_wrapped_func(void) {
|
||||
dead_in_wrapped(); /* dead -- function is inside #if 0 */
|
||||
}
|
||||
#endif
|
||||
|
||||
void caller(void) {
|
||||
live_helper(); /* live -- no guard */
|
||||
|
||||
#if 0
|
||||
dead_in_if0(); /* dead -- inside #if 0 */
|
||||
#else
|
||||
live_in_else(); /* live -- #else of #if 0 */
|
||||
#endif
|
||||
|
||||
#if 0
|
||||
dead_in_elifblock(); /* dead -- inside #if 0 (elif form) */
|
||||
#elif 1
|
||||
live_in_elif(); /* live -- #elif of #if 0 (regression guard) */
|
||||
#endif
|
||||
|
||||
#if 1
|
||||
live_in_if1(); /* live -- #if 1 is taken */
|
||||
#elif 0
|
||||
dead_in_elif0(); /* dead -- inside #elif 0 */
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package main
|
||||
|
||||
// Fixture for testing Go dead-guard detection on CALLS edges.
|
||||
//
|
||||
// Go's if_statement shares the same tree-sitter node type as Python's,
|
||||
// and Go's `false` literal shares the same node type. The existing
|
||||
// _eval_static_dead_cond already handles cond.type == "false", so Go
|
||||
// dead guards are detected by the same code path as Python.
|
||||
//
|
||||
// Patterns tested:
|
||||
// if false { dead() } -- consequence is dead
|
||||
// if false { } else { live() } -- else branch is live
|
||||
|
||||
func live_helper() {}
|
||||
|
||||
func dead_false_call() {}
|
||||
|
||||
func live_in_else() {}
|
||||
|
||||
func dead_in_consequence() {}
|
||||
|
||||
func live_final_else() {}
|
||||
|
||||
func live_in_wrapped() {}
|
||||
|
||||
func caller() {
|
||||
live_helper() // live -- no guard
|
||||
|
||||
if false {
|
||||
dead_false_call() // dead consequence
|
||||
}
|
||||
}
|
||||
|
||||
func else_branch() {
|
||||
// Calls in the else branch of if false are live.
|
||||
if false {
|
||||
dead_in_consequence() // dead consequence
|
||||
} else {
|
||||
live_in_else() // live -- else branch
|
||||
}
|
||||
}
|
||||
|
||||
func dead_wrapped_func() {
|
||||
// A whole function definition is NOT inside if false in Go
|
||||
// (Go forbids func declarations inside if blocks), so this
|
||||
// call stays live -- it is at module scope.
|
||||
live_in_wrapped() // live -- func def is at module scope, not guarded
|
||||
}
|
||||
|
||||
func some_condition() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func elif_chain() {
|
||||
// Go has no elif, but chained if-else-if achieves the same.
|
||||
// Only the if-false consequence is dead; the else branch is live.
|
||||
if false {
|
||||
dead_in_consequence() // dead
|
||||
} else {
|
||||
if some_condition() {
|
||||
live_final_else() // live
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func live_in_if_true() {}
|
||||
|
||||
func true_guard() {
|
||||
// if true is NOT a dead guard -- the consequence is live.
|
||||
if true {
|
||||
live_in_if_true() // live -- true is not a dead guard
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// Fixture for testing TypeScript/JavaScript dead-guard detection.
|
||||
//
|
||||
// Both TS and JS share the same tree-sitter if_statement node type.
|
||||
// The condition is wrapped in parenthesized_expression, which must be
|
||||
// unwrapped before checking for false/0 literals.
|
||||
|
||||
function live_helper(): void {}
|
||||
|
||||
function dead_false_call(): void {}
|
||||
|
||||
function dead_zero_call(): void {}
|
||||
|
||||
function live_in_else(): void {}
|
||||
|
||||
function dead_in_consequence(): void {}
|
||||
|
||||
function live_final_else(): void {}
|
||||
|
||||
function live_in_if_true(): void {}
|
||||
|
||||
function some_condition(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
function caller(): void {
|
||||
live_helper(); // live -- no guard
|
||||
|
||||
if (false) {
|
||||
dead_false_call(); // dead consequence
|
||||
}
|
||||
}
|
||||
|
||||
function zero_guard(): void {
|
||||
if (0) {
|
||||
dead_zero_call(); // dead consequence -- 0 is falsy
|
||||
}
|
||||
}
|
||||
|
||||
function else_branch(): void {
|
||||
if (false) {
|
||||
dead_in_consequence(); // dead consequence
|
||||
} else {
|
||||
live_in_else(); // live -- else branch
|
||||
}
|
||||
}
|
||||
|
||||
function elif_chain(): void {
|
||||
if (false) {
|
||||
dead_in_consequence(); // dead
|
||||
} else if (some_condition()) {
|
||||
live_final_else(); // live
|
||||
}
|
||||
}
|
||||
|
||||
function true_guard(): void {
|
||||
// if true is NOT a dead guard -- consequence is live.
|
||||
if (true) {
|
||||
live_in_if_true(); // live
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID int
|
||||
Name string
|
||||
Email string
|
||||
}
|
||||
|
||||
type UserRepository interface {
|
||||
FindByID(id int) (*User, error)
|
||||
Save(user *User) error
|
||||
}
|
||||
|
||||
type InMemoryRepo struct {
|
||||
users map[int]*User
|
||||
}
|
||||
|
||||
func NewInMemoryRepo() *InMemoryRepo {
|
||||
return &InMemoryRepo{users: make(map[int]*User)}
|
||||
}
|
||||
|
||||
func (r *InMemoryRepo) FindByID(id int) (*User, error) {
|
||||
user, ok := r.users[id]
|
||||
if !ok {
|
||||
return nil, errors.New("user not found")
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (r *InMemoryRepo) Save(user *User) error {
|
||||
r.users[user.ID] = user
|
||||
fmt.Printf("Saved user %d\n", user.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func CreateUser(repo UserRepository, name string, email string) (*User, error) {
|
||||
user := &User{ID: 1, Name: name, Email: email}
|
||||
err := repo.Save(user)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
# Helper library sourced by sample.sh — used to verify `source` is
|
||||
# resolved to a real file by _resolve_module_to_file.
|
||||
|
||||
lib_helper() {
|
||||
echo "helper called"
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
# Fixture for testing REFERENCES edge extraction in Python map dispatch patterns.
|
||||
|
||||
|
||||
def handle_create(data):
|
||||
print("create", data)
|
||||
|
||||
|
||||
def handle_update(data):
|
||||
print("update", data)
|
||||
|
||||
|
||||
def handle_delete(data):
|
||||
print("delete", data)
|
||||
|
||||
|
||||
def validate_input(data):
|
||||
return data is not None
|
||||
|
||||
|
||||
def process_data(data):
|
||||
return data
|
||||
|
||||
|
||||
def format_output(data):
|
||||
return str(data)
|
||||
|
||||
|
||||
# Pattern 1: Dict with function values
|
||||
handlers = {
|
||||
"create": handle_create,
|
||||
"update": handle_update,
|
||||
"delete": handle_delete,
|
||||
}
|
||||
|
||||
# Pattern 2: List of function references (pipeline)
|
||||
pipeline = [validate_input, process_data, format_output]
|
||||
|
||||
|
||||
# Pattern 3: Assignment to dict key
|
||||
dynamic_handlers = {}
|
||||
dynamic_handlers["format"] = format_output
|
||||
|
||||
|
||||
def dispatch(action):
|
||||
handler = handlers.get(action)
|
||||
if handler:
|
||||
handler({})
|
||||
@@ -0,0 +1,55 @@
|
||||
// Fixture for testing REFERENCES edge extraction in map dispatch patterns.
|
||||
|
||||
function handleCreate(data: any): void {
|
||||
console.log("create", data);
|
||||
}
|
||||
|
||||
function handleUpdate(data: any): void {
|
||||
console.log("update", data);
|
||||
}
|
||||
|
||||
function handleDelete(data: any): void {
|
||||
console.log("delete", data);
|
||||
}
|
||||
|
||||
function validateInput(data: any): boolean {
|
||||
return data != null;
|
||||
}
|
||||
|
||||
function processData(data: any): any {
|
||||
return data;
|
||||
}
|
||||
|
||||
function formatOutput(data: any): string {
|
||||
return JSON.stringify(data);
|
||||
}
|
||||
|
||||
// Pattern 1: Object literal with function values (Record<string, Handler>)
|
||||
const handlers: Record<string, (data: any) => void> = {
|
||||
create: handleCreate,
|
||||
update: handleUpdate,
|
||||
delete: handleDelete,
|
||||
};
|
||||
|
||||
// Pattern 2: Shorthand property references
|
||||
const shorthandMap = { validateInput, processData };
|
||||
|
||||
// Pattern 3: Property assignment to map
|
||||
const dynamicHandlers: Record<string, Function> = {};
|
||||
dynamicHandlers['format'] = formatOutput;
|
||||
|
||||
// Pattern 4: Array of function references (pipeline)
|
||||
const pipeline = [validateInput, processData, formatOutput];
|
||||
|
||||
// Pattern 5: Function passed as callback argument
|
||||
function register(fn: Function): void {
|
||||
// registration logic
|
||||
}
|
||||
|
||||
function dispatch(action: string): void {
|
||||
const handler = handlers[action];
|
||||
if (handler) {
|
||||
register(handleCreate);
|
||||
handler({});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Mocha TDD interface: enabled via `mocha --ui tdd`.
|
||||
// `suite` is the describe-equivalent and `test` is the it-equivalent.
|
||||
import { UserRepository, UserService } from './sample_typescript';
|
||||
|
||||
suite('UserService (mocha TDD)', () => {
|
||||
test('constructs a service', () => {
|
||||
const service = new UserService();
|
||||
if (!service) throw new Error('expected service');
|
||||
});
|
||||
|
||||
test('returns undefined for unknown id', () => {
|
||||
const service = new UserService();
|
||||
const user = service.getUser(404);
|
||||
if (user !== undefined) throw new Error('expected undefined');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
{ lib, pkgs, ... }:
|
||||
|
||||
let
|
||||
helper = import ./foo.nix { inherit lib; };
|
||||
in {
|
||||
environment.systemPackages = [ pkgs.hello ];
|
||||
|
||||
services.myservice = {
|
||||
enable = true;
|
||||
greeting = helper.greeting;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "7fb27b941602401d91542211134fc71a",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Sample Notebook\n",
|
||||
"This is a markdown cell."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "acae54e37e7d407bbb7b55eff062a284",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%pip install pandas\n",
|
||||
"!ls -la\n",
|
||||
"import os\n",
|
||||
"from pathlib import Path\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "9a63283cbaf04dbcab1f6479b197f3a8",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import math\n",
|
||||
"\n",
|
||||
"def add(x, y):\n",
|
||||
" return x + y\n",
|
||||
"\n",
|
||||
"def multiply(a, b):\n",
|
||||
" return a * b\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "8dd0d8092fe74a7c96281538738b07e2",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"class DataProcessor:\n",
|
||||
" def __init__(self, name):\n",
|
||||
" self.name = name\n",
|
||||
"\n",
|
||||
" def process(self, data):\n",
|
||||
" result = add(data, 1)\n",
|
||||
" return multiply(result, 2)\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "raw",
|
||||
"id": "72eea5119410473aa328ad9291626812",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This raw cell should be skipped."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "8edb47106e1a46a883d545849b8ab81b",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"processor = DataProcessor('test')\n",
|
||||
"output = processor.process(5)\n",
|
||||
"print(output)\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python",
|
||||
"version": "3.11.0"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Sample Python file for testing the parser."""
|
||||
|
||||
import os
|
||||
from pathlib import Path # noqa: F401 — used by parser tests
|
||||
|
||||
|
||||
class BaseService:
|
||||
"""A base service class."""
|
||||
|
||||
def __init__(self, name: str):
|
||||
self.name = name
|
||||
|
||||
def start(self) -> None:
|
||||
print(f"Starting {self.name}")
|
||||
|
||||
|
||||
class AuthService(BaseService):
|
||||
"""Authentication service."""
|
||||
|
||||
def __init__(self, name: str, secret: str):
|
||||
super().__init__(name)
|
||||
self.secret = secret
|
||||
|
||||
def authenticate(self, token: str) -> bool:
|
||||
return self._validate_token(token)
|
||||
|
||||
def _validate_token(self, token: str) -> bool:
|
||||
return token == self.secret
|
||||
|
||||
|
||||
def create_auth_service() -> AuthService:
|
||||
secret = os.environ.get("SECRET", "default")
|
||||
return AuthService("auth", secret)
|
||||
|
||||
|
||||
def process_request(service: AuthService, token: str) -> dict:
|
||||
if service.authenticate(token):
|
||||
return {"status": "ok"}
|
||||
return {"status": "denied"}
|
||||
|
||||
|
||||
def _log_action(func):
|
||||
"""Simple decorator."""
|
||||
def wrapper(*args, **kwargs):
|
||||
return func(*args, **kwargs)
|
||||
return wrapper
|
||||
|
||||
|
||||
@_log_action
|
||||
def guarded_process(service: AuthService, token: str) -> dict:
|
||||
return process_request(service, token)
|
||||
@@ -0,0 +1,69 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub trait Repository {
|
||||
fn find_by_id(&self, id: u64) -> Option<&User>;
|
||||
fn save(&mut self, user: User);
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct User {
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
pub email: String,
|
||||
}
|
||||
|
||||
pub struct InMemoryRepo {
|
||||
users: HashMap<u64, User>,
|
||||
}
|
||||
|
||||
impl InMemoryRepo {
|
||||
pub fn new() -> Self {
|
||||
InMemoryRepo {
|
||||
users: HashMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Repository for InMemoryRepo {
|
||||
fn find_by_id(&self, id: u64) -> Option<&User> {
|
||||
self.users.get(&id)
|
||||
}
|
||||
|
||||
fn save(&mut self, user: User) {
|
||||
println!("Saving user {}", user.id);
|
||||
self.users.insert(user.id, user);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_user(repo: &mut impl Repository, name: &str, email: &str) -> User {
|
||||
let user = User {
|
||||
id: 1,
|
||||
name: name.to_string(),
|
||||
email: email.to_string(),
|
||||
};
|
||||
repo.save(user.clone());
|
||||
user
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn new_repo_is_empty() {
|
||||
let repo = InMemoryRepo::new();
|
||||
assert!(repo.find_by_id(1).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_user_saves_to_repo() {
|
||||
let mut repo = InMemoryRepo::new();
|
||||
let user = create_user(&mut repo, "alice", "[email protected]");
|
||||
assert_eq!(user.name, "alice");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn async_test_is_detected() {
|
||||
assert!(true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Request, Response } from 'express';
|
||||
|
||||
interface UserData {
|
||||
id: number;
|
||||
name: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
class UserRepository {
|
||||
private users: Map<number, UserData> = new Map();
|
||||
|
||||
findById(id: number): UserData | undefined {
|
||||
return this.users.get(id);
|
||||
}
|
||||
|
||||
save(user: UserData): void {
|
||||
this.users.set(user.id, user);
|
||||
}
|
||||
}
|
||||
|
||||
class UserService extends UserRepository {
|
||||
getUser(id: number): UserData | undefined {
|
||||
return this.findById(id);
|
||||
}
|
||||
|
||||
createUser(name: string, email: string): UserData {
|
||||
const user: UserData = { id: Date.now(), name, email };
|
||||
this.save(user);
|
||||
return user;
|
||||
}
|
||||
}
|
||||
|
||||
export function handleGetUser(req: Request, res: Response): void {
|
||||
const service = new UserService();
|
||||
const user = service.getUser(Number(req.params.id));
|
||||
if (user) {
|
||||
res.json(user);
|
||||
} else {
|
||||
res.status(404).json({ error: 'Not found' });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { UserRepository, UserService } from './sample_typescript';
|
||||
|
||||
describe('UserService', () => {
|
||||
it('should create a user', () => {
|
||||
const repo = new UserRepository();
|
||||
const service = new UserService(repo);
|
||||
});
|
||||
|
||||
it('should find a user by id', () => {
|
||||
const repo = new UserRepository();
|
||||
const service = new UserService(repo);
|
||||
const user = service.findById('123');
|
||||
});
|
||||
|
||||
test('alternative test syntax', () => {
|
||||
const repo = new UserRepository();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
<template>
|
||||
<div class="app">
|
||||
<h1>{{ title }}</h1>
|
||||
<UserList :users="users" @select="onSelectUser" />
|
||||
<button @click="increment">Count: {{ count }}</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed } from 'vue'
|
||||
import UserList from './UserList.vue'
|
||||
|
||||
interface User {
|
||||
id: number
|
||||
name: string
|
||||
}
|
||||
|
||||
const count = ref(0)
|
||||
const title = ref('My App')
|
||||
const users = ref<User[]>([])
|
||||
|
||||
function increment() {
|
||||
count.value++
|
||||
}
|
||||
|
||||
function onSelectUser(user: User) {
|
||||
console.log(user.name)
|
||||
}
|
||||
|
||||
const doubled = computed(() => count.value * 2)
|
||||
|
||||
function fetchUsers() {
|
||||
return fetch('/api/users')
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,38 @@
|
||||
const std = @import("std");
|
||||
const util = @import("./sample_zig_util.zig");
|
||||
|
||||
pub fn main() !void {
|
||||
std.debug.print("hello\n", .{});
|
||||
const x = helper(2);
|
||||
_ = x;
|
||||
util.noop();
|
||||
}
|
||||
|
||||
fn helper(x: i32) i32 {
|
||||
return x + 1;
|
||||
}
|
||||
|
||||
pub const Point = struct {
|
||||
x: i32,
|
||||
y: i32,
|
||||
|
||||
pub fn init(x: i32, y: i32) Point {
|
||||
return .{ .x = x, .y = y };
|
||||
}
|
||||
|
||||
pub fn distance(self: Point, other: Point) f32 {
|
||||
_ = other;
|
||||
return @intCast(helper(self.x));
|
||||
}
|
||||
};
|
||||
|
||||
const Color = enum { red, green, blue };
|
||||
|
||||
pub const Shape = union(enum) {
|
||||
circle: f32,
|
||||
square: f32,
|
||||
};
|
||||
|
||||
test "helper increments" {
|
||||
try expect(helper(1) == 2);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
pub fn noop() void {}
|
||||
@@ -0,0 +1,3 @@
|
||||
export function cn(...args: string[]): string {
|
||||
return args.join(' ');
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
---
|
||||
# Sanitized standalone task file fixture
|
||||
|
||||
- name: Create app user
|
||||
user:
|
||||
name: appuser
|
||||
shell: /bin/bash
|
||||
|
||||
- name: Clone repository
|
||||
git:
|
||||
repo: https://github.com/example/app.git
|
||||
dest: /opt/app
|
||||
register: clone_result
|
||||
|
||||
- ansible.builtin.package:
|
||||
name: python3-pip
|
||||
state: present
|
||||
|
||||
- name: Install requirements
|
||||
pip:
|
||||
requirements: /opt/app/requirements.txt
|
||||
changed_when: false
|
||||
|
||||
- name: Apply role configuration
|
||||
ansible.builtin.include_role:
|
||||
name: shared_config
|
||||
|
||||
- name: Run deployment steps
|
||||
ansible.builtin.import_tasks: deploy_steps.yml
|
||||
|
||||
- name: Load environment vars
|
||||
include_vars:
|
||||
file: env_vars.yml
|
||||
|
||||
- name: Create directories
|
||||
file:
|
||||
path: "{{ item }}"
|
||||
state: directory
|
||||
mode: "0755"
|
||||
loop:
|
||||
- /opt/app/logs
|
||||
- /opt/app/tmp
|
||||
loop_control:
|
||||
label: "{{ item }}"
|
||||
@@ -0,0 +1,9 @@
|
||||
library(testthat)
|
||||
|
||||
test_that("addition works", {
|
||||
expect_equal(add(1, 2), 3)
|
||||
})
|
||||
|
||||
test_add <- function() {
|
||||
stopifnot(add(1, 2) == 3)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Tests for sample_python.py - used to verify TESTED_BY edge detection."""
|
||||
|
||||
from tests.fixtures.sample_python import AuthService, process_request
|
||||
|
||||
|
||||
def test_authenticate_valid():
|
||||
service = AuthService("test", "secret123")
|
||||
assert service.authenticate("secret123") is True
|
||||
|
||||
|
||||
def test_authenticate_invalid():
|
||||
service = AuthService("test", "secret123")
|
||||
assert service.authenticate("wrong") is False
|
||||
|
||||
|
||||
def test_process_request_ok():
|
||||
service = AuthService("test", "secret123")
|
||||
result = process_request(service, "secret123")
|
||||
assert result["status"] == "ok"
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["src/*"],
|
||||
"@utils/*": ["src/lib/utils/*"]
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user