Skip to content
This repository has been archived by the owner on Sep 5, 2023. It is now read-only.

Fix warpmemory function naming and implicits + other minor stuff #1075

Draft
wants to merge 156 commits into
base: cairo-1.0
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
156 commits
Select commit Hold shift + click to select a range
793838e
Make warplib a scarb project
rodrigo-pino Apr 17, 2023
bf9b585
Add maths module
rodrigo-pino Apr 18, 2023
00c9872
update corelib to alpha 7
rodrigo-pino Apr 18, 2023
692d01d
Add arm binaries from alpha 7
rodrigo-pino Apr 18, 2023
73370a8
Add warp plugin binaries
rodrigo-pino Apr 18, 2023
8f76b9d
Rework structure for
rodrigo-pino Apr 18, 2023
7a0e865
Fix warp dependency
rodrigo-pino Apr 18, 2023
73e4582
Fix warplib and delete files to ignore
rodrigo-pino Apr 19, 2023
b96fc7e
delete autogenerted warplib scripts
rodrigo-pino Apr 19, 2023
ab61da8
Add corelib and bin for linux_x64
rodrigo-pino Apr 19, 2023
f52d419
Scarb package name replaces - for _
rodrigo-pino Apr 19, 2023
7eeb1d1
Update compileCairo1 to use new binary
rodrigo-pino Apr 19, 2023
719cd0e
Update compilation testing framework
rodrigo-pino Apr 19, 2023
78e3da9
Some comments
rodrigo-pino Apr 19, 2023
1b79ba0
Merge branch 'wm-plugin-integration' of https://github.com/Nethermind…
rodrigo-pino Apr 19, 2023
40e08df
Address review
rodrigo-pino Apr 20, 2023
26c0c1a
Add unimplemented traits for WarpMemory
rodrigo-pino Apr 20, 2023
2b89fe6
Typo
rodrigo-pino Apr 20, 2023
bf3b9f5
Merge branch 'warp-memory-base-for-cairo1' into warplib-memory-to-cairo1
rodrigo-pino Apr 20, 2023
0c5bf41
Delete maths.cairo
rodrigo-pino Apr 20, 2023
a746825
Fix comp errors
rodrigo-pino Apr 20, 2023
0b028b3
Merge branch 'cairo-1.0' into warplib-memory-to-cairo1
rodrigo-pino Apr 21, 2023
3a6bd0b
Add array handling logic
rodrigo-pino Apr 21, 2023
f38cbcc
Fix some compilation errors
rodrigo-pino Apr 21, 2023
6b4289c
Make memory operations safe
rodrigo-pino Apr 24, 2023
95fdfb3
Merge branch 'cairo-1.0' into warplib-memory-to-cairo1
rodrigo-pino Apr 25, 2023
e7f2778
Update part of memory systems
rodrigo-pino Apr 25, 2023
d6a2904
Add implicit conversion cases
rodrigo-pino Apr 25, 2023
cac9aa9
fix typo
rodrigo-pino Apr 27, 2023
50c8b66
Merge branch 'warplib-memory-to-cairo1' into warp-memory-util-func-gen
rodrigo-pino Apr 27, 2023
60a0ed9
Array concat
rodrigo-pino May 1, 2023
4bc0ae1
Minor refactoring to importPath.ts
rodrigo-pino May 1, 2023
bdc2074
Use Serde trait to store/retrieve from memory (#1040)
piwonskp May 1, 2023
c32d021
Merge branch 'warplib-memory-to-cairo1' into warp-memory-util-func-gen
rodrigo-pino May 1, 2023
791a782
Address review
rodrigo-pino May 2, 2023
c8db599
Update read_id to get_or_create_id
rodrigo-pino May 2, 2023
68ab655
Merge branch 'warplib-memory-to-cairo1' into warp-memory-util-func-gen
rodrigo-pino May 2, 2023
8a8b504
Remove warplib/target
rodrigo-pino May 3, 2023
3a8d2d9
Update imports
rodrigo-pino May 3, 2023
2181a35
Rewrite memory to calldata
rodrigo-pino May 3, 2023
02bbc22
memory to storage
rodrigo-pino May 3, 2023
463eb66
Update workflow
rodrigo-pino May 8, 2023
0230865
Fix tsc compilation errors
rodrigo-pino May 8, 2023
ad0c204
Update warplib testing framwerk
rodrigo-pino May 8, 2023
7c166b6
Fix bugs and compilation erros in warplib
rodrigo-pino May 8, 2023
dd7b03f
Add unit tests to Warplib
rodrigo-pino May 8, 2023
b95e703
Remove warplib sierra
rodrigo-pino May 8, 2023
bdaf11e
calldata to memory
rodrigo-pino May 8, 2023
5a95fc3
Merge branch 'warplib-memory-to-cairo1' into warp-memory-util-func-gen
rodrigo-pino May 8, 2023
b1996f9
Add storage to memory
rodrigo-pino May 8, 2023
790b55d
Fix tsc compile bugs
rodrigo-pino May 9, 2023
6ea49ce
Add cairo1 compile and format for when using warp
rodrigo-pino May 9, 2023
79828bd
Update abi imports
rodrigo-pino May 11, 2023
2e6dd15
Improvements to memory util func gen
rodrigo-pino May 11, 2023
6731ab0
Other import updates
rodrigo-pino May 11, 2023
77e0e62
Fix some issues with imports
rodrigo-pino May 11, 2023
14c4893
Update a maths util function
rodrigo-pino May 11, 2023
682f8d2
Minor bug fixes in accessors
rodrigo-pino May 11, 2023
06083e7
Address review + add new test
rodrigo-pino May 11, 2023
4c6194e
Use into
rodrigo-pino May 11, 2023
e80d52e
Address review
rodrigo-pino May 12, 2023
2ebf940
Update warplib/src/test/warp_memory_test.cairo
rodrigo-pino May 15, 2023
5c05eb8
Update warplib/src/test/warp_memory_test.cairo
rodrigo-pino May 15, 2023
19e4e26
Update warplib/src/test/warp_memory_test.cairo
rodrigo-pino May 15, 2023
df86239
start_pos -> position
rodrigo-pino May 15, 2023
3078b2f
Fix and test change
rodrigo-pino May 15, 2023
4b1b152
Update warplib/src/test/warp_memory_test.cairo
rodrigo-pino May 16, 2023
ee13cf5
Update warplib/src/test/warp_memory_test.cairo
rodrigo-pino May 16, 2023
c9a9ef1
Update warplib/src/test/warp_memory_test.cairo
rodrigo-pino May 16, 2023
32fd4d8
Update warplib/src/test/warp_memory_test.cairo
rodrigo-pino May 16, 2023
741aa3d
Update warplib/src/test/warp_memory_test.cairo
rodrigo-pino May 16, 2023
0871e3c
Update warplib/src/test/warp_memory_test.cairo
rodrigo-pino May 16, 2023
d7f545b
Merge branch 'cairo-1.0' into warplib-memory-to-cairo1
rodrigo-pino May 16, 2023
5d7db50
Minor stuff
rodrigo-pino May 16, 2023
c24e2a5
Update warplib/src/test/warp_memory_test.cairo
rodrigo-pino May 16, 2023
fae6076
Remove starknet_accounts_devnet
rodrigo-pino May 16, 2023
c55a7dd
Merge branch 'warplib-memory-to-cairo1' into warp-memory-util-func-gen
rodrigo-pino May 16, 2023
468b241
Add super to importPaths
rodrigo-pino May 16, 2023
faa514a
Fix testing
rodrigo-pino May 16, 2023
6a885ef
Merge branch 'warplib-memory-to-cairo1' into warp-memory-util-func-gen
rodrigo-pino May 16, 2023
6d0a4d4
Improvments + linting
rodrigo-pino May 16, 2023
f07adc0
Remove mut
rodrigo-pino May 16, 2023
59db7df
Some minor fixes
rodrigo-pino May 17, 2023
239487f
Merge branch 'cairo-1.0' into warp-memory-util-func-gen
rodrigo-pino May 17, 2023
faad4d8
Fix
rodrigo-pino May 21, 2023
8fb17f7
linting
rodrigo-pino May 21, 2023
750cf03
Mergin'
rodrigo-pino May 22, 2023
1728081
Move tests related with warp memory/storage
rodrigo-pino May 25, 2023
ac7cf06
Another rename :)
rodrigo-pino May 25, 2023
2b70d15
Nitpick in contract writer
rodrigo-pino May 25, 2023
8919e03
Nitpick in source unit writer
rodrigo-pino May 25, 2023
e5d2ee0
Ensure addition of WarpMemory struct
rodrigo-pino May 25, 2023
19bab28
Update arguments type to `new_dynamic_array`
rodrigo-pino May 25, 2023
57a12c5
Delete Warp Memory fixed path
rodrigo-pino May 25, 2023
b6e747f
Update import paths to avoid flattening
rodrigo-pino May 25, 2023
48ecb37
Add rudimentary parser for WarpMemory in Warplib
rodrigo-pino May 25, 2023
d9b233a
Update compilation tests
rodrigo-pino May 25, 2023
d7c461d
Address review
rodrigo-pino May 26, 2023
2a7434b
Add endent in calldataToMemory
rodrigo-pino May 26, 2023
2be3de3
Improvements in concat util func gen
rodrigo-pino May 26, 2023
8a34567
Add utilitie
rodrigo-pino May 26, 2023
75f681b
General fixes
rodrigo-pino May 26, 2023
144a25c
Improvements
rodrigo-pino May 26, 2023
deafe3c
Update src/cairoUtilFuncGen/memory/implicitConversion.ts
rodrigo-pino May 26, 2023
e674560
Linting
rodrigo-pino May 26, 2023
b8d724f
Merge branch 'warp-memory-util-func-gen' of https://github.com/Nether…
rodrigo-pino May 26, 2023
419fda9
General fixes and improvements
rodrigo-pino May 27, 2023
fbac08f
Relocation of warplib function
rodrigo-pino May 27, 2023
c7b7010
Update src/cairoUtilFuncGen/memory/memoryStruct.ts
rodrigo-pino May 27, 2023
dc08211
Merge branch 'cairo-1.0' into warp-memory-util-func-gen
rodrigo-pino May 27, 2023
24ae54b
Bug fix
rodrigo-pino May 27, 2023
362ca24
Update src/cairoUtilFuncGen/memory/memoryToStorage.ts
rodrigo-pino May 27, 2023
cedb768
Update src/cairoUtilFuncGen/memory/memoryToStorage.ts
rodrigo-pino May 27, 2023
ba450bf
Update src/cairoUtilFuncGen/memory/memoryToStorage.ts
rodrigo-pino May 27, 2023
da63ff9
Update src/cairoUtilFuncGen/memory/memoryToCalldata.ts
rodrigo-pino May 28, 2023
a5c1d72
Rename to try
rodrigo-pino May 28, 2023
5e59884
Endent
rodrigo-pino May 28, 2023
5845513
try rename
rodrigo-pino May 28, 2023
cfeb672
Add felt constant and minor improvements
rodrigo-pino May 28, 2023
5176a93
Merge branch 'warp-memory-util-func-gen' of https://github.com/Nether…
rodrigo-pino May 28, 2023
ae621dc
Typo
rodrigo-pino May 28, 2023
2939381
Linting
rodrigo-pino May 28, 2023
59f523d
Restore .starknet_account_devnet
rodrigo-pino May 28, 2023
5547aa0
Write variables as mut
rodrigo-pino May 29, 2023
63d34c3
Remove triple sss
rodrigo-pino May 29, 2023
5ad8461
Remainig triple sss
rodrigo-pino May 29, 2023
a82ae66
Nitpicks
rodrigo-pino May 29, 2023
b9c757d
Merge branch 'warp-memory-util-func-gen' into fix-implicit-annotation…
rodrigo-pino May 29, 2023
7bc8cfd
Compilation fix
rodrigo-pino May 29, 2023
1b1cded
Fix some parsing errors
rodrigo-pino May 30, 2023
43929d7
remove .starknet_accounts_devnet
rodrigo-pino Jun 1, 2023
5464a08
Add some comments
rodrigo-pino Jun 1, 2023
1b51e9b
Untry
rodrigo-pino Jun 1, 2023
98dec07
Merge branch 'warp-memory-util-func-gen' into fix-implicit-annotation…
rodrigo-pino Jun 1, 2023
0c48df8
Restore behaviour file to default
rodrigo-pino Jun 1, 2023
75b75c4
Restore behaviour file to default 2
rodrigo-pino Jun 1, 2023
00f8cc6
Merge branch 'cairo-1.0' into warp-memory-util-func-gen
rodrigo-pino Jun 1, 2023
7877eb0
Merge branch 'warp-memory-util-func-gen' into fix-implicit-annotation…
rodrigo-pino Jun 1, 2023
a07d458
compilation fix
rodrigo-pino Jun 1, 2023
53abf6e
Merge branch 'cairo-1.0' into fix-implicit-annotation-warp-memory
rodrigo-pino Jun 2, 2023
3234f35
Lots of minor bugs
rodrigo-pino Jun 2, 2023
4d2f8f4
Update corelibs
rodrigo-pino Jun 7, 2023
5f45f68
Update binaries
rodrigo-pino Jun 7, 2023
500fcb6
Update testing
rodrigo-pino Jun 7, 2023
a2277f1
Add cairo 1.1 linux x64 binaries
Jun 8, 2023
afb51d7
Update starknet-devnet to match cairo 1.1
Jun 8, 2023
cc5d177
Update output repo
rodrigo-pino Jun 8, 2023
eb42d88
Bug fix
rodrigo-pino Jun 8, 2023
534e180
Reset old path
rodrigo-pino Jun 8, 2023
c60ee7d
Fix testnet bugs
rodrigo-pino Jun 9, 2023
ee8b73c
Merge branch 'update-cairo-1.1' into fix-implicit-annotation-warp-memory
rodrigo-pino Jun 9, 2023
f389aef
Merge branch 'cairo-1.0' into fix-implicit-annotation-warp-memory
rodrigo-pino Jun 9, 2023
8662bb0
Add missing imports
rodrigo-pino Jun 9, 2023
f78c823
Add integer for import gathering
rodrigo-pino Jun 14, 2023
4099b18
Add an import path and u252 are treated as felt internally
rodrigo-pino Jun 14, 2023
90320b5
Linting
rodrigo-pino Jun 16, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions src/cairoWriter/writers/cairoContractWriter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,17 @@ export class CairoContractWriter extends CairoASTNodeWriter {
`// This contract may be abstract, it may not implement an abstract parent's methods\n// completely or it may not invoke an inherited contract's constructor correctly.\n`,
];

const dynamicVariables = [...node.dynamicStorageAllocations.entries()].map(
const staticVariables = [...node.staticStorageAllocations.entries()].map(
([decl, loc]) => `const ${decl.name}: felt252 = ${loc};`,
);
const staticVariables = [...node.staticStorageAllocations.entries()].map(
const dynamicVariables = [...node.dynamicStorageAllocations.entries()].map(
([decl, loc]) => `const ${decl.name}: felt252 = ${loc};`,
);
const variables = [
`// Dynamic variables - Arrays and Maps`,
...dynamicVariables,
`// Static variables`,
staticVariables.length > 0 ? '// Static variables' : '',
...staticVariables,
dynamicVariables.length > 0 ? '// Dynamic variables - Arrays and Maps' : '',
...dynamicVariables,
];

let documentation = getDocumentation(node.documentation, writer);
Expand Down
4 changes: 2 additions & 2 deletions src/cairoWriter/writers/sourceUnitWriter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ export class SourceUnitWriter extends CairoASTNodeWriter {
this.generateInterfaceNameMappings(node);

// Every sourceUnit should only define a single contract
const mainContract_ =
const mainContracts =
node.vContracts.length >= 2
? node.vContracts.filter((cd) => !cd.name.endsWith(TEMP_INTERFACE_SUFFIX))
: node.vContracts;

assert(mainContract_.length <= 1, 'Every SourceUnit should only define a single contract');
assert(mainContracts.length <= 1, 'Every SourceUnit should only define a single contract');

structRemappings = new Map();

Expand Down
20 changes: 17 additions & 3 deletions src/passes/cairoUtilImporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,16 @@ import {
} from 'solc-typed-ast';
import { AST } from '../ast/ast';
import { ASTMapper } from '../ast/mapper';
import { CairoFunctionDefinition } from '../export';
import { requireNonNullish } from '../export';
import { createImport } from '../utils/importFuncGenerator';
import {
INTO,
U256_FROM_FELTS,
U128_FROM_FELT,
CONTRACT_ADDRESS,
WARP_MEMORY,
WM_INIT,
CUTOFF_DOWNCAST,
WARPLIB_INTEGER,
} from '../utils/importPaths';
Expand All @@ -31,16 +34,27 @@ import { getContainingSourceUnit, primitiveTypeToCairo } from '../utils/utils';
the warplib maths functions as they are added to the code, but for determining if
Uint256 needs to be imported, it's easier to do it here
*/

export class CairoUtilImporter extends ASTMapper {
private dummySourceUnit: SourceUnit | undefined;

// Function to add passes that should have been run before this pass
addInitialPassPrerequisites(): void {
const passKeys: Set<string> = new Set<string>([]);
// It requires the AnnotateImplicits (An) because we need to know if any functions
// uses WarpMemory
// It requires Function Prunner (Fp) for it not to delete any of these newly added
// imports
const passKeys: Set<string> = new Set<string>(['An', 'Fp']);
passKeys.forEach((key) => this.addPassPrerequisite(key));
}

visitCairoFunctionDefinition(node: CairoFunctionDefinition, ast: AST): void {
if (node.implicits.has('warp_memory')) {
createImport(...WARP_MEMORY, this.dummySourceUnit ?? node, ast);
createImport(...WM_INIT, this.dummySourceUnit ?? node, ast);
}
this.commonVisit(node, ast);
}

visitElementaryTypeName(node: ElementaryTypeName, ast: AST): void {
const cairoType = primitiveTypeToCairo(node.name);
if (cairoType === 'u256') {
Expand All @@ -63,7 +77,7 @@ export class CairoUtilImporter extends ASTMapper {

visitLiteral(node: Literal, ast: AST): void {
const type = safeGetNodeType(node, ast.inference);
if (type instanceof IntType && type.nBits > 251) {
if (type instanceof IntType && type.nBits === 256) {
createImport(...U256_FROM_FELTS, this.dummySourceUnit ?? node, ast);
}

Expand Down
26 changes: 21 additions & 5 deletions src/passes/references/memoryAllocations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,13 @@ import { printNode } from '../../utils/astPrinter';
import { CairoType, TypeConversionContext } from '../../utils/cairoTypeSystem';
import { NotSupportedYetError } from '../../utils/errors';
import { createCallToFunction } from '../../utils/functionGeneration';
import { createNumberLiteral, createUint256TypeName } from '../../utils/nodeTemplates';
import {
createFeltTypeName,
createNumberLiteral,
createUint256TypeName,
} from '../../utils/nodeTemplates';
import { getElementType, safeGetNodeType } from '../../utils/nodeTypeProcessing';
import { WM_NEW } from '../../utils/importPaths';
import { U256_TO_FELT252, WM_NEW } from '../../utils/importPaths';

/*
Handles expressions that directly insert data into memory: struct constructors, news, and inline arrays
Expand Down Expand Up @@ -83,8 +87,8 @@ export class MemoryAllocations extends ReferenceSubPass {
node,
...WM_NEW,
[
['len', createUint256TypeName(ast)],
['elemWidth', createUint256TypeName(ast)],
['len', createFeltTypeName(ast)],
['elem_size', createFeltTypeName(ast)],
],
[['loc', node.vExpression.vTypeName, DataLocation.Memory]],
);
Expand All @@ -102,9 +106,21 @@ export class MemoryAllocations extends ReferenceSubPass {
TypeConversionContext.Ref,
);

const uint256ToFeltDef = ast.registerImport(
node,
...U256_TO_FELT252,
[['x_256', createUint256TypeName(ast)]],
[['x_252', createFeltTypeName(ast)]],
);
const uint256ToFeltConversion = createCallToFunction(
uint256ToFeltDef,
[node.vArguments[0]],
ast,
);

const call = createCallToFunction(
funcImport,
[node.vArguments[0], createNumberLiteral(elementCairoType.width, ast, 'uint256')],
[uint256ToFeltConversion, createNumberLiteral(elementCairoType.width, ast, 'uint252')],
ast,
);

Expand Down
2 changes: 1 addition & 1 deletion src/utils/cairoTypeSystem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export abstract class CairoType {
} else if (tp instanceof FunctionType) {
throw new NotSupportedYetError('Serialising FunctionType not supported yet');
} else if (tp instanceof IntType) {
return new CairoUint(tp.nBits);
return tp.nBits === 252 ? new CairoFelt() : new CairoUint(tp.nBits);
} else if (tp instanceof MappingType) {
return new WarpLocation();
} else if (tp instanceof PointerType) {
Expand Down
19 changes: 1 addition & 18 deletions src/utils/importFuncGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,23 +91,6 @@ const FUNCTION_IMPORTS = [
Paths.BOOL_INTO_FELT252,
Paths.FELT252_INTO_BOOL,
Paths.WARPLIB_INTEGER,
Paths.WARP_MEMORY,
Paths.WM_NEW,
Paths.WM_READ,
Paths.WM_ALLOC,
Paths.WM_STORE,
Paths.WM_WRITE,
Paths.WM_CREATE,
Paths.WM_GET_ID,
Paths.WM_RETRIEVE,
Paths.WM_INDEX_DYN,
Paths.WM_UNSAFE_READ,
Paths.WM_INDEX_STATIC,
Paths.WM_UNSAFE_ALLOC,
Paths.WM_UNSAFE_WRITE,
Paths.WM_READ_MULTIPLE,
Paths.WM_WRITE_MULTIPLE,
Paths.WM_DYN_ARRAY_LENGTH,
];

export function createImport(
Expand Down Expand Up @@ -175,7 +158,7 @@ export function createImport(
return createFuncImport();
}

throw new TranspileFailedError(`Import ${name} from ${path} is not defined.`);
throw new TranspileFailedError(`Import ${name} from ${path.join('::')} is not defined.`);
}

function findExistingImport(
Expand Down
10 changes: 8 additions & 2 deletions src/utils/importPaths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,8 @@ const MEMORY_MODULE = ['warplib', 'warp_memory'];

export const WARP_MEMORY: [string[], string] = [MEMORY_MODULE, 'WarpMemory'];
const WARP_MEMORY_TRAIT: string[] = [...MEMORY_MODULE, 'WarpMemoryTrait'];

export const WM_INIT: [string[], string] = [WARP_MEMORY_TRAIT, 'warp_memory.initialize'];
export const WM_READ: [string[], string] = [WARP_MEMORY_TRAIT, 'warp_memory.read'];
export const WM_WRITE: [string[], string] = [WARP_MEMORY_TRAIT, 'warp_memory.write'];
export const WM_ALLOC: [string[], string] = [WARP_MEMORY_TRAIT, 'warp_memory.alloc'];
Expand All @@ -261,7 +263,7 @@ export const WM_UNSAFE_ALLOC: [string[], string] = [
'warp_memory.unsafe_alloc',
];

const WARP_MEMORY_ARRAYS_TRAIT: string[] = [...MEMORY_MODULE, 'WarpMemoryArraysTrait'];
const WARP_MEMORY_ARRAYS_TRAIT: string[] = [...MEMORY_MODULE, 'arrays', 'WarpMemoryArraysTrait'];
export const WM_DYN_ARRAY_LENGTH: [string[], string] = [
WARP_MEMORY_ARRAYS_TRAIT,
'warp_memory.length_dyn',
Expand All @@ -280,7 +282,11 @@ export const WM_GET_ID: [string[], string] = [
'warp_memory.get_or_create_id',
];

const MULTICELL_ACCESSOR_TRAIT: string[] = [...MEMORY_MODULE, 'WarpMemoryMultiCellAccessorTrait'];
const MULTICELL_ACCESSOR_TRAIT: string[] = [
...MEMORY_MODULE,
'accessors',
'WarpMemoryMultiCellAccessorTrait',
];
export const WM_WRITE_MULTIPLE: [string[], string] = [
MULTICELL_ACCESSOR_TRAIT,
'warp_memory.write_multiple',
Expand Down
106 changes: 106 additions & 0 deletions src/warplib/gatherWarplibImports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Implicits } from '../utils/utils';
import { parseMultipleRawCairoFunctions } from '../utils/cairoParsing';
import { glob } from 'glob';
import path from 'path';
import assert from 'assert';

import { WARP_ROOT } from '../config';

Expand All @@ -18,6 +19,23 @@ export const warplibImportInfo = glob
.slice('warplib/src/'.length, -'.cairo'.length)
.split(path.sep),
];

// Handle WarpMemory function gathering differently
if (importPath.includes('warp_memory')) {
// Hardcode WarpMemory struct
if (pathToFile.endsWith('warp_memory.cairo')) {
warplibMap.set(importPath.join('/'), new Map([['WarpMemory', []]]));
}
gatherWarpMemoryFuncs(rawCairoCode, importPath, warplibMap);
return warplibMap;
}

if (importPath[importPath.length - 1] === 'integer') {
console.log('Gather int conversion');
gatherIntegerConversion(rawCairoCode, importPath, warplibMap);
return warplibMap;
}

// TODO: Add encodePath here. Importing encodePath cause circular
// dependency error. Suggested solution is to relocate all import
// related scripts (including this, and the ones in src/utils)
Expand All @@ -32,3 +50,91 @@ export const warplibImportInfo = glob
);
return warplibMap;
}, new Map<string, Map<string, Implicits[]>>());

function gatherIntegerConversion(
rawCairoCode: string,
importPath: string[],
warplibMap: Map<string, Map<string, Implicits[]>>,
) {
const integerTraitInfo = traitFunctionExtractor(rawCairoCode);
console.log(integerTraitInfo);

integerTraitInfo.forEach(({ trait, code }) => {
const traitImportPath = [...importPath, trait];
const key = traitImportPath.join('/');

const fileMap: Map<string, Implicits[]> = warplibMap.get(key) ?? new Map<string, Implicits[]>();
if (!warplibMap.has(key)) {
warplibMap.set(key, fileMap);
}

parseMultipleRawCairoFunctions(code).forEach((cairoFunc) => fileMap.set(cairoFunc.name, []));
});
}

// Functions that stored warp memory functions accordingly
function gatherWarpMemoryFuncs(
rawCairoCode: string,
importPath: string[],
warplibMap: Map<string, Map<string, Implicits[]>>,
) {
// Get the body for each trait
const warpMemoryTraitInfo = traitFunctionExtractor(rawCairoCode);

// Store each trait import path with each function prefixed with "warp_memory."
warpMemoryTraitInfo.forEach(({ trait, code }) => {
const traitImportPath = [...importPath, trait];
const key = traitImportPath.join('/');

const fileMap: Map<string, Implicits[]> = warplibMap.get(key) ?? new Map<string, Implicits[]>();
if (!warplibMap.has(key)) {
warplibMap.set(key, fileMap);
}

parseMultipleRawCairoFunctions(code).forEach((cairoFunc) =>
fileMap.set(`warp_memory.${cairoFunc.name}`, ['warp_memory']),
);
});
}

type TraitInfo = { trait: string; code: string };
function traitFunctionExtractor(rawCairoCode: string): TraitInfo[] {
const warpMemoryInfo: TraitInfo[] = [];
let currentTrait = '';
let currentBody = '';
rawCairoCode
.split('\n')
.filter((l) => !l.match('^[ ]*$'))
.forEach((l) => {
if (l.trim().startsWith('trait')) {
if (currentTrait !== '') {
warpMemoryInfo.push({ trait: currentTrait, code: currentBody });
}
currentTrait = extractName('trait', l);
currentBody = '';
return;
}
if (l.trim().startsWith('impl')) {
if (currentTrait !== '') {
warpMemoryInfo.push({ trait: currentTrait, code: currentBody });
}
currentTrait = '';
currentBody = '';
return;
}
currentBody += '\n' + l.trim();
});

return warpMemoryInfo;
}

function extractName(keyword: string, line: string) {
const regex = new RegExp(`${keyword}[ ]+(?<name>\\w+)`);
const m = line.match(regex);
assert(
m !== null && m.groups !== undefined,
`Error extracting name for ${keyword} in line:\n"${line}"`,
);

return m.groups.name;
}
Loading