From 01f4a01eb90cb745696bb52ec7e2c281fd977ea7 Mon Sep 17 00:00:00 2001 From: AlejandroLabourdette Date: Sun, 5 Feb 2023 20:06:12 -0500 Subject: [PATCH 01/28] generateTypeStr does not show location for default pointers --- src/utils/getTypeString.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/utils/getTypeString.ts b/src/utils/getTypeString.ts index 499041581..a955df65e 100644 --- a/src/utils/getTypeString.ts +++ b/src/utils/getTypeString.ts @@ -240,9 +240,9 @@ export function generateExpressionTypeString(type: TypeNode): string { if (type instanceof PointerType) { if (type.to instanceof MappingType) return generateExpressionTypeString(type.to); else - return `${generateExpressionTypeString(type.to)} ${type.location}${ - type.kind !== undefined ? ' ' + type.kind : '' - }`; + return `${generateExpressionTypeString(type.to)} + ${type.location === DataLocation.Default ? '' : type.location} + ${type.kind !== undefined ? ' ' + type.kind : ''}`; } else if (type instanceof FunctionType) { const mapper = (node: TypeNode) => generateExpressionTypeString(node); From 70a612774cc862ded20c033c9058935cb323fd50 Mon Sep 17 00:00:00 2001 From: AlejandroLabourdette Date: Sun, 5 Feb 2023 20:11:37 -0500 Subject: [PATCH 02/28] getParameterTypes for struct constructor use new type pattern --- src/utils/nodeTypeProcessing.ts | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/src/utils/nodeTypeProcessing.ts b/src/utils/nodeTypeProcessing.ts index 20a286e4c..81affe6ff 100644 --- a/src/utils/nodeTypeProcessing.ts +++ b/src/utils/nodeTypeProcessing.ts @@ -58,9 +58,7 @@ export function getParameterTypes(functionCall: FunctionCall, ast: AST): TypeNod case FunctionCallKind.StructConstructorCall: { assert( - functionType instanceof TypeNameType && - functionType.type instanceof PointerType && - functionType.type.to instanceof UserDefinedType, + functionType instanceof TypeNameType && functionType.type instanceof UserDefinedType, error( `TypeNode for ${printNode( functionCall.vExpression, @@ -70,7 +68,7 @@ export function getParameterTypes(functionCall: FunctionCall, ast: AST): TypeNod )}`, ), ); - const structDef = functionType.type.to.definition; + const structDef = functionType.type.definition; assert(structDef instanceof StructDefinition); return structDef.vMembers.map(ast.inference.variableDeclarationToTypeNode, ast.inference); } @@ -295,17 +293,17 @@ export function safeGetNodeType( inference: InferType, ): TypeNode { getContainingSourceUnit(node); - // if (node instanceof Literal) { - // return getNodeType(node, inference); - // } - // if (node instanceof VariableDeclaration) { - // return inference.variableDeclarationToTypeNode(node); - // } - // if (node instanceof TypeName) { - // return inference.typeNameToTypeNode(node) - // } - // return inference.typeOf(node); - return getNodeType(node, inference); + if (node instanceof Literal) { + return getNodeType(node, inference); + } + if (node instanceof VariableDeclaration) { + return inference.variableDeclarationToTypeNode(node); + } + if (node instanceof TypeName) { + return inference.typeNameToTypeNode(node); + } + return inference.typeOf(node); + // return getNodeType(node, inference); } export function safeGetNodeTypeInCtx( From e762048c7673a8199bd956b88bdec49aee40ed2c Mon Sep 17 00:00:00 2001 From: AlejandroLabourdette Date: Sun, 5 Feb 2023 20:12:32 -0500 Subject: [PATCH 03/28] create identifier do not specialize the nodeType --- src/utils/nodeTemplates.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/utils/nodeTemplates.ts b/src/utils/nodeTemplates.ts index 6b28b9dfb..e51557538 100644 --- a/src/utils/nodeTemplates.ts +++ b/src/utils/nodeTemplates.ts @@ -162,10 +162,7 @@ export function createIdentifier( dataLocation?: DataLocation, lookupNode?: ASTNode, ): Identifier { - const type = specializeType( - safeGetNodeTypeInCtx(variable, ast.inference, lookupNode ?? variable), - dataLocation ?? (variable.stateVariable ? DataLocation.Storage : variable.storageLocation), - ); + const type = safeGetNodeTypeInCtx(variable, ast.inference, lookupNode ?? variable); const node = new Identifier( ast.reserveId(), '', From dbd437f8d3ed7a0df6777f86b9377d3421d5f70f Mon Sep 17 00:00:00 2001 From: AlejandroLabourdette Date: Thu, 9 Feb 2023 15:24:27 -0500 Subject: [PATCH 04/28] TypeNameRemover pass after BuiltinHandler --- src/passes/references/dataAccessFunctionaliser.ts | 3 +++ src/passes/references/expectedLocationAnalyser.ts | 4 ++++ src/passes/typeNameRemover.ts | 9 ++++++++- src/transpiler.ts | 2 +- 4 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/passes/references/dataAccessFunctionaliser.ts b/src/passes/references/dataAccessFunctionaliser.ts index dfe667f01..36f45597c 100644 --- a/src/passes/references/dataAccessFunctionaliser.ts +++ b/src/passes/references/dataAccessFunctionaliser.ts @@ -20,6 +20,7 @@ import { FixedBytesType, BytesType, StringType, + TypeNameType, } from 'solc-typed-ast'; import { TranspileFailedError, WillNotSupportError } from '../../utils/errors'; import { printNode, printTypeNode } from '../../utils/astPrinter'; @@ -265,6 +266,8 @@ export class DataAccessFunctionaliser extends ReferenceSubPass { } visitIndexAccess(node: IndexAccess, ast: AST): void { + const nodeType = safeGetNodeType(node, ast.inference); + if (nodeType instanceof TypeNameType) return this.commonVisit(node, ast); assert(node.vIndexExpression !== undefined); const [actualLoc, expectedLoc] = this.getLocations(node); diff --git a/src/passes/references/expectedLocationAnalyser.ts b/src/passes/references/expectedLocationAnalyser.ts index a766b79f9..6d57ad247 100644 --- a/src/passes/references/expectedLocationAnalyser.ts +++ b/src/passes/references/expectedLocationAnalyser.ts @@ -19,6 +19,7 @@ import { PointerType, Return, TupleExpression, + TypeNameType, UnaryOperation, UserDefinedType, VariableDeclarationStatement, @@ -37,6 +38,7 @@ import { safeGetNodeType, } from '../../utils/nodeTypeProcessing'; import { notNull } from '../../utils/typeConstructs'; +import { getNodeType } from '../../utils/typeStrings/typeString_parser'; import { getContainingFunction, isExternallyVisible } from '../../utils/utils'; /* @@ -178,6 +180,8 @@ export class ExpectedLocationAnalyser extends ASTMapper { } visitIndexAccess(node: IndexAccess, ast: AST): void { + const nodeType = safeGetNodeType(node, ast.inference); + if (nodeType instanceof TypeNameType) return this.commonVisit(node, ast); assert(node.vIndexExpression !== undefined); const baseLoc = this.actualLocations.get(node.vBaseExpression); assert(baseLoc !== undefined); diff --git a/src/passes/typeNameRemover.ts b/src/passes/typeNameRemover.ts index 629325ef5..c92b7f46f 100644 --- a/src/passes/typeNameRemover.ts +++ b/src/passes/typeNameRemover.ts @@ -17,7 +17,14 @@ import { safeGetNodeType } from '../utils/nodeTypeProcessing'; export class TypeNameRemover extends ASTMapper { // Function to add passes that should have been run before this pass addInitialPassPrerequisites(): void { - const passKeys: Set = new Set([]); + const passKeys: Set = new Set([ + // Builtin Handler needs to be run first because some builtin + // functions like abi.decode uses TypeNames as arguments, otherwise, + // they will be removed before use + // Eg: + // abi.decode(data, (uint[7][])); + 'B', + ]); passKeys.forEach((key) => this.addPassPrerequisite(key)); } diff --git a/src/transpiler.ts b/src/transpiler.ts index 9357917db..674eb0b35 100644 --- a/src/transpiler.ts +++ b/src/transpiler.ts @@ -101,7 +101,6 @@ function applyPasses( ): AST { const passes: Map = createPassMap([ ['Tf', TupleFixes], - ['Tnr', TypeNameRemover], ['Ru', RejectUnsupportedFeatures], ['Iat', InlineAssemblyTransformer], ['Wa', WarnSupportedFeatures], @@ -146,6 +145,7 @@ function applyPasses( ['Abc', ArgBoundChecker], ['Ec', EnumConverter], ['B', BuiltinHandler], + ['Tnr', TypeNameRemover], ['Bc', BytesConverter], ['Us', UnreachableStatementPruner], ['Fp', FunctionPruner], From e14067673cc6ddd1c7b2abb520869d16694b80ba Mon Sep 17 00:00:00 2001 From: AlejandroLabourdette Date: Thu, 9 Feb 2023 15:30:19 -0500 Subject: [PATCH 05/28] lint --- src/passes/references/expectedLocationAnalyser.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/passes/references/expectedLocationAnalyser.ts b/src/passes/references/expectedLocationAnalyser.ts index 6d57ad247..c9e2f63df 100644 --- a/src/passes/references/expectedLocationAnalyser.ts +++ b/src/passes/references/expectedLocationAnalyser.ts @@ -38,7 +38,6 @@ import { safeGetNodeType, } from '../../utils/nodeTypeProcessing'; import { notNull } from '../../utils/typeConstructs'; -import { getNodeType } from '../../utils/typeStrings/typeString_parser'; import { getContainingFunction, isExternallyVisible } from '../../utils/utils'; /* From 44921292f7c5bf322f1739399d66ca9c8d568b77 Mon Sep 17 00:00:00 2001 From: AlejandroLabourdette Date: Thu, 9 Feb 2023 19:08:47 -0500 Subject: [PATCH 06/28] after abi builtins pass instead of builtinHandler --- src/passes/references/dataAccessFunctionaliser.ts | 3 --- src/passes/references/expectedLocationAnalyser.ts | 3 --- src/passes/typeNameRemover.ts | 4 ++-- src/transpiler.ts | 2 +- 4 files changed, 3 insertions(+), 9 deletions(-) diff --git a/src/passes/references/dataAccessFunctionaliser.ts b/src/passes/references/dataAccessFunctionaliser.ts index 36f45597c..dfe667f01 100644 --- a/src/passes/references/dataAccessFunctionaliser.ts +++ b/src/passes/references/dataAccessFunctionaliser.ts @@ -20,7 +20,6 @@ import { FixedBytesType, BytesType, StringType, - TypeNameType, } from 'solc-typed-ast'; import { TranspileFailedError, WillNotSupportError } from '../../utils/errors'; import { printNode, printTypeNode } from '../../utils/astPrinter'; @@ -266,8 +265,6 @@ export class DataAccessFunctionaliser extends ReferenceSubPass { } visitIndexAccess(node: IndexAccess, ast: AST): void { - const nodeType = safeGetNodeType(node, ast.inference); - if (nodeType instanceof TypeNameType) return this.commonVisit(node, ast); assert(node.vIndexExpression !== undefined); const [actualLoc, expectedLoc] = this.getLocations(node); diff --git a/src/passes/references/expectedLocationAnalyser.ts b/src/passes/references/expectedLocationAnalyser.ts index c9e2f63df..a766b79f9 100644 --- a/src/passes/references/expectedLocationAnalyser.ts +++ b/src/passes/references/expectedLocationAnalyser.ts @@ -19,7 +19,6 @@ import { PointerType, Return, TupleExpression, - TypeNameType, UnaryOperation, UserDefinedType, VariableDeclarationStatement, @@ -179,8 +178,6 @@ export class ExpectedLocationAnalyser extends ASTMapper { } visitIndexAccess(node: IndexAccess, ast: AST): void { - const nodeType = safeGetNodeType(node, ast.inference); - if (nodeType instanceof TypeNameType) return this.commonVisit(node, ast); assert(node.vIndexExpression !== undefined); const baseLoc = this.actualLocations.get(node.vBaseExpression); assert(baseLoc !== undefined); diff --git a/src/passes/typeNameRemover.ts b/src/passes/typeNameRemover.ts index c92b7f46f..f9397f04e 100644 --- a/src/passes/typeNameRemover.ts +++ b/src/passes/typeNameRemover.ts @@ -18,12 +18,12 @@ export class TypeNameRemover extends ASTMapper { // Function to add passes that should have been run before this pass addInitialPassPrerequisites(): void { const passKeys: Set = new Set([ - // Builtin Handler needs to be run first because some builtin + // ABI Builtin needs to be handled first because some builtin // functions like abi.decode uses TypeNames as arguments, otherwise, // they will be removed before use // Eg: // abi.decode(data, (uint[7][])); - 'B', + 'Abi', ]); passKeys.forEach((key) => this.addPassPrerequisite(key)); } diff --git a/src/transpiler.ts b/src/transpiler.ts index 674eb0b35..a1cf2d354 100644 --- a/src/transpiler.ts +++ b/src/transpiler.ts @@ -139,13 +139,13 @@ function applyPasses( ['Ntd', NewToDeploy], ['I', ImplicitConversionToExplicit], ['Abi', ABIBuiltins], + ['Tnr', TypeNameRemover], ['Ev', Events], ['Dh', DeleteHandler], ['Rf', References], ['Abc', ArgBoundChecker], ['Ec', EnumConverter], ['B', BuiltinHandler], - ['Tnr', TypeNameRemover], ['Bc', BytesConverter], ['Us', UnreachableStatementPruner], ['Fp', FunctionPruner], From 25e13d26f17a1e2032deffa731d6016e69ed9283 Mon Sep 17 00:00:00 2001 From: AlejandroLabourdette Date: Thu, 9 Feb 2023 22:18:42 -0500 Subject: [PATCH 07/28] skip visitIndexAccess to TypeNames that are before abiBuiltin --- src/passes/implicitConversionToExplicit.ts | 7 ++++++- src/passes/staticArrayIndexer.ts | 3 +++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/passes/implicitConversionToExplicit.ts b/src/passes/implicitConversionToExplicit.ts index 3ae32fa71..d38a1049d 100644 --- a/src/passes/implicitConversionToExplicit.ts +++ b/src/passes/implicitConversionToExplicit.ts @@ -247,7 +247,12 @@ export class ImplicitConversionToExplicit extends ASTMapper { visitIndexAccess(node: IndexAccess, ast: AST): void { this.commonVisit(node, ast); - if (node.vIndexExpression === undefined) return; + if ( + safeGetNodeType(node, ast.inference) instanceof TypeNameType || + node.vIndexExpression === undefined + ) { + return; + } const [baseType, location] = generalizeType( safeGetNodeType(node.vBaseExpression, ast.inference), diff --git a/src/passes/staticArrayIndexer.ts b/src/passes/staticArrayIndexer.ts index 0c697b0aa..ecef569be 100644 --- a/src/passes/staticArrayIndexer.ts +++ b/src/passes/staticArrayIndexer.ts @@ -12,6 +12,7 @@ import { Mutability, PointerType, StateVariableVisibility, + TypeNameType, TypeNode, VariableDeclaration, VariableDeclarationStatement, @@ -58,6 +59,8 @@ export class StaticArrayIndexer extends ASTMapper { } visitIndexAccess(node: IndexAccess, ast: AST): void { + if (safeGetNodeType(node, ast.inference) instanceof TypeNameType) + return this.commonVisit(node, ast); this.staticIndexToMemory(node, ast); } From 7a80e990271feec9b9f177f5329cbfce37907401 Mon Sep 17 00:00:00 2001 From: AlejandroLabourdette Date: Thu, 9 Feb 2023 22:31:26 -0500 Subject: [PATCH 08/28] generalize type in argBoundChecker visitFuncCall pass --- src/passes/argBoundChecker.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/passes/argBoundChecker.ts b/src/passes/argBoundChecker.ts index 001781131..73d74e6ef 100644 --- a/src/passes/argBoundChecker.ts +++ b/src/passes/argBoundChecker.ts @@ -7,6 +7,7 @@ import { FunctionCallKind, EnumDefinition, IntType, + generalizeType, } from 'solc-typed-ast'; import { ASTMapper } from '../ast/mapper'; import { isExternallyVisible } from '../utils/utils'; @@ -30,7 +31,7 @@ export class ArgBoundChecker extends ASTMapper { visitFunctionDefinition(node: FunctionDefinition, ast: AST): void { if (isExternallyVisible(node) && node.vBody !== undefined) { node.vParameters.vParameters.forEach((decl) => { - const type = safeGetNodeType(decl, ast.inference); + const type = generalizeType(safeGetNodeType(decl, ast.inference))[0]; if (checkableType(type)) { const functionCall = ast .getUtilFuncGen(node) From 85bb001cf7e0ce427e768557f5cd7de0c6a10fa0 Mon Sep 17 00:00:00 2001 From: AlejandroLabourdette Date: Thu, 9 Feb 2023 22:46:24 -0500 Subject: [PATCH 09/28] lint --- src/utils/nodeTemplates.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/nodeTemplates.ts b/src/utils/nodeTemplates.ts index e51557538..88b56a98e 100644 --- a/src/utils/nodeTemplates.ts +++ b/src/utils/nodeTemplates.ts @@ -28,7 +28,7 @@ import { import { AST } from '../ast/ast'; import { CairoTempVarStatement } from '../ast/cairoNodes'; import { generateExpressionTypeString, generateLiteralTypeString } from './getTypeString'; -import { safeGetNodeTypeInCtx, specializeType } from './nodeTypeProcessing'; +import { safeGetNodeTypeInCtx } from './nodeTypeProcessing'; import { notNull } from './typeConstructs'; import { toHexString, toSingleExpression } from './utils'; From 2702eaa87e0f17eccfab3822a11e94d81180ccca Mon Sep 17 00:00:00 2001 From: AlejandroLabourdette Date: Thu, 9 Feb 2023 23:24:01 -0500 Subject: [PATCH 10/28] don't flat typeNames single tuple at TupleFlattener --- src/passes/tupleFixes/tupleFlattener.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/passes/tupleFixes/tupleFlattener.ts b/src/passes/tupleFixes/tupleFlattener.ts index fbaf8632a..70bdb1478 100644 --- a/src/passes/tupleFixes/tupleFlattener.ts +++ b/src/passes/tupleFixes/tupleFlattener.ts @@ -1,6 +1,7 @@ -import { TupleExpression } from 'solc-typed-ast'; +import { TupleExpression, TypeNameType } from 'solc-typed-ast'; import { AST } from '../../ast/ast'; import { ASTMapper } from '../../ast/mapper'; +import { safeGetNodeType } from '../../export'; import { WillNotSupportError } from '../../utils/errors'; export class TupleFlattener extends ASTMapper { @@ -18,6 +19,9 @@ export class TupleFlattener extends ASTMapper { node.vOriginalComponents[0].typeString === node.typeString && !node.isInlineArray ) { + if (safeGetNodeType(node.vOriginalComponents[0], ast.inference) instanceof TypeNameType) { + return this.commonVisit(node, ast); + } const parent = node.parent; ast.replaceNode(node, node.vOriginalComponents[0], parent); this.dispatchVisit(node.vOriginalComponents[0], ast); From e945a7ba0b5622d703d4c34766b8e796cbc3a0b5 Mon Sep 17 00:00:00 2001 From: AlejandroLabourdette Date: Fri, 10 Feb 2023 01:12:01 -0500 Subject: [PATCH 11/28] WarpInferType created --- src/ast/ast.ts | 5 +++-- src/ast/warpInferType.ts | 11 +++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) create mode 100644 src/ast/warpInferType.ts diff --git a/src/ast/ast.ts b/src/ast/ast.ts index 108ee0040..492e374e5 100644 --- a/src/ast/ast.ts +++ b/src/ast/ast.ts @@ -28,6 +28,7 @@ import { createBlock } from '../utils/nodeTemplates'; import { safeGetNodeType } from '../utils/nodeTypeProcessing'; import { getContainingSourceUnit, isExternalCall, mergeImports } from '../utils/utils'; import { CairoFunctionDefinition } from './cairoNodes'; +import { WarpInferType } from './warpInferType'; /* A centralised store of information required for transpilation, a reference @@ -56,7 +57,7 @@ export class AST { context: ASTContext; // node requiring cairo import -> file to import from -> symbols to import imports: Map>> = new Map(); - public inference: InferType; + public inference: WarpInferType; readonly tempId = -1; @@ -74,7 +75,7 @@ export class AST { 'All contexts should be the same, otherwise they are from seperate solc-typed-ast compiles and they will have no relationship to each other.', ); this.context = roots[0].requiredContext; - this.inference = new InferType(compilerVersion); + this.inference = new WarpInferType(compilerVersion); assert( this.context.locate(this.tempId) === undefined, `Attempted to create an AST with a context that already has ${this.tempId} registered`, diff --git a/src/ast/warpInferType.ts b/src/ast/warpInferType.ts new file mode 100644 index 000000000..d3ef57b7a --- /dev/null +++ b/src/ast/warpInferType.ts @@ -0,0 +1,11 @@ +import { Expression, InferType, TupleType, TypeNode } from 'solc-typed-ast'; +import { CairoAssert } from './cairoNodes'; + +export class WarpInferType extends InferType { + typeOf(node: Expression): TypeNode { + if (node instanceof CairoAssert) { + return new TupleType([]); + } + return super.typeOf(node); + } +} From a6101cac8b0ca506cea6eee16a7f6d00821f4fe4 Mon Sep 17 00:00:00 2001 From: AlejandroLabourdette Date: Fri, 10 Feb 2023 01:13:20 -0500 Subject: [PATCH 12/28] lint --- src/ast/ast.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/ast/ast.ts b/src/ast/ast.ts index 492e374e5..68521fb4a 100644 --- a/src/ast/ast.ts +++ b/src/ast/ast.ts @@ -8,7 +8,6 @@ import { FunctionCall, generalizeType, Identifier, - InferType, Mutability, SourceUnit, Statement, From 25e74b96ecd48291bd5edafaa681cd748078f757 Mon Sep 17 00:00:00 2001 From: AlejandroLabourdette Date: Fri, 10 Feb 2023 01:51:10 -0500 Subject: [PATCH 13/28] generalize type in memoryToCalldata.ts --- src/cairoUtilFuncGen/memory/memoryToCalldata.ts | 2 +- src/utils/nodeTypeProcessing.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cairoUtilFuncGen/memory/memoryToCalldata.ts b/src/cairoUtilFuncGen/memory/memoryToCalldata.ts index e02b581c5..ef31cd1b5 100644 --- a/src/cairoUtilFuncGen/memory/memoryToCalldata.ts +++ b/src/cairoUtilFuncGen/memory/memoryToCalldata.ts @@ -107,7 +107,7 @@ export class MemoryToCallDataGen extends StringIndexedFuncGen { `func ${funcName}${implicits}(mem_loc : felt) -> (retData: ${outputType.toString()}){`, ` alloc_locals;`, ...structDef.vMembers.map((decl, index) => { - const memberType = safeGetNodeType(decl, this.ast.inference); + const memberType = generalizeType(safeGetNodeType(decl, this.ast.inference))[0]; if (isReferenceType(memberType)) { this.requireImport('warplib.memory', 'wm_read_id'); const allocSize = isDynamicArray(memberType) diff --git a/src/utils/nodeTypeProcessing.ts b/src/utils/nodeTypeProcessing.ts index 57ea377fa..245bac72e 100644 --- a/src/utils/nodeTypeProcessing.ts +++ b/src/utils/nodeTypeProcessing.ts @@ -416,7 +416,7 @@ export function getByteSize(type: TypeNode, inference: InferType): number | bigi 'Struct byte size calculation requires compiler version', ); return type.definition.vMembers - .map((varDecl) => safeGetNodeType(varDecl, inference)) + .map((varDecl) => generalizeType(safeGetNodeType(varDecl, inference))[0]) .reduce(sumMemberSize, 0n); } From 8162700377576739677759cdf5f5efc0f9e6e7c1 Mon Sep 17 00:00:00 2001 From: AlejandroLabourdette Date: Fri, 10 Feb 2023 07:54:34 -0500 Subject: [PATCH 14/28] remove warpInferType --- src/ast/ast.ts | 6 +++--- src/ast/warpInferType.ts | 11 ----------- src/utils/nodeTypeProcessing.ts | 3 +++ 3 files changed, 6 insertions(+), 14 deletions(-) delete mode 100644 src/ast/warpInferType.ts diff --git a/src/ast/ast.ts b/src/ast/ast.ts index 68521fb4a..108ee0040 100644 --- a/src/ast/ast.ts +++ b/src/ast/ast.ts @@ -8,6 +8,7 @@ import { FunctionCall, generalizeType, Identifier, + InferType, Mutability, SourceUnit, Statement, @@ -27,7 +28,6 @@ import { createBlock } from '../utils/nodeTemplates'; import { safeGetNodeType } from '../utils/nodeTypeProcessing'; import { getContainingSourceUnit, isExternalCall, mergeImports } from '../utils/utils'; import { CairoFunctionDefinition } from './cairoNodes'; -import { WarpInferType } from './warpInferType'; /* A centralised store of information required for transpilation, a reference @@ -56,7 +56,7 @@ export class AST { context: ASTContext; // node requiring cairo import -> file to import from -> symbols to import imports: Map>> = new Map(); - public inference: WarpInferType; + public inference: InferType; readonly tempId = -1; @@ -74,7 +74,7 @@ export class AST { 'All contexts should be the same, otherwise they are from seperate solc-typed-ast compiles and they will have no relationship to each other.', ); this.context = roots[0].requiredContext; - this.inference = new WarpInferType(compilerVersion); + this.inference = new InferType(compilerVersion); assert( this.context.locate(this.tempId) === undefined, `Attempted to create an AST with a context that already has ${this.tempId} registered`, diff --git a/src/ast/warpInferType.ts b/src/ast/warpInferType.ts deleted file mode 100644 index d3ef57b7a..000000000 --- a/src/ast/warpInferType.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { Expression, InferType, TupleType, TypeNode } from 'solc-typed-ast'; -import { CairoAssert } from './cairoNodes'; - -export class WarpInferType extends InferType { - typeOf(node: Expression): TypeNode { - if (node instanceof CairoAssert) { - return new TupleType([]); - } - return super.typeOf(node); - } -} diff --git a/src/utils/nodeTypeProcessing.ts b/src/utils/nodeTypeProcessing.ts index 245bac72e..7e241e96c 100644 --- a/src/utils/nodeTypeProcessing.ts +++ b/src/utils/nodeTypeProcessing.ts @@ -297,6 +297,9 @@ export function safeGetNodeType( if (node instanceof Literal) { return getNodeType(node, inference); } + if (node instanceof CairoAssert) { + return new TupleType([]); + } if (node instanceof VariableDeclaration) { return inference.variableDeclarationToTypeNode(node); } From 775d383e1574a00351cbd2c638df755fc52bb2b1 Mon Sep 17 00:00:00 2001 From: Franco Barpp Gomes Date: Mon, 20 Mar 2023 10:08:13 -0300 Subject: [PATCH 15/28] Fix cairo-lang dependencies issues after major upgrades (#995) --- .github/workflows/test-behaviour.yml | 2 ++ .github/workflows/test-cli.yml | 2 ++ requirements.txt | 4 ++++ warp_venv.sh | 2 ++ 4 files changed, 10 insertions(+) diff --git a/.github/workflows/test-behaviour.yml b/.github/workflows/test-behaviour.yml index 120bf118a..44454c495 100644 --- a/.github/workflows/test-behaviour.yml +++ b/.github/workflows/test-behaviour.yml @@ -103,6 +103,8 @@ jobs: run: | pip install -r requirements.txt pip install cairo-lang=="$CAIRO_LANG_VERSION" + pip install web3==5.* + pip install typeguard==2.* - name: Setup source hash (push) if: ${{ github.event_name == 'push' }} diff --git a/.github/workflows/test-cli.yml b/.github/workflows/test-cli.yml index a46801e9e..c0d718361 100644 --- a/.github/workflows/test-cli.yml +++ b/.github/workflows/test-cli.yml @@ -37,6 +37,8 @@ jobs: make compile pip3 install cairo-lang=="$CAIRO_LANG_VERSION" pip3 install starknet-devnet==0.4.4 + pip3 install web3==5.* + pip3 install typeguard==2.* - name: Build warplib run: yarn warplib diff --git a/requirements.txt b/requirements.txt index 4963fb223..7668c9135 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,3 +5,7 @@ flask-cors >= 3.0.10 cairo-lang==0.10.3 # Requrired by the cli test starknet-devnet==0.4.4 +# Fix until cairo-lang supports web3 v6 or adds a matching pattern for v5 +web3==5.* +# Fix until cairo-lang 0.11 is released +typeguard==2.* diff --git a/warp_venv.sh b/warp_venv.sh index 1f6d5f27b..a2542dc58 100755 --- a/warp_venv.sh +++ b/warp_venv.sh @@ -7,5 +7,7 @@ $PYTHON_BIN -m venv "$SCRIPT_DIR"/warp_venv . $SCRIPT_DIR/warp_venv/bin/activate pip install cairo-lang==0.10.3 +pip install web3==5.* +pip install typeguard==2.* deactivate From d76b610c10a8d28207028ee24c2b205e921e16bc Mon Sep 17 00:00:00 2001 From: AlejandroLabourdette Date: Tue, 21 Mar 2023 01:17:15 -0400 Subject: [PATCH 16/28] fix abiDecode from merge --- src/cairoUtilFuncGen/memory/memoryToCalldata.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/cairoUtilFuncGen/memory/memoryToCalldata.ts b/src/cairoUtilFuncGen/memory/memoryToCalldata.ts index 377f55e2b..fd786a3f6 100644 --- a/src/cairoUtilFuncGen/memory/memoryToCalldata.ts +++ b/src/cairoUtilFuncGen/memory/memoryToCalldata.ts @@ -79,12 +79,13 @@ export class MemoryToCallDataGen extends StringIndexedFuncGen { `Copying ${printTypeNode(type)} from memory to calldata not implemented yet`, ); }; + const generalizedType = generalizeType(type)[0]; return delegateBasedOnType( - type, - (type) => this.createDynamicArrayCopyFunction(type), - (type) => this.createStaticArrayCopyFunction(type), - (type) => this.createStructCopyFunction(type), + generalizedType, + (generalizedType) => this.createDynamicArrayCopyFunction(generalizedType), + (generalizedType) => this.createStaticArrayCopyFunction(generalizedType), + (generalizedType) => this.createStructCopyFunction(generalizedType), unexpectedTypeFunc, unexpectedTypeFunc, ); From 15ef0934e564b23b4bc28f81f0af262ffc060ba0 Mon Sep 17 00:00:00 2001 From: julio4 <30329843+julio4@users.noreply.github.com> Date: Tue, 21 Mar 2023 15:03:55 +0100 Subject: [PATCH 17/28] fix: typos (#991) --- docs/docs/features/cairo_stubs.mdx | 2 +- docs/docs/getting_started/cli.mdx | 2 +- .../getting_started/inputs-and-outputs.mdx | 4 ++-- docs/docs/solidity_equivalents/inputs.mdx | 2 +- src/ast/ast.ts | 12 +++++----- src/ast/cairoNodes/cairoFunctionDefinition.ts | 2 +- .../cairoGeneratedFunctionDefinition.ts | 2 +- src/cairoUtilFuncGen/abi/abiDecode.ts | 2 +- src/cairoUtilFuncGen/abi/abiEncode.ts | 6 ++--- src/cairoUtilFuncGen/abi/abiEncodePacked.ts | 2 +- src/cairoUtilFuncGen/abi/indexEncode.ts | 4 ++-- .../calldata/calldataToStorage.ts | 2 +- .../calldata/implicitArrayConversion.ts | 16 +++++++------- src/cairoUtilFuncGen/enumInputCheck.ts | 6 ++--- .../memory/implicitConversion.ts | 10 ++++----- src/cairoUtilFuncGen/storage/dynArray.ts | 10 ++++----- .../storage/mappingIndexAccess.ts | 8 +++---- src/cairoUtilFuncGen/storage/storageDelete.ts | 6 ++--- .../storage/storageToCalldata.ts | 4 ++-- .../storage/storageToMemory.ts | 2 +- src/cairoUtilFuncGen/utils/encodeToFelt.ts | 6 ++--- src/cairoWriter/utils.ts | 2 +- src/cairoWriter/writers/assignmentWriter.ts | 2 +- .../writers/emitStatementWriter.ts | 2 +- src/cairoWriter/writers/identifierWriter.ts | 2 +- src/cairoWriter/writers/sourceUnitWriter.ts | 2 +- src/cli.ts | 8 +++---- src/freeStructWritter.ts | 2 +- src/icf/README.md | 2 +- src/icf/genCairo.ts | 8 +++---- src/icf/utils/util.ts | 2 +- .../conditionalSplitter.ts | 2 +- .../utils/conditionalFunctionaliser.ts | 2 +- src/passes/deleteHandler.ts | 2 +- .../dynamicArrayModifier.ts | 14 ++++++------ .../memoryRefInputModifier.ts | 8 +++---- src/passes/externalContractHandler/index.ts | 4 ++-- src/passes/freeFunctionInliner.ts | 2 +- src/passes/functionModifierHandler/index.ts | 2 +- .../generateGetters/gettersGenerator.ts | 2 +- src/passes/implicitConversionToExplicit.ts | 6 ++--- .../constructorInheritance.ts | 2 +- .../inheritanceInliner/eventInheritance.ts | 2 +- .../inheritanceInliner/functionInheritance.ts | 2 +- .../inheritanceInliner/inheritanceInliner.ts | 16 +++++++------- .../modifiersInheritance.ts | 8 +++---- src/passes/inheritanceInliner/utils.ts | 2 +- src/passes/inlineAssemblyTransformer.ts | 2 +- src/passes/namedArgsRemover.ts | 2 +- src/passes/newToDeploy.ts | 2 +- src/passes/orderNestedStructs.ts | 8 +++---- .../externalFunctionCreator.ts | 4 ++-- .../references/dataAccessFunctionaliser.ts | 4 ++-- .../references/expectedLocationAnalyser.ts | 2 +- .../references/externalReturnReceiver.ts | 4 ++-- .../replaceIdentifierContractMemberAccess.ts | 8 +++---- src/passes/staticArrayIndexer.ts | 16 +++++++------- src/passes/storageAllocator.ts | 2 +- src/semanticTestRunner.ts | 4 ++-- src/utils/astChecking.ts | 8 +++---- src/utils/errors.ts | 4 ++-- src/utils/functionGeneration.ts | 2 +- src/utils/importFuncGenerator.ts | 6 ++--- src/utils/nodeTemplates.ts | 4 ++-- src/utils/postCairoWrite.ts | 10 ++++----- src/utils/typeStrings/typeStringParser.ts | 22 +++++++++---------- .../typeStrings/typeStringParserHeader.ts | 20 ++++++++--------- .../typeStrings/typeString_grammar.pegjs | 2 +- src/utils/utils.ts | 4 ++-- src/warplib/generateWarplib.ts | 2 +- tests/behaviour/errors.ts | 2 +- tests/behaviour/expectations/behaviour.ts | 16 +++++++------- tests/behaviour/expectations/semantic.ts | 2 +- tests/behaviour/expectations/utils.ts | 2 +- warplib/memory.cairo | 2 +- 75 files changed, 192 insertions(+), 192 deletions(-) diff --git a/docs/docs/features/cairo_stubs.mdx b/docs/docs/features/cairo_stubs.mdx index 631e6a9ec..041c86d2e 100644 --- a/docs/docs/features/cairo_stubs.mdx +++ b/docs/docs/features/cairo_stubs.mdx @@ -9,7 +9,7 @@ The system works in the following way: 1. To start a Cairo Block add your Cairo code above a Solidity function with 3 forward slashes at the beginning of each line and the phrase `warp-cairo` at the top. 2. The user then uses a number of MACROS to interact with the transpiled contract. -3. The Solidity function will then be replaced with the Cario function that is above it. +3. The Solidity function will then be replaced with the Cairo function that is above it. The following MACROS are supported: diff --git a/docs/docs/getting_started/cli.mdx b/docs/docs/getting_started/cli.mdx index 241051e25..a2ffa8320 100644 --- a/docs/docs/getting_started/cli.mdx +++ b/docs/docs/getting_started/cli.mdx @@ -14,7 +14,7 @@ Available Commands: analyse [options] Debug tool to analyse the AST status [options] Get the status of a transaction compile [options] Compile cairo files with warplib in the cairo-path - gen_interface [options] Use native Cairo contracts in your Soldity by creating a Solidity interface and a Cairo translation contract for the target Cairo contract + gen_interface [options] Use native Cairo contracts in your Solidity by creating a Solidity interface and a Cairo translation contract for the target Cairo contract deploy [options] Deploy a warped cairo contract deploy_account [options] Deploy an account to Starknet invoke [options] Invoke a function on a warped contract using the Solidity abi diff --git a/docs/docs/getting_started/inputs-and-outputs.mdx b/docs/docs/getting_started/inputs-and-outputs.mdx index 1a2c99070..428496407 100644 --- a/docs/docs/getting_started/inputs-and-outputs.mdx +++ b/docs/docs/getting_started/inputs-and-outputs.mdx @@ -15,7 +15,7 @@ This is supported in Warp's `deploy`, `invoke` and `call` commands. Warp takes these inputs and transcodes them into Cairo to forward them onto the desired network. ``` -warp invoke --inputs \"ExampleString\",\[1,2,3,4\],-1,100. +warp invoke --inputs \"ExampleString\",\[1,2,3,4\],-1,100. ``` ### Using Cairo ABI @@ -34,7 +34,7 @@ Note that there are some nuances that come with using the Cairo ABI: upper 128 bits e.g `0x10000000000000000000000000000000f` as a `uint256` -> `15,1`. ``` -warp invoke --use_cairo_abi --inputs 13,0x45,0x78,0x61,0x6d,0x70,0x6c,0x65,0x53,0x74,0x72,0x69,0x6e,0x67,4,1,2,3,4,255,100. +warp invoke --use_cairo_abi --inputs 13,0x45,0x78,0x61,0x6d,0x70,0x6c,0x65,0x53,0x74,0x72,0x69,0x6e,0x67,4,1,2,3,4,255,100. ``` ### Passing values of different types in both ABIs diff --git a/docs/docs/solidity_equivalents/inputs.mdx b/docs/docs/solidity_equivalents/inputs.mdx index d77c0f39f..a801c2fba 100644 --- a/docs/docs/solidity_equivalents/inputs.mdx +++ b/docs/docs/solidity_equivalents/inputs.mdx @@ -122,7 +122,7 @@ Arrays can have a compile-time fixed size, or they can have a dynamic size. `uint[3][2]` is represented as `(Uint256, Uint256, Uint256), (Uint256, Uint256, Uint256))`. So, If you want to pass `[[12, 13, 14], [13, 14, 15]]` then you have to provide `12, 0, 13, 0, 14, 0, 13, 0, 14, 0, 15, 0` to interact with warped contracts. -- Dynamic sized arrays are repsented as `(arr_len: felt, arr: (base type in cairo)*)`, the first value represents number of elements in the array. +- Dynamic sized arrays are represented as `(arr_len: felt, arr: (base type in cairo)*)`, the first value represents number of elements in the array. **Example**: diff --git a/src/ast/ast.ts b/src/ast/ast.ts index 4ec945fab..4eabddc52 100644 --- a/src/ast/ast.ts +++ b/src/ast/ast.ts @@ -71,7 +71,7 @@ export class AST { ); assert( roots.every((sourceUnit) => sourceUnit.requiredContext === roots[0].requiredContext), - 'All contexts should be the same, otherwise they are from seperate solc-typed-ast compiles and they will have no relationship to each other.', + 'All contexts should be the same, otherwise they are from separate solc-typed-ast compiles and they will have no relationship to each other.', ); this.context = roots[0].requiredContext; this.inference = new InferType(compilerVersion); @@ -119,7 +119,7 @@ export class AST { [replacementVariable], ); this.insertStatementBefore(node, declaration); - const replacementIdentifer = new Identifier( + const replacementIdentifier = new Identifier( this.tempId, node.src, node.typeString, @@ -127,10 +127,10 @@ export class AST { replacementVariable.id, node.raw, ); - this.replaceNode(node, replacementIdentifer); + this.replaceNode(node, replacementIdentifier); declaration.vInitialValue = node; this.registerChild(node, declaration); - return [replacementIdentifer, declaration]; + return [replacementIdentifier, declaration]; } getContainingRoot(node: ASTNode): SourceUnit { @@ -215,7 +215,7 @@ export class AST { } const parent = existingStatement.parent; - // Blocks are not instances of Statements, but they satisy typescript shaped typing rules to be classed as Statements + // Blocks are not instances of Statements, but they satisfy typescript shaped typing rules to be classed as Statements const replacementBlock = createBlock([existingStatement, newStatement], this); this.replaceNode(existingStatement, replacementBlock, parent); } @@ -259,7 +259,7 @@ export class AST { } const parent = existingStatement.parent; - // Blocks are not instances of Statements, but they satisy typescript shaped typing rules to be classed as Statements + // Blocks are not instances of Statements, but they satisfy typescript shaped typing rules to be classed as Statements const replacementBlock = createBlock([newStatement, existingStatement], this); this.replaceNode(existingStatement, replacementBlock, parent); } diff --git a/src/ast/cairoNodes/cairoFunctionDefinition.ts b/src/ast/cairoNodes/cairoFunctionDefinition.ts index 25b4e48a8..a7f9f18a8 100644 --- a/src/ast/cairoNodes/cairoFunctionDefinition.ts +++ b/src/ast/cairoNodes/cairoFunctionDefinition.ts @@ -58,7 +58,7 @@ export class CairoFunctionDefinition extends FunctionDefinition { ) { assert( !(acceptsRawDArray && acceptsUnpackedStructArray), - 'A function cannot recieve both structured and raw dynamic arrays', + 'A function cannot receive both structured and raw dynamic arrays', ); super( id, diff --git a/src/ast/cairoNodes/cairoGeneratedFunctionDefinition.ts b/src/ast/cairoNodes/cairoGeneratedFunctionDefinition.ts index b2b39587e..ead1efbc4 100644 --- a/src/ast/cairoNodes/cairoGeneratedFunctionDefinition.ts +++ b/src/ast/cairoNodes/cairoGeneratedFunctionDefinition.ts @@ -10,7 +10,7 @@ import { CairoRawStringFunctionDefinition } from './cairoRawStringFunctionDefini export class CairoGeneratedFunctionDefinition extends CairoRawStringFunctionDefinition { /** - * List of function defintions called by the generated function + * List of function definitions called by the generated function */ public functionsCalled: FunctionDefinition[]; diff --git a/src/cairoUtilFuncGen/abi/abiDecode.ts b/src/cairoUtilFuncGen/abi/abiDecode.ts index 61f223f36..d99e4ab8b 100644 --- a/src/cairoUtilFuncGen/abi/abiDecode.ts +++ b/src/cairoUtilFuncGen/abi/abiDecode.ts @@ -53,7 +53,7 @@ export class AbiDecode extends StringIndexedFuncGenWithAuxiliar { public gen(expressions: Expression[]): FunctionCall { assert( expressions.length === 2, - 'ABI decode must recieve two arguments: data to decode, and types to decode into', + 'ABI decode must receive two arguments: data to decode, and types to decode into', ); const [data, types] = expressions.map( (t) => generalizeType(safeGetNodeType(t, this.ast.inference))[0], diff --git a/src/cairoUtilFuncGen/abi/abiEncode.ts b/src/cairoUtilFuncGen/abi/abiEncode.ts index c55c3793b..8cd7d0488 100644 --- a/src/cairoUtilFuncGen/abi/abiEncode.ts +++ b/src/cairoUtilFuncGen/abi/abiEncode.ts @@ -31,7 +31,7 @@ const IMPLICITS = '{bitwise_ptr : BitwiseBuiltin*, range_check_ptr : felt, warp_memory : DictAccess*}'; /** - * Given any data type produces the same output of solidty abi.encode + * Given any data type produces the same output of solidity abi.encode * in the form of an array of felts where each element represents a byte */ export class AbiEncode extends AbiBase { @@ -282,7 +282,7 @@ export class AbiEncode extends AbiBase { if (existing !== undefined) return existing; const elementT = getElementType(type); - const elemntTSize = CairoType.fromSol(elementT, this.ast).width; + const elementTSize = CairoType.fromSol(elementT, this.ast).width; const [readElement, readFunc] = this.readMemory(elementT, 'elem_loc'); const [headEncodingCode, functionsCalled] = this.generateEncodingCode( @@ -308,7 +308,7 @@ export class AbiEncode extends AbiBase { ` return (final_offset=bytes_offset);`, ` }`, ` let (index256) = felt_to_uint256(index);`, - ` let (elem_loc) = wm_index_dyn(mem_ptr, index256, ${uint256(elemntTSize)});`, + ` let (elem_loc) = wm_index_dyn(mem_ptr, index256, ${uint256(elementTSize)});`, ` let (elem) = ${readElement};`, ` ${headEncodingCode}`, ` return ${name}(new_bytes_index, new_bytes_offset, bytes_array, element_offset, index + 1, length, mem_ptr);`, diff --git a/src/cairoUtilFuncGen/abi/abiEncodePacked.ts b/src/cairoUtilFuncGen/abi/abiEncodePacked.ts index 581852b0d..54c23b3a1 100644 --- a/src/cairoUtilFuncGen/abi/abiEncodePacked.ts +++ b/src/cairoUtilFuncGen/abi/abiEncodePacked.ts @@ -27,7 +27,7 @@ const IMPLICITS = '{bitwise_ptr : BitwiseBuiltin*, range_check_ptr : felt, warp_memory : DictAccess*}'; /** - * Given any data type produces the same output of solidty abi.encodePacked + * Given any data type produces the same output of solidity abi.encodePacked * in the form of an array of felts where each element represents a byte */ export class AbiEncodePacked extends AbiBase { diff --git a/src/cairoUtilFuncGen/abi/indexEncode.ts b/src/cairoUtilFuncGen/abi/indexEncode.ts index 6fcf360d6..e843fbc06 100644 --- a/src/cairoUtilFuncGen/abi/indexEncode.ts +++ b/src/cairoUtilFuncGen/abi/indexEncode.ts @@ -242,7 +242,7 @@ export class IndexEncode extends AbiBase { if (existing !== undefined) return existing; const elementT = getElementType(type); - const elemntTSize = CairoType.fromSol(elementT, this.ast).width; + const elementTSize = CairoType.fromSol(elementT, this.ast).width; const [readElement, readFunc] = this.readMemory(elementT, 'elem_loc'); const [headEncodingCode, functionsCalled] = this.generateEncodingCode( @@ -264,7 +264,7 @@ export class IndexEncode extends AbiBase { ` return (final_index=bytes_index);`, ` }`, ` let (index256) = felt_to_uint256(index);`, - ` let (elem_loc) = wm_index_dyn(mem_ptr, index256, ${uint256(elemntTSize)});`, + ` let (elem_loc) = wm_index_dyn(mem_ptr, index256, ${uint256(elementTSize)});`, ` let (elem) = ${readElement};`, ` ${headEncodingCode}`, ` return ${name}(bytes_index, bytes_array, index + 1, length, mem_ptr);`, diff --git a/src/cairoUtilFuncGen/calldata/calldataToStorage.ts b/src/cairoUtilFuncGen/calldata/calldataToStorage.ts index 4e849e6f1..2a276e07d 100644 --- a/src/cairoUtilFuncGen/calldata/calldataToStorage.ts +++ b/src/cairoUtilFuncGen/calldata/calldataToStorage.ts @@ -113,7 +113,7 @@ export class CalldataToStorageGen extends StringIndexedFuncGen { return { name: funcName, code: code, functionsCalled: funcsCalled }; } - // TODO: Check if funcion size can be reduced for big static arrays + // TODO: Check if function size can be reduced for big static arrays private createStaticArrayCopyFunction(arrayType: ArrayType): GeneratedFunctionInfo { assert(arrayType.size !== undefined); diff --git a/src/cairoUtilFuncGen/calldata/implicitArrayConversion.ts b/src/cairoUtilFuncGen/calldata/implicitArrayConversion.ts index dda90377e..91bf5541d 100644 --- a/src/cairoUtilFuncGen/calldata/implicitArrayConversion.ts +++ b/src/cairoUtilFuncGen/calldata/implicitArrayConversion.ts @@ -253,7 +253,7 @@ export class ImplicitArrayConversion extends StringIndexedFuncGen { TypeConversionContext.CallDataRef, ); - const [copyInstructions, requiredFunctions] = this.createDyamicToDynamicCopyCode( + const [copyInstructions, requiredFunctions] = this.createDynamicToDynamicCopyCode( targetType, sourceType, ); @@ -302,17 +302,17 @@ export class ImplicitArrayConversion extends StringIndexedFuncGen { ]; } if (targetElementT.signed) { - const convertionFunc = this.requireImport( + const conversionFunc = this.requireImport( 'warplib.maths.int_conversions', `warp_int${sourceElementT.nBits}_to_int${targetElementT.nBits}`, ); return [ (index, offset) => [ - ` let (arg_${index}) = ${convertionFunc.name}(arg[${index}]);`, + ` let (arg_${index}) = ${conversionFunc.name}(arg[${index}]);`, ` ${writeToStorage.name}(${add('storage_loc', offset)}, arg_${index});`, ].join('\n'), - [writeToStorage, convertionFunc], + [writeToStorage, conversionFunc], ]; } const toUintFunc = this.requireImport('warplib.maths.utils', 'felt_to_uint256'); @@ -476,7 +476,7 @@ export class ImplicitArrayConversion extends StringIndexedFuncGen { ]; } - private createDyamicToDynamicCopyCode( + private createDynamicToDynamicCopyCode( targetType: ArrayType, sourceType: ArrayType, ): [() => string, CairoFunctionDefinition[]] { @@ -487,7 +487,7 @@ export class ImplicitArrayConversion extends StringIndexedFuncGen { if (targetElmType instanceof IntType) { assert(sourceElmType instanceof IntType); - const convertionFunc = targetElmType.signed + const conversionFunc = targetElmType.signed ? this.requireImport( 'warplib.maths.int_conversions', `warp_int${sourceElmType.nBits}_to_int${targetElmType.nBits}`, @@ -497,11 +497,11 @@ export class ImplicitArrayConversion extends StringIndexedFuncGen { () => [ sourceElmType.signed - ? ` let (val) = ${convertionFunc.name}(ptr[0]);` + ? ` let (val) = ${conversionFunc.name}(ptr[0]);` : ` let (val) = felt_to_uint256(ptr[0]);`, ` ${writeDef.name}(storage_loc, val);`, ].join('\n'), - [writeDef, convertionFunc], + [writeDef, conversionFunc], ]; } diff --git a/src/cairoUtilFuncGen/enumInputCheck.ts b/src/cairoUtilFuncGen/enumInputCheck.ts index eb74637c5..098612810 100644 --- a/src/cairoUtilFuncGen/enumInputCheck.ts +++ b/src/cairoUtilFuncGen/enumInputCheck.ts @@ -37,9 +37,9 @@ export class EnumInputCheck extends StringIndexedFuncGen { assert(inputType instanceof IntType); const key = enumDef.name + (inputType.nBits === 256 ? '256' : ''); - const exisiting = this.generatedFunctionsDef.get(key); - if (exisiting !== undefined) { - return exisiting; + const existing = this.generatedFunctionsDef.get(key); + if (existing !== undefined) { + return existing; } const funcInfo = this.getOrCreate(inputType, enumDef); diff --git a/src/cairoUtilFuncGen/memory/implicitConversion.ts b/src/cairoUtilFuncGen/memory/implicitConversion.ts index 400e1d95a..ff942cc9c 100644 --- a/src/cairoUtilFuncGen/memory/implicitConversion.ts +++ b/src/cairoUtilFuncGen/memory/implicitConversion.ts @@ -49,7 +49,7 @@ export class MemoryImplicitConversionGen extends StringIndexedFuncGen { super(ast, sourceUnit); } - public genIfNecesary(sourceExpression: Expression, targetType: TypeNode): [Expression, boolean] { + public genIfNecessary(sourceExpression: Expression, targetType: TypeNode): [Expression, boolean] { const sourceType = safeGetNodeType(sourceExpression, this.ast.inference); const generalTarget = generalizeType(targetType)[0]; @@ -460,10 +460,10 @@ export class MemoryImplicitConversionGen extends StringIndexedFuncGen { } export function getBaseType(type: TypeNode): TypeNode { - const deferencedType = generalizeType(type)[0]; - return deferencedType instanceof ArrayType - ? getBaseType(deferencedType.elementT) - : deferencedType; + const dereferencedType = generalizeType(type)[0]; + return dereferencedType instanceof ArrayType + ? getBaseType(dereferencedType.elementT) + : dereferencedType; } function typesToCairoTypes( diff --git a/src/cairoUtilFuncGen/storage/dynArray.ts b/src/cairoUtilFuncGen/storage/dynArray.ts index 6ee79d0a8..71ce67dff 100644 --- a/src/cairoUtilFuncGen/storage/dynArray.ts +++ b/src/cairoUtilFuncGen/storage/dynArray.ts @@ -33,12 +33,12 @@ export class DynArrayGen extends StringIndexedFuncGen { const cairoType = CairoType.fromSol(type, this.ast, TypeConversionContext.StorageAllocation); const key = cairoType.fullStringRepresentation; - const lenghtKey = key + '_LENGTH'; + const lengthKey = key + '_LENGTH'; const existing = this.generatedFunctionsDef.get(key); if (existing !== undefined) { - const exsitingLength = this.generatedFunctionsDef.get(lenghtKey); - assert(exsitingLength !== undefined); - return [existing, exsitingLength]; + const existingLength = this.generatedFunctionsDef.get(lengthKey); + assert(existingLength !== undefined); + return [existing, existingLength]; } const [arrayInfo, lengthInfo] = this.getOrCreate(cairoType); @@ -70,7 +70,7 @@ export class DynArrayGen extends StringIndexedFuncGen { ); this.generatedFunctionsDef.set(key, dynArray); - this.generatedFunctionsDef.set(lenghtKey, dynArrayLength); + this.generatedFunctionsDef.set(lengthKey, dynArrayLength); return [dynArray, dynArrayLength]; } diff --git a/src/cairoUtilFuncGen/storage/mappingIndexAccess.ts b/src/cairoUtilFuncGen/storage/mappingIndexAccess.ts index cb407fde8..d82a0acb2 100644 --- a/src/cairoUtilFuncGen/storage/mappingIndexAccess.ts +++ b/src/cairoUtilFuncGen/storage/mappingIndexAccess.ts @@ -29,7 +29,7 @@ import { CairoUtilFuncGenBase, GeneratedFunctionInfo, locationIfComplexType } fr import { DynArrayGen } from './dynArray'; export class MappingIndexAccessGen extends CairoUtilFuncGenBase { - private indexAccesFunctions = new Map(); + private indexAccessFunctions = new Map(); private stringHashFunctions = new Map(); constructor(private dynArrayGen: DynArrayGen, ast: AST, sourceUnit: SourceUnit) { super(ast, sourceUnit); @@ -67,7 +67,7 @@ export class MappingIndexAccessGen extends CairoUtilFuncGenBase { TypeConversionContext.StorageAllocation, ).fullStringRepresentation; const key = indexKey + '-' + nodeKey; - const existing = this.indexAccesFunctions.get(key); + const existing = this.indexAccessFunctions.get(key); if (existing !== undefined) { return existing; } @@ -93,7 +93,7 @@ export class MappingIndexAccessGen extends CairoUtilFuncGenBase { this.ast, this.sourceUnit, ); - this.indexAccesFunctions.set(key, funcDef); + this.indexAccessFunctions.set(key, funcDef); return funcDef; } @@ -105,7 +105,7 @@ export class MappingIndexAccessGen extends CairoUtilFuncGenBase { TypeConversionContext.StorageAllocation, ); - const identifier = this.indexAccesFunctions.size; + const identifier = this.indexAccessFunctions.size; const funcName = `WS_INDEX_${indexCairoType.typeName}_to_${valueCairoType.typeName}${identifier}`; const mappingName = `WARP_MAPPING${identifier}`; const indexTypeString = indexCairoType.toString(); diff --git a/src/cairoUtilFuncGen/storage/storageDelete.ts b/src/cairoUtilFuncGen/storage/storageDelete.ts index 3b3eece5e..d2885aa4f 100644 --- a/src/cairoUtilFuncGen/storage/storageDelete.ts +++ b/src/cairoUtilFuncGen/storage/storageDelete.ts @@ -36,7 +36,7 @@ export class StorageDeleteGen extends StringIndexedFuncGen { // } private creatingFunctions: Map; - // Map to store unsolved function dependecies + // Map to store unsolved function dependencies // of generated functions private functionDependencies: Map; @@ -216,7 +216,7 @@ export class StorageDeleteGen extends StringIndexedFuncGen { this.creatingFunctions.set(generateKey(type), funcName); const elementT = generalizeType(type.elementT)[0]; - const elementTWidht = CairoType.fromSol( + const elementTWidth = CairoType.fromSol( elementT, this.ast, TypeConversionContext.StorageAllocation, @@ -229,7 +229,7 @@ export class StorageDeleteGen extends StringIndexedFuncGen { ? [` let (elem_id) = ${storageReadFunc.name}(loc);`, ` ${auxDeleteFuncName}(elem_id);`] : [` ${auxDeleteFuncName}(loc);`]; const length = narrowBigIntSafe(type.size); - const nextLoc = add('loc', elementTWidht); + const nextLoc = add('loc', elementTWidth); const deleteFunc = [ `func ${funcName}_elem${IMPLICITS}(loc : felt, index : felt){`, diff --git a/src/cairoUtilFuncGen/storage/storageToCalldata.ts b/src/cairoUtilFuncGen/storage/storageToCalldata.ts index a1f453560..097212ced 100644 --- a/src/cairoUtilFuncGen/storage/storageToCalldata.ts +++ b/src/cairoUtilFuncGen/storage/storageToCalldata.ts @@ -147,7 +147,7 @@ export class StorageToCalldataGen extends StringIndexedFuncGen { assert(structDef instanceof CairoDynArray); const storageReadFunc = this.storageReadGen.getOrCreateFuncDef(elementT); - const sturctDynArray = this.externalDynArrayStructConstructor.getOrCreateFuncDef(arrayType); + const structDynArray = this.externalDynArrayStructConstructor.getOrCreateFuncDef(arrayType); const [dynArray, dynArrayLength] = this.dynArrayGen.getOrCreateFuncDef(elementT); const arrayName = dynArray.name; @@ -201,7 +201,7 @@ export class StorageToCalldataGen extends StringIndexedFuncGen { code: code, functionsCalled: [ ...importedFuncs, - sturctDynArray, + structDynArray, dynArray, dynArrayLength, storageReadFunc, diff --git a/src/cairoUtilFuncGen/storage/storageToMemory.ts b/src/cairoUtilFuncGen/storage/storageToMemory.ts index 417a72ddb..e1fa90264 100644 --- a/src/cairoUtilFuncGen/storage/storageToMemory.ts +++ b/src/cairoUtilFuncGen/storage/storageToMemory.ts @@ -341,7 +341,7 @@ export class StorageToMemoryGen extends StringIndexedFuncGen { ]; } throw new TranspileFailedError( - `Trying to create recursive code for unsupported referency type: ${printTypeNode( + `Trying to create recursive code for unsupported reference type: ${printTypeNode( elementT, )}`, ); diff --git a/src/cairoUtilFuncGen/utils/encodeToFelt.ts b/src/cairoUtilFuncGen/utils/encodeToFelt.ts index 3f0cc60ac..5bab9a666 100644 --- a/src/cairoUtilFuncGen/utils/encodeToFelt.ts +++ b/src/cairoUtilFuncGen/utils/encodeToFelt.ts @@ -204,7 +204,7 @@ export class EncodeAsFelt extends StringIndexedFuncGenWithAuxiliar { } /** - * Given a type it generates the appropiate auxiliar encoding function for this specific type. + * Given a type it generates the appropriate auxiliar encoding function for this specific type. * @param type to encode (only arrays and structs allowed) * @returns name of the generated function */ @@ -236,8 +236,8 @@ export class EncodeAsFelt extends StringIndexedFuncGenWithAuxiliar { } /** - * Generates caior code depending on the type. If it is a value type it generates - * the appropiate instructions. If it is a an array or struct, it generates a function + * Generates cairo code depending on the type. If it is a value type it generates + * the appropriate instructions. If it is a an array or struct, it generates a function * call * @param type type to generate encoding code * @param currentElementName cairo variable to encode to felt diff --git a/src/cairoWriter/utils.ts b/src/cairoWriter/utils.ts index 84bff7349..59e01f342 100644 --- a/src/cairoWriter/utils.ts +++ b/src/cairoWriter/utils.ts @@ -33,7 +33,7 @@ export function getInterfaceNameForContract( const interfaceName = interfaceNameMappings.get(sourceUnit)?.get(contractName); assert( interfaceName !== undefined, - `An error occured during name substitution for the interface ${contractName}`, + `An error occurred during name substitution for the interface ${contractName}`, ); return interfaceName; diff --git a/src/cairoWriter/writers/assignmentWriter.ts b/src/cairoWriter/writers/assignmentWriter.ts index 4eb0af228..341edd5cc 100644 --- a/src/cairoWriter/writers/assignmentWriter.ts +++ b/src/cairoWriter/writers/assignmentWriter.ts @@ -8,7 +8,7 @@ export class AssignmentWriter extends CairoASTNodeWriter { assert(node.operator === '=', `Unexpected operator ${node.operator}`); const [lhs, rhs] = [node.vLeftHandSide, node.vRightHandSide]; const nodes = [lhs, rhs].map((v) => writer.write(v)); - // This is specifically needed because of the construtions involved with writing + // This is specifically needed because of the constructions involved with writing // conditionals (derived from short circuit expressions). Other tuple assignments // and function call assignments will have been split if ( diff --git a/src/cairoWriter/writers/emitStatementWriter.ts b/src/cairoWriter/writers/emitStatementWriter.ts index 9c0a5f4fa..e81236218 100644 --- a/src/cairoWriter/writers/emitStatementWriter.ts +++ b/src/cairoWriter/writers/emitStatementWriter.ts @@ -6,7 +6,7 @@ import { getDocumentation } from '../utils'; export class EmitStatementWriter extends CairoASTNodeWriter { writeInner(node: EmitStatement, writer: ASTWriter): SrcDesc { const eventDef = node.vEventCall.vReferencedDeclaration; - assert(eventDef instanceof EventDefinition, `Expected EventDefintion as referenced type`); + assert(eventDef instanceof EventDefinition, `Expected EventDefinition as referenced type`); const documentation = getDocumentation(node.documentation, writer); const args: string = node.vEventCall.vArguments.map((v) => writer.write(v)).join(', '); diff --git a/src/cairoWriter/writers/identifierWriter.ts b/src/cairoWriter/writers/identifierWriter.ts index b3b3fe707..e0464cdec 100644 --- a/src/cairoWriter/writers/identifierWriter.ts +++ b/src/cairoWriter/writers/identifierWriter.ts @@ -13,7 +13,7 @@ export class IdentifierWriter extends CairoASTNodeWriter { } if (isExternalMemoryDynArray(node, this.ast.inference)) { // Memory treated as calldata behaves similarly to calldata but it's - // element pointer and length variabes are not wrapped inside a struct. + // element pointer and length variables are not wrapped inside a struct. // When access to the dynamic array is needed, this two variables are used instead return [`${node.name}_len, ${node.name}`]; } diff --git a/src/cairoWriter/writers/sourceUnitWriter.ts b/src/cairoWriter/writers/sourceUnitWriter.ts index f936f9743..8b3df4282 100644 --- a/src/cairoWriter/writers/sourceUnitWriter.ts +++ b/src/cairoWriter/writers/sourceUnitWriter.ts @@ -37,7 +37,7 @@ export class SourceUnitWriter extends CairoASTNodeWriter { // Only constants generated by `newToDeploy` exist at this stage const constants = node.vVariables.flatMap((v) => { - assert(v.vValue !== undefined, 'Constants cannot be unanssigned'); + assert(v.vValue !== undefined, 'Constants cannot be unassigned'); return [`// ${v.documentation}`, `const ${v.name} = ${writer.write(v.vValue)};`].join('\n'); }); diff --git a/src/cli.ts b/src/cli.ts index c7dc3a3b2..9011b8093 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -79,7 +79,7 @@ program false, ) .option('--print-trees', 'Debug: Print all the intermediate ASTs') - .option('--no-stubs', 'Debug: Hide the stubs in the intermedidate ASTs when using --print-trees') + .option('--no-stubs', 'Debug: Hide the stubs in the intermediate ASTs when using --print-trees') .option('--no-strict', 'Debug: Allow silent failure of AST consistency checks') .option('--until ', 'Stops transpilation after the specified pass') .option('--no-warnings', 'Suppress warnings from the Solidity compiler') @@ -152,7 +152,7 @@ program .option('--order ', 'Use a custom set of transpilation passes') .option('-o, --output-dir ', 'Output directory for transformed Solidity files') .option('--print-trees', 'Debug: Print all the intermediate ASTs') - .option('--no-stubs', 'Debug: Hide the stubs in the intermedidate ASTs when using --print-trees') + .option('--no-stubs', 'Debug: Hide the stubs in the intermediate ASTs when using --print-trees') .option('--no-strict', 'Debug: Allow silent failure of AST consistency checks') .option('--until ', 'Stop processing at specified pass') .option('--no-warnings', 'Suppress printed warnings') @@ -235,7 +235,7 @@ export interface SolcInterfaceGenOptions { program .command('gen-interface ') .description( - 'Use native Cairo contracts in your Soldity by creating a Solidity interface and a Cairo translation contract for the target Cairo contract', + 'Use native Cairo contracts in your Solidity by creating a Solidity interface and a Cairo translation contract for the target Cairo contract', ) .option('--cairo-path ', 'Cairo libraries/modules import path') .option( @@ -275,7 +275,7 @@ program .option('-d, --debug_info', 'Compile include debug information', false) .option( '--inputs ', - 'Arguments to be passed to constructor of the program as a comma seperated list of strings, ints and lists', + 'Arguments to be passed to constructor of the program as a comma separated list of strings, ints and lists', undefined, ) .option('--use_cairo_abi', 'Use the cairo abi instead of solidity for the inputs', false) diff --git a/src/freeStructWritter.ts b/src/freeStructWritter.ts index 588bdcfcc..ce378090b 100644 --- a/src/freeStructWritter.ts +++ b/src/freeStructWritter.ts @@ -13,7 +13,7 @@ import { makeStructTree, reorderStructs } from './passes/orderNestedStructs'; i.e libraries can be seen as implicit base contracts of the contracts that use them The ReferencedLibraries pass converts external call to the library to internal call to it. - This pass is called before the ReferncedLibraries pass to inline free functions + This pass is called before the ReferencedLibraries pass to inline free functions into the contract if the free functions make library calls or if they call other free function which do that. */ diff --git a/src/icf/README.md b/src/icf/README.md index 7b47f5244..bc671664c 100644 --- a/src/icf/README.md +++ b/src/icf/README.md @@ -201,7 +201,7 @@ namespace Forwarder_a_warped_interface { } } -// Original soldity abi: ["constructor()","useAdd(uint256,uint256)","itr()"] +// Original solidity abi: ["constructor()","useAdd(uint256,uint256)","itr()"] ``` ### Step 5. diff --git a/src/icf/genCairo.ts b/src/icf/genCairo.ts index 325c33bf7..bad8656bb 100644 --- a/src/icf/genCairo.ts +++ b/src/icf/genCairo.ts @@ -4,7 +4,7 @@ import { castStatement, getStructDependencyGraph, reverseCastStatement, - stringfyStructs, + stringifyStructs, transformType, typeToStructMapping, uint256TransformStructs, @@ -18,7 +18,7 @@ export function genCairoContract( class_hash: string | undefined, ): string { const langDirective: string[] = getStarknetLangDirective(); - const structs: string[] = stringfyStructs(getStructDependencyGraph(abi)); + const structs: string[] = stringifyStructs(getStructDependencyGraph(abi)); const forwarderInterface: string[] = getForwarderInterface(abi); const [ interactiveFuncs, @@ -35,9 +35,9 @@ export function genCairoContract( '\n\n// existing structs\n' + structs.join('\n') + '\n\n// transformed structs \n' + - stringfyStructs(transformStructs).join('\n') + + stringifyStructs(transformStructs).join('\n') + '\n\n// tuple structs \n' + - stringfyStructs(tupleStructs).join('\n') + + stringifyStructs(tupleStructs).join('\n') + '\n\n// forwarder interface \n' + forwarderInterface.join('\n') + '\n\n//cast functions for structs \n' + diff --git a/src/icf/utils/util.ts b/src/icf/utils/util.ts index 06906c24e..b1a7e3b57 100644 --- a/src/icf/utils/util.ts +++ b/src/icf/utils/util.ts @@ -2,7 +2,7 @@ import { AbiItemType, StructAbiItemType } from '../abiTypes'; import keccak from 'keccak'; import { INDENT } from '../genCairo'; -export function stringfyStructs(structs: StructAbiItemType[]): string[] { +export function stringifyStructs(structs: StructAbiItemType[]): string[] { return structs .filter((item: AbiItemType) => item.name !== 'Uint256') .map((item: StructAbiItemType) => { diff --git a/src/passes/conditionalSplitter/conditionalSplitter.ts b/src/passes/conditionalSplitter/conditionalSplitter.ts index 392eeef47..e737c51f2 100644 --- a/src/passes/conditionalSplitter/conditionalSplitter.ts +++ b/src/passes/conditionalSplitter/conditionalSplitter.ts @@ -115,7 +115,7 @@ function* expressionGenerator(prefix: string): Generator (int a, int b) = (y,x); x = a; y = b; diff --git a/src/passes/conditionalSplitter/utils/conditionalFunctionaliser.ts b/src/passes/conditionalSplitter/utils/conditionalFunctionaliser.ts index 63269b1b7..e20a26b63 100644 --- a/src/passes/conditionalSplitter/utils/conditionalFunctionaliser.ts +++ b/src/passes/conditionalSplitter/utils/conditionalFunctionaliser.ts @@ -204,7 +204,7 @@ export function getNodeVariables(node: Conditional) { // - they are the expression of a return statement // - they are the expression of an expressionStatement // There might be nested conditionals as well, but the pass goes through -// the outtermost first and transform it, so it falls in the previous cases +// the outermost first and transform it, so it falls in the previous cases export function getStatementsForVoidConditionals( node: Conditional, variables: VariableDeclaration[], diff --git a/src/passes/deleteHandler.ts b/src/passes/deleteHandler.ts index d3e31a143..880700caf 100644 --- a/src/passes/deleteHandler.ts +++ b/src/passes/deleteHandler.ts @@ -32,7 +32,7 @@ export class DeleteHandler extends ASTMapper { } const nodeType = safeGetNodeType(node.vSubExpression, ast.inference); - // Deletetion from storage is handled in References + // Deletion from storage is handled in References if ( (nodeType instanceof PointerType && nodeType.location === DataLocation.Storage) || (node instanceof Identifier && diff --git a/src/passes/externalArgModifier/dynamicArrayModifier.ts b/src/passes/externalArgModifier/dynamicArrayModifier.ts index e83ae5903..79494b36f 100644 --- a/src/passes/externalArgModifier/dynamicArrayModifier.ts +++ b/src/passes/externalArgModifier/dynamicArrayModifier.ts @@ -21,7 +21,7 @@ export class DynArrayModifier extends ASTMapper { arrays into external functions. Externally passed dynArrays in Cairo are 2 arguments while in Solidity they are - 1. This means a work around is needed for handelling them. The dynArray is + 1. This means a work around is needed for handling them. The dynArray is converted into a struct that holds its two members (len and ptr). The Identifiers that reference the original dynArray are now replaced with ones that reference the struct. ie dArray[1] -> dArray_struct.ptr[1]. This struct has storageLocation @@ -30,17 +30,17 @@ export class DynArrayModifier extends ASTMapper { The above happens irrespective of whether the a dynArray is declared to be in Memory or CallData. If the original dynArray is in Memory an additional VariableDeclarationStatement is inserted at the beginning of the function body - with the VariableDeclaration dataLocation in memory and the intialValue being - an indentifer that references the dynArray_struct. This will trigger the write + with the VariableDeclaration dataLocation in memory and the initialValue being + an identifier that references the dynArray_struct. This will trigger the write in the dataAccessFunctionalizer and will use the appropriate functions to write the calldata struct containing the dynArray to Memory. Once again all the - Identifiers that refer to the orignal dynArray are replaced with the identifiers + Identifiers that refer to the original dynArray are replaced with the identifiers that reference the VariableDeclaration. - Notes on the CallData Struct Constuction: + Notes on the CallData Struct Construction: The dynArray is passed to a StructConstructor FunctionCall that has 1 argument. The FunctionDefinition it references is as Stub that takes 1 argument and is - never written. What is written is a StructDefintition with two members. + never written. What is written is a StructDefinition with two members. Only once the cairoWriter is reached is the single argument in the ParameterListWriter and FunctionCallWriter split into two. @@ -117,7 +117,7 @@ export class DynArrayModifier extends ASTMapper { ), ); } - // The orignal dynArray argument is changed to having it's DataLocation in CallData. + // The original dynArray argument is changed to having it's DataLocation in CallData. // Now both the dynArray and the struct representing it are in CallData. ast.setContextRecursive(node); varDecl.storageLocation = DataLocation.CallData; diff --git a/src/passes/externalArgModifier/memoryRefInputModifier.ts b/src/passes/externalArgModifier/memoryRefInputModifier.ts index 67e297945..f7378067a 100644 --- a/src/passes/externalArgModifier/memoryRefInputModifier.ts +++ b/src/passes/externalArgModifier/memoryRefInputModifier.ts @@ -10,17 +10,17 @@ import { isExternallyVisible } from '../../utils/utils'; export class RefTypeModifier extends ASTMapper { /* - This pass filters the inputParameters of FunctionDefintions for reference types sitting in + This pass filters the inputParameters of FunctionDefinitions for reference types sitting in memory that are not DynArrays. The original dataLocation of each of the filtered VariableDeclarations is then set to CallData. - A VariableDeclarationStatement is then inserted into the beginning of the fuction body with a + A VariableDeclarationStatement is then inserted into the beginning of the function body with a cloned VariableDeclaration with the DataLocation set to Memory and the initialValue being an Identifier referencing the original VariableDeclaration in the Parameter list, with the DataLocation as CallData. - This will trigger the dataAccessFunctionalizer to insert the necccessary write UtilGens from + This will trigger the dataAccessFunctionalizer to insert the necessary write UtilGens from CallDataToMemory. Before pass: @@ -38,7 +38,7 @@ export class RefTypeModifier extends ASTMapper { function testReturnMember(structDef calldata structA) external pure returns (uint8) { structDef memory __warp_usrid_2_structA_mem = structA; - return __warp_usirid1_structA.__warp_usrid_0_member1; + return __warp_usrid1_structA.__warp_usrid_0_member1; } */ diff --git a/src/passes/externalContractHandler/index.ts b/src/passes/externalContractHandler/index.ts index 1195d0a31..890ef69af 100644 --- a/src/passes/externalContractHandler/index.ts +++ b/src/passes/externalContractHandler/index.ts @@ -7,7 +7,7 @@ import { ExternalContractInterfaceInserter } from './externalContractInterfaceIn /* This is a compound pass which internally calls ExternalContractInterfaceInserter pass - to insert interfaces for the external contracts that has been refrenced into the AST + to insert interfaces for the external contracts that has been referenced into the AST for every SourceUnit. Simple importing contracts (namespaces in cairo) would not work because the constructors @@ -22,7 +22,7 @@ export class ExternalContractHandler extends ASTMapper { // Function to add passes that should have been run before this pass addInitialPassPrerequisites(): void { const passKeys: Set = new Set([ - 'Ii', // Inheritance Inline pass inherit all functions from the base contracts, so that external contracts refrerences in the base contracts are handled + 'Ii', // Inheritance Inline pass inherit all functions from the base contracts, so that external contracts references in the base contracts are handled 'Sa', // All contracts are changed to Cairo Contracts, and this passes uses the CairoContract class ]); passKeys.forEach((key) => this.addPassPrerequisite(key)); diff --git a/src/passes/freeFunctionInliner.ts b/src/passes/freeFunctionInliner.ts index e8c833360..2581d3efe 100644 --- a/src/passes/freeFunctionInliner.ts +++ b/src/passes/freeFunctionInliner.ts @@ -16,7 +16,7 @@ import { union } from '../utils/utils'; i.e libraries can be seen as implicit base contracts of the contracts that use them The ReferencedLibraries pass converts external call to the library to internal call to it. - This pass is called before the ReferncedLibraries pass to inline free functions + This pass is called before the ReferencedLibraries pass to inline free functions into the contract if the free functions make library calls or if they call other free function which do that. */ diff --git a/src/passes/functionModifierHandler/index.ts b/src/passes/functionModifierHandler/index.ts index a59b435c4..0b8fa802c 100644 --- a/src/passes/functionModifierHandler/index.ts +++ b/src/passes/functionModifierHandler/index.ts @@ -6,7 +6,7 @@ import { ModifierRemover } from './modifierRemover'; /* This pass takes all functions that are being modified and transform them into a sequence of functions, which are called in the same order the modifier invocations were declared. Each of these functions will - contain the code of the correponding modifier. + contain the code of the corresponding modifier. Once this is done, ModifierDefinition nodes are removed from the ast since they are no longer needed. diff --git a/src/passes/generateGetters/gettersGenerator.ts b/src/passes/generateGetters/gettersGenerator.ts index d806a814d..4b6b00e16 100644 --- a/src/passes/generateGetters/gettersGenerator.ts +++ b/src/passes/generateGetters/gettersGenerator.ts @@ -193,7 +193,7 @@ function genFunctionParams( ast: AST, ): VariableDeclaration[] { /* - This function will return the list of paramters + This function will return the list of parameters for a getter function of a public state var For e.g mapping(uint => mapping(address => uint256)) diff --git a/src/passes/implicitConversionToExplicit.ts b/src/passes/implicitConversionToExplicit.ts index 3ae32fa71..0b23ee3bc 100644 --- a/src/passes/implicitConversionToExplicit.ts +++ b/src/passes/implicitConversionToExplicit.ts @@ -153,7 +153,7 @@ export class ImplicitConversionToExplicit extends ASTMapper { assert( node.vInitialValue !== undefined, - `Implicit conversion to explicit expects variables to be initialised (did you run variable declaration initialiser?). Found at ${printNode( + `Implicit conversion to explicit expects variables to be initialized (did you run variable declaration initializer?). Found at ${printNode( node, )}`, ); @@ -211,7 +211,7 @@ export class ImplicitConversionToExplicit extends ASTMapper { } if (node.vFunctionName === 'decode') { - assert(node.vArguments.length === 2, 'decode recieves two arguments'); + assert(node.vArguments.length === 2, 'decode receives two arguments'); insertConversionIfNecessary(node.vArguments[0], new BytesType(), node, ast); return; } @@ -318,7 +318,7 @@ export function insertConversionIfNecessary( const parent = expression.parent; const [replacement, shouldReplace] = ast .getUtilFuncGen(expression) - .memory.convert.genIfNecesary(expression, targetType); + .memory.convert.genIfNecessary(expression, targetType); if (shouldReplace) { ast.replaceNode(expression, replacement, parent); } diff --git a/src/passes/inheritanceInliner/constructorInheritance.ts b/src/passes/inheritanceInliner/constructorInheritance.ts index f111ddde5..1085ae9d0 100644 --- a/src/passes/inheritanceInliner/constructorInheritance.ts +++ b/src/passes/inheritanceInliner/constructorInheritance.ts @@ -48,7 +48,7 @@ import { updateReferencedDeclarations } from './utils'; When collecting the arguments, it's important to notice that expressions should be evaluated in the reverse order the constructors are executed. To do so, each time a - contract is entered, the previous constracts in the order of linearization are checked + contract is entered, the previous contract in the order of linearization are checked looking for the call to this contract's constructor; and argument references are updated In the following example: diff --git a/src/passes/inheritanceInliner/eventInheritance.ts b/src/passes/inheritanceInliner/eventInheritance.ts index acf94c504..73811795f 100644 --- a/src/passes/inheritanceInliner/eventInheritance.ts +++ b/src/passes/inheritanceInliner/eventInheritance.ts @@ -4,7 +4,7 @@ import { CairoContract } from '../../ast/cairoNodes'; import { cloneASTNode } from '../../utils/cloning'; import { getBaseContracts } from './utils'; -export function addEventDefintion( +export function addEventDefinition( node: CairoContract, idRemapping: Map, ast: AST, diff --git a/src/passes/inheritanceInliner/functionInheritance.ts b/src/passes/inheritanceInliner/functionInheritance.ts index afcc081a2..29526a425 100644 --- a/src/passes/inheritanceInliner/functionInheritance.ts +++ b/src/passes/inheritanceInliner/functionInheritance.ts @@ -46,7 +46,7 @@ export function addPrivateSuperFunctions( } return clonedFunction; }) - // filter the nulls returned when trying to inheritr overriden fallback functions + // filter the nulls returned when trying to inherit overridden fallback functions .filter((f): f is FunctionDefinition => f !== null) .forEach((func) => { node.appendChild(func); diff --git a/src/passes/inheritanceInliner/inheritanceInliner.ts b/src/passes/inheritanceInliner/inheritanceInliner.ts index ce862b6d9..5bdfa285c 100644 --- a/src/passes/inheritanceInliner/inheritanceInliner.ts +++ b/src/passes/inheritanceInliner/inheritanceInliner.ts @@ -9,16 +9,16 @@ import { CairoContract } from '../../ast/cairoNodes'; import { ASTMapper } from '../../ast/mapper'; import { TranspileFailedError } from '../../utils/errors'; import { solveConstructors } from './constructorInheritance'; -import { addEventDefintion } from './eventInheritance'; +import { addEventDefinition } from './eventInheritance'; import { addPrivateSuperFunctions } from './functionInheritance'; import { solveLibraryInheritance } from './libraryInheritance'; -import { addNonOverridenModifiers } from './modifiersInheritance'; +import { addNonOverriddenModifiers as addNonOverriddenModifiers } from './modifiersInheritance'; import { addStorageVariables } from './storageVariablesInheritance'; import { getBaseContracts, removeBaseContractDependence, updateReferencedDeclarations, - updateReferenceEmitStatemets, + updateReferenceEmitStatements, } from './utils'; export class InheritanceInliner extends ASTMapper { @@ -61,11 +61,11 @@ export class InheritanceInliner extends ASTMapper { // (, ) is stored in the map for each one of them. // // When there is an overriding function (or modifier) all references to the function - // should point to this particular function and not the overriden implementation of it. + // should point to this particular function and not the overridden implementation of it. // That is what the overriders maps are used for, they keep the reference to the // overriding member. // Nevertheless, the references to all the cloned members must also be kept, since they - // can be called specifying the contract, even if they are being overriden somewhere + // can be called specifying the contract, even if they are being overridden somewhere // else down the line of inheritance. // // Example: @@ -103,13 +103,13 @@ export class InheritanceInliner extends ASTMapper { addPrivateSuperFunctions(node, functionRemapping, functionRemappingOverriders, ast); addStorageVariables(node, variableRemapping, ast); - addNonOverridenModifiers(node, modifierRemapping, modifierRemappingOverriders, ast); - addEventDefintion(node, eventRemapping, ast); + addNonOverriddenModifiers(node, modifierRemapping, modifierRemappingOverriders, ast); + addEventDefinition(node, eventRemapping, ast); updateReferencedDeclarations(node, functionRemapping, functionRemappingOverriders, ast); updateReferencedDeclarations(node, variableRemapping, variableRemapping, ast); updateReferencedDeclarations(node, modifierRemapping, modifierRemappingOverriders, ast); - updateReferenceEmitStatemets(node, eventRemapping, ast); + updateReferenceEmitStatements(node, eventRemapping, ast); removeBaseContractDependence(node); diff --git a/src/passes/inheritanceInliner/modifiersInheritance.ts b/src/passes/inheritanceInliner/modifiersInheritance.ts index 71ae1abaf..2c4b43aca 100644 --- a/src/passes/inheritanceInliner/modifiersInheritance.ts +++ b/src/passes/inheritanceInliner/modifiersInheritance.ts @@ -4,7 +4,7 @@ import { CairoContract } from '../../ast/cairoNodes'; import { cloneASTNode } from '../../utils/cloning'; import { fixSuperReference, getBaseContracts } from './utils'; -export function addNonOverridenModifiers( +export function addNonOverriddenModifiers( node: CairoContract, idRemapping: Map, idRemappingOverriders: Map, @@ -18,15 +18,15 @@ export function addNonOverridenModifiers( .filter((node) => node.kind !== ContractKind.Library) .forEach((contract) => { contract.vModifiers.forEach((modifier, depth) => { - const exisitingModifier = currentModifiers.get(modifier.name); + const existingModifier = currentModifiers.get(modifier.name); const clonedModifier = cloneASTNode(modifier, ast); idRemapping.set(modifier.id, clonedModifier); - if (exisitingModifier === undefined) { + if (existingModifier === undefined) { currentModifiers.set(modifier.name, clonedModifier); idRemappingOverriders.set(modifier.id, clonedModifier); } else { clonedModifier.name = `m${depth + 1}_${clonedModifier.name}`; - idRemappingOverriders.set(modifier.id, exisitingModifier); + idRemappingOverriders.set(modifier.id, existingModifier); } node.appendChild(clonedModifier); fixSuperReference(clonedModifier, contract, node); diff --git a/src/passes/inheritanceInliner/utils.ts b/src/passes/inheritanceInliner/utils.ts index 0bf17c8d2..6363f9a63 100644 --- a/src/passes/inheritanceInliner/utils.ts +++ b/src/passes/inheritanceInliner/utils.ts @@ -71,7 +71,7 @@ export function updateReferencedDeclarations( }); } -export function updateReferenceEmitStatemets( +export function updateReferenceEmitStatements( node: ASTNode, idRemapping: Map, ast: AST, diff --git a/src/passes/inlineAssemblyTransformer.ts b/src/passes/inlineAssemblyTransformer.ts index 6b548b05e..55b287d5f 100644 --- a/src/passes/inlineAssemblyTransformer.ts +++ b/src/passes/inlineAssemblyTransformer.ts @@ -50,7 +50,7 @@ const binaryOps: { [name: string]: string } = { mod: '%', exp: '**', }; -// Consider grouping functions by number of arguments. They probbably all use uint256 with the only difference being number of args. +// Consider grouping functions by number of arguments. They probably all use uint256 with the only difference being number of args. const solidityEquivalents: { [name: string]: string } = { addmod: 'function (uint256,uint256,uint256) pure returns (uint256)', mulmod: 'function (uint256,uint256,uint256) pure returns (uint256)', diff --git a/src/passes/namedArgsRemover.ts b/src/passes/namedArgsRemover.ts index f8ca7faf8..3217396ae 100644 --- a/src/passes/namedArgsRemover.ts +++ b/src/passes/namedArgsRemover.ts @@ -69,7 +69,7 @@ export class NamedArgsRemover extends ASTMapper { fieldNames.length !== orderedFieldNames.length ) { throw new TranspileFailedError( - 'Number of arguments must less or euqal to number of function field names', + 'Number of arguments must less or equal to number of function field names', ); } diff --git a/src/passes/newToDeploy.ts b/src/passes/newToDeploy.ts index b9ca009aa..54885ce96 100644 --- a/src/passes/newToDeploy.ts +++ b/src/passes/newToDeploy.ts @@ -67,7 +67,7 @@ import { getContainingSourceUnit } from '../utils/utils'; export class NewToDeploy extends ASTMapper { addInitialPassPrerequisites(): void { const passKeys: Set = new Set([ - 'Ffi', // Define the `encoder` util function after the free funtion has been moved + 'Ffi', // Define the `encoder` util function after the free function has been moved ]); passKeys.forEach((key) => this.addPassPrerequisite(key)); } diff --git a/src/passes/orderNestedStructs.ts b/src/passes/orderNestedStructs.ts index 0f94f5b44..279fc6fbd 100644 --- a/src/passes/orderNestedStructs.ts +++ b/src/passes/orderNestedStructs.ts @@ -50,7 +50,7 @@ export class OrderNestedStructs extends ASTMapper { const newStructOrder = reorderStructs(roots, tree); - // remove old struct definiton + // remove old struct definition structs.forEach((child) => { if (child instanceof StructDefinition) { node.removeChild(child); @@ -75,7 +75,7 @@ export function reorderStructs( } // dfs through the tree -// root is alawys added to orderedStructs after all it's children +// root is always added to orderedStructs after all it's children function visitTree( root: StructDefinition, tree: Map, @@ -102,7 +102,7 @@ export function makeStructTree( structs.forEach((struct) => { struct.vMembers.forEach((varDecl) => { const nestedStruct = findStruct(safeGetNodeType(varDecl, ast.inference)); - // second check to avoid adding imported structs to contract defintion + // second check to avoid adding imported structs to contract definition if (nestedStruct !== null && structs.has(nestedStruct)) { roots.delete(nestedStruct); tree.has(struct) ? tree.get(struct)?.push(nestedStruct) : tree.set(struct, [nestedStruct]); @@ -110,7 +110,7 @@ export function makeStructTree( }); }); - // roots are struct definition from which none other struct defintion + // roots are struct definition from which none other struct definition // depends on return [roots, tree]; } diff --git a/src/passes/publicFunctionSplitter/externalFunctionCreator.ts b/src/passes/publicFunctionSplitter/externalFunctionCreator.ts index ee6a673e3..6bed46598 100644 --- a/src/passes/publicFunctionSplitter/externalFunctionCreator.ts +++ b/src/passes/publicFunctionSplitter/externalFunctionCreator.ts @@ -47,7 +47,7 @@ export class ExternalFunctionCreator extends ASTMapper { if (FunctionVisibility.Public === node.visibility && node.kind !== FunctionKind.Constructor) { if (this.internalFunctionCallSet.has(node)) { - const newExternalFunction = this.createExternalFunctionDefintion(node, ast); + const newExternalFunction = this.createExternalFunctionDefinition(node, ast); this.insertReturnStatement(node, newExternalFunction, ast); this.modifyPublicFunction(node); this.internalToExternalFunctionMap.set(node, newExternalFunction); @@ -63,7 +63,7 @@ export class ExternalFunctionCreator extends ASTMapper { node.name = `${node.name}${INTERNAL_FUNCTION_SUFFIX}`; } - private createExternalFunctionDefintion(node: FunctionDefinition, ast: AST): FunctionDefinition { + private createExternalFunctionDefinition(node: FunctionDefinition, ast: AST): FunctionDefinition { const newBlock = createBlock([], ast); const internalFunctionBody = node.vBody; node.vBody = undefined; diff --git a/src/passes/references/dataAccessFunctionaliser.ts b/src/passes/references/dataAccessFunctionaliser.ts index d83a8d4d8..9c564fc11 100644 --- a/src/passes/references/dataAccessFunctionaliser.ts +++ b/src/passes/references/dataAccessFunctionaliser.ts @@ -123,7 +123,7 @@ export class DataAccessFunctionaliser extends ReferenceSubPass { } // Update the expected location of the node to be equal to its - // actual location, now that any discrepency has been handled + // actual location, now that any discrepancy has been handled if (copyFunc) { this.replace(node, copyFunc, parent, expectedLoc, expectedLoc, ast); @@ -162,7 +162,7 @@ export class DataAccessFunctionaliser extends ReferenceSubPass { } else if (fromLoc === DataLocation.Memory) { const [convert, result] = ast .getUtilFuncGen(node) - .memory.convert.genIfNecesary( + .memory.convert.genIfNecessary( node.vLeftHandSide, safeGetNodeType(node.vRightHandSide, ast.inference), ); diff --git a/src/passes/references/expectedLocationAnalyser.ts b/src/passes/references/expectedLocationAnalyser.ts index a766b79f9..bd068eb6d 100644 --- a/src/passes/references/expectedLocationAnalyser.ts +++ b/src/passes/references/expectedLocationAnalyser.ts @@ -138,7 +138,7 @@ export class ExpectedLocationAnalyser extends ASTMapper { } const parameterTypes = getParameterTypes(node, ast); - // When calling `push`, the function recieves two paramaters nonetheless the argument is just one + // When calling `push`, the function receives two parameters nonetheless the argument is just one // This does not explode because javascript does not gives an index out of range exception node.vArguments.forEach((arg, index) => { // Solc 0.7.0 types push and pop as you would expect, 0.8.0 adds an extra initial argument diff --git a/src/passes/references/externalReturnReceiver.ts b/src/passes/references/externalReturnReceiver.ts index 5d9e562a6..a313466d1 100644 --- a/src/passes/references/externalReturnReceiver.ts +++ b/src/passes/references/externalReturnReceiver.ts @@ -25,8 +25,8 @@ export class ExternalReturnReceiver extends ASTMapper { return this.commonVisit(node, ast); } - // For each variable that recieves an external call and is neither a value type nor a - // reference type with calldata location, create a temporal variable which recieves the + // For each variable that receives an external call and is neither a value type nor a + // reference type with calldata location, create a temporal variable which receives the // calldata output and then copy it to the current node expected location node.vDeclarations .filter( diff --git a/src/passes/replaceIdentifierContractMemberAccess.ts b/src/passes/replaceIdentifierContractMemberAccess.ts index 179451764..f157330f4 100644 --- a/src/passes/replaceIdentifierContractMemberAccess.ts +++ b/src/passes/replaceIdentifierContractMemberAccess.ts @@ -7,8 +7,8 @@ import { isExternallyVisible } from '../utils/utils'; import { getContractTypeString } from '../utils/getTypeString'; /** - * This pass replaces all identifier whose refrenced declaration defined outside of the function body, - * by a member access with the expression as an identifier refrenced to it's parent contract. + * This pass replaces all identifier whose referenced declaration defined outside of the function body, + * by a member access with the expression as an identifier referenced to it's parent contract. * For e.g. * contract A { * uint public a; @@ -18,7 +18,7 @@ import { getContractTypeString } from '../utils/getTypeString'; * } * } * -- function f to be written outside of namespace A (see `cairoWriter.ts: 519`) -- - * This is done to separate the external functions outside of the namspace + * This is done to separate the external functions outside of the namespace * so that there would be abi's generated for them. see `cairoWriter.ts: 519`. * from cairo v0.10.0, for the functions lying inside the cairo namespace , there would be * no abi generated for them. @@ -28,7 +28,7 @@ export class ReplaceIdentifierContractMemberAccess extends ASTMapper { // Function to add passes that should have been run before this pass addInitialPassPrerequisites(): void { const passKeys: Set = new Set([ - 'Sa', // Pass uses CairoFunctionDefintion and CairoContract + 'Sa', // Pass uses CairoFunctionDefinition and CairoContract ]); passKeys.forEach((key) => this.addPassPrerequisite(key)); } diff --git a/src/passes/staticArrayIndexer.ts b/src/passes/staticArrayIndexer.ts index 0c697b0aa..061bc6869 100644 --- a/src/passes/staticArrayIndexer.ts +++ b/src/passes/staticArrayIndexer.ts @@ -44,8 +44,8 @@ export class StaticArrayIndexer extends ASTMapper { inside another structure, then the whole structure is copied to memory */ - // Tracks calldata structures which already have a memory counterpart initalized - private staticArrayAccesed = new Map(); + // Tracks calldata structures which already have a memory counterpart initialized + private staticArrayAccessed = new Map(); // Function to add passes that should have been run before this pass addInitialPassPrerequisites(): void { @@ -73,10 +73,10 @@ export class StaticArrayIndexer extends ASTMapper { const refId = identifier.referencedDeclaration; - let refVarDecl = this.staticArrayAccesed.get(refId); + let refVarDecl = this.staticArrayAccessed.get(refId); if (refVarDecl === undefined) { refVarDecl = this.initMemoryArray(identifier, parentFunction, ast); - this.staticArrayAccesed.set(refId, refVarDecl); + this.staticArrayAccessed.set(refId, refVarDecl); } const indexReplacement = this.setExpressionToMemory(node, refVarDecl, ast); @@ -153,20 +153,20 @@ export class StaticArrayIndexer extends ASTMapper { DataLocation.CallData, ); - const varDeclStmnt = new VariableDeclarationStatement( + const varDeclStatement = new VariableDeclarationStatement( ast.reserveId(), '', [varDecl.id], [varDecl], assignation, ); - ast.setContextRecursive(varDeclStmnt); + ast.setContextRecursive(varDeclStatement); ast.setContextRecursive(varDecl); if (parentFunction.vParameters.vParameters.some((vd) => vd.id === refId)) { - parentFunction.vBody?.insertAtBeginning(varDeclStmnt); + parentFunction.vBody?.insertAtBeginning(varDeclStatement); } else { - ast.insertStatementAfter(identifier.vReferencedDeclaration, varDeclStmnt); + ast.insertStatementAfter(identifier.vReferencedDeclaration, varDeclStatement); } return varDecl; } diff --git a/src/passes/storageAllocator.ts b/src/passes/storageAllocator.ts index 75e7e4069..cd1475835 100644 --- a/src/passes/storageAllocator.ts +++ b/src/passes/storageAllocator.ts @@ -94,7 +94,7 @@ export class StorageAllocator extends ASTMapper { ast.replaceNode(node, cairoNode); - // This next code line is a hotfix when there is struct inheritance and the base contract's definiton + // This next code line is a hotfix when there is struct inheritance and the base contract's definition // gets replaced by its cairo counter part. From now on using `getNodeType` on an expression with a // an inherited struct type will crash unexpectedly. // The issue is caused because the property `vLinearizedBaseContracts` that is accessed through `getNodeType` diff --git a/src/semanticTestRunner.ts b/src/semanticTestRunner.ts index cbfd46e38..53367b320 100644 --- a/src/semanticTestRunner.ts +++ b/src/semanticTestRunner.ts @@ -10,7 +10,7 @@ To execute this script, run: - compare flag will tell the differences between tests list present in semanticWhitelist.ts and tests written in specified version of solc -- filter can be specified to run a specfic group of tests or an individual +- filter can be specified to run a specific group of tests or an individual test It generates a file `tests/behaviour/expectations/semanticTestsGenerated.ts` @@ -122,7 +122,7 @@ const testDirs = execSync( const filterDirs: string[] = [ ...testDirs, - 'tests/behaviour/solidity/test/libsolidity/semanticTests', // An extra entry for miscllaneous tests + 'tests/behaviour/solidity/test/libsolidity/semanticTests', // An extra entry for miscellaneous tests ]; const currentTestsFileBody = readFileSync( diff --git a/src/utils/astChecking.ts b/src/utils/astChecking.ts index 66c1319db..d0a8cdbad 100644 --- a/src/utils/astChecking.ts +++ b/src/utils/astChecking.ts @@ -143,7 +143,7 @@ function checkVFieldCtx( * 3) if field is a number then `vField` is an `ASTNode` and `field == vField.id` * 4) if field is an array of numbers then `vField` is an `ASTNode[]` and * `node.field.length === node.vField.length` and `node.field[i] === - * node.vField[i].id` forall i in `[0, ... node.field.lenth)` + * node.vField[i].id` forall i in `[0, ... node.field.length)` * */ function checkFieldAndVFieldMatch( @@ -421,9 +421,9 @@ export function checkSane(unit: SourceUnit, ctx: ASTContext): void { node.vSymbolAliases.length !== node.symbolAliases.length ) { throw new InsaneASTError( - `symbolAliases.length (${node.symbolAliases.length}) and vSymboliAliases.length ${ + `symbolAliases.length (${node.symbolAliases.length}) and vSymbolAliases.length ${ node.vSymbolAliases.length - } misamtch for import ${pp(node)}`, + } mismatch for import ${pp(node)}`, ); } @@ -725,7 +725,7 @@ function checkEmptyNamesForNamelessFunctions(nodes: FunctionDefinition[]) { * - All reachable nodes belong to the same context, have their parent/sibling set correctly. * - All number id properties of nodes point to a node in the same context. * - When a number property (e.g. `scope`) has a corresponding `v` prefixed property (e.g. `vScope`) - * check that the number proerty corresponds to the id of the `v` prefixed property. + * check that the number property corresponds to the id of the `v` prefixed property. * - Most 'v' properties point to direct children of a node. * * NOTE: While this code can be slightly slow, its meant to be used mostly in testing so its diff --git a/src/utils/errors.ts b/src/utils/errors.ts index 5a834bb6a..aabb89998 100644 --- a/src/utils/errors.ts +++ b/src/utils/errors.ts @@ -52,9 +52,9 @@ export function getErrorMessage( ): string { let errorNum = 0; const errorMsg = [...unsupportedPerSource.entries()].reduce( - (fullMsg, [filePath, unsopported]) => { + (fullMsg, [filePath, unsupported]) => { const content = fs.readFileSync(filePath, { encoding: 'utf8' }); - const newMessage = unsopported.reduce((newMessage, [errorMsg, node]) => { + const newMessage = unsupported.reduce((newMessage, [errorMsg, node]) => { const errorCode = getSourceFromLocations( content, [parseSourceLocation(node.src)], diff --git a/src/utils/functionGeneration.ts b/src/utils/functionGeneration.ts index 3d4dba4eb..1320984fe 100644 --- a/src/utils/functionGeneration.ts +++ b/src/utils/functionGeneration.ts @@ -113,7 +113,7 @@ export function createCairoGeneratedFunction( return funcDef; } -export function createCairoImportFunctionDefintion( +export function createCairoImportFunctionDefinition( funcName: string, path: string, implicits: Set, diff --git a/src/utils/importFuncGenerator.ts b/src/utils/importFuncGenerator.ts index 93f6530e8..5326ce1fc 100644 --- a/src/utils/importFuncGenerator.ts +++ b/src/utils/importFuncGenerator.ts @@ -5,7 +5,7 @@ import { TranspileFailedError } from '../utils/errors'; import { warplibImportInfo } from '../warplib/gatherWarplibImports'; import { Implicits } from './implicits'; import { - createCairoImportFunctionDefintion, + createCairoImportFunctionDefinition, createCairoImportStructDefinition, ParameterInfo, } from './functionGeneration'; @@ -39,7 +39,7 @@ export function createImport( const hasInputs = inputs !== undefined && inputs.length > 0; const hasOutputs = outputs !== undefined && outputs.length > 0; if (!hasInputs || !hasOutputs) return existingImport; - return createCairoImportFunctionDefintion( + return createCairoImportFunctionDefinition( name, path, existingImport.implicits, @@ -52,7 +52,7 @@ export function createImport( } const createFuncImport = (...implicits: Implicits[]) => - createCairoImportFunctionDefintion( + createCairoImportFunctionDefinition( name, path, new Set(implicits), diff --git a/src/utils/nodeTemplates.ts b/src/utils/nodeTemplates.ts index 9b4e99785..2639996a4 100644 --- a/src/utils/nodeTemplates.ts +++ b/src/utils/nodeTemplates.ts @@ -291,7 +291,7 @@ export function createDefaultConstructor(node: ContractDefinition, ast: AST): Fu export function createVariableDeclarationStatement( varDecls: (VariableDeclaration | null)[], - intitalValue: Expression | undefined, + initialValue: Expression | undefined, ast: AST, ): VariableDeclarationStatement { assert( @@ -303,7 +303,7 @@ export function createVariableDeclarationStatement( '', varDecls.map((v) => (v === null ? null : v.id)), varDecls.filter(notNull), - intitalValue, + initialValue, ); ast.setContextRecursive(node); return node; diff --git a/src/utils/postCairoWrite.ts b/src/utils/postCairoWrite.ts index 2289249d2..3425fa79f 100644 --- a/src/utils/postCairoWrite.ts +++ b/src/utils/postCairoWrite.ts @@ -11,7 +11,7 @@ export const HASH_OPTION = 'sha256'; /** Is used post transpilation to insert the class hash for any contract that can deploy another. - During transpilation 0 is placed where the class hash would be because cotracts to declare + During transpilation 0 is placed where the class hash would be because contracts to declare have not yet been fully transpiled. At this stage all contracts have been transpiled, so they can be compiled and their class hash computed. Each class hash needed is written into the cairo contract @@ -40,13 +40,13 @@ export function postProcessCairoFile( // If the file does have dependencies then we need to make sure that the dependencies of // those files have been calculated and inserted. filesToHash.forEach((file) => { - hashDependacies(file, outputDir, debugInfo, dependencyGraph, contractHashToClassHash); + hashDependencies(file, outputDir, debugInfo, dependencyGraph, contractHashToClassHash); }); setDeclaredAddresses(path.join(outputDir, contractPath), contractHashToClassHash); return contractPath; } -function hashDependacies( +function hashDependencies( contractPath: string, outputDir: string, debugInfo: boolean, @@ -63,7 +63,7 @@ function hashDependacies( filesToHash .map((file) => { - hashDependacies(file, outputDir, debugInfo, dependencyGraph, contractHashToClassHash); + hashDependencies(file, outputDir, debugInfo, dependencyGraph, contractHashToClassHash); return file; }) .forEach((file) => { @@ -184,7 +184,7 @@ export function getDependencyGraph(root: string, outputDir: string): Map([ + const visibilities = new Set([ FunctionVisibility.Internal, FunctionVisibility.External, FunctionVisibility.Public, @@ -62,14 +62,14 @@ function getFunctionAttributes( ]); for (const decorator of decorators) { - if (visiblities.has(decorator)) { - if (visiblity !== undefined) { + if (visibilities.has(decorator)) { + if (visibility !== undefined) { throw new Error( - `Multiple visiblity decorators specified: ${decorator} conflicts with ${visiblity}`, + `Multiple visibility decorators specified: ${decorator} conflicts with ${visibility}`, ); } - visiblity = decorator as FunctionVisibility; + visibility = decorator as FunctionVisibility; } else if (mutabilities.has(decorator)) { if (mutability !== undefined) { throw new Error( @@ -81,9 +81,9 @@ function getFunctionAttributes( } } - // Assume default visiblity is internal - if (visiblity === undefined) { - visiblity = FunctionVisibility.Internal; + // Assume default visibility is internal + if (visibility === undefined) { + visibility = FunctionVisibility.Internal; } // Assume default mutability is non-payable @@ -91,7 +91,7 @@ function getFunctionAttributes( mutability = FunctionStateMutability.NonPayable; } - return [visiblity, mutability]; + return [visibility, mutability]; } /** @@ -709,7 +709,7 @@ function peg$parse(input: string, options?: IParseOptions) { const peg$c206 = '=>'; const peg$c207 = peg$literalExpectation('=>', false); const peg$c208 = function (keyType: any, valueType: any): any { - // Identifiers refering directly to state variable maps + // Identifiers referring directly to state variable maps // don't have a pointer suffix. // So we wrap them in a PointerType here. // This means we explicitly disagree with the exact typeString. diff --git a/src/utils/typeStrings/typeStringParserHeader.ts b/src/utils/typeStrings/typeStringParserHeader.ts index 12cfcee55..92193191a 100644 --- a/src/utils/typeStrings/typeStringParserHeader.ts +++ b/src/utils/typeStrings/typeStringParserHeader.ts @@ -44,10 +44,10 @@ import { ModuleType } from './ast/moduleType'; function getFunctionAttributes( decorators: string[], ): [FunctionVisibility, FunctionStateMutability] { - let visiblity: FunctionVisibility | undefined; + let visibility: FunctionVisibility | undefined; let mutability: FunctionStateMutability | undefined; - const visiblities = new Set([ + const visibilities = new Set([ FunctionVisibility.Internal, FunctionVisibility.External, FunctionVisibility.Public, @@ -62,14 +62,14 @@ function getFunctionAttributes( ]); for (const decorator of decorators) { - if (visiblities.has(decorator)) { - if (visiblity !== undefined) { + if (visibilities.has(decorator)) { + if (visibility !== undefined) { throw new Error( - `Multiple visiblity decorators specified: ${decorator} conflicts with ${visiblity}`, + `Multiple visibility decorators specified: ${decorator} conflicts with ${visibility}`, ); } - visiblity = decorator as FunctionVisibility; + visibility = decorator as FunctionVisibility; } else if (mutabilities.has(decorator)) { if (mutability !== undefined) { throw new Error( @@ -81,9 +81,9 @@ function getFunctionAttributes( } } - // Assume default visiblity is internal - if (visiblity === undefined) { - visiblity = FunctionVisibility.Internal; + // Assume default visibility is internal + if (visibility === undefined) { + visibility = FunctionVisibility.Internal; } // Assume default mutability is non-payable @@ -91,7 +91,7 @@ function getFunctionAttributes( mutability = FunctionStateMutability.NonPayable; } - return [visiblity, mutability]; + return [visibility, mutability]; } /** diff --git a/src/utils/typeStrings/typeString_grammar.pegjs b/src/utils/typeStrings/typeString_grammar.pegjs index 7dd87df42..7ba1da0bd 100644 --- a/src/utils/typeStrings/typeString_grammar.pegjs +++ b/src/utils/typeStrings/typeString_grammar.pegjs @@ -328,7 +328,7 @@ UserDefinedType = MappingType = MAPPING __ "(" __ keyType: ArrayPtrType __ "=>" __ valueType: Type __ ")" { - // Identifiers refering directly to state variable maps + // Identifiers referring directly to state variable maps // don't have a pointer suffix. // So we wrap them in a PointerType here. // This means we explicitly disagree with the exact typeString. diff --git a/src/utils/utils.ts b/src/utils/utils.ts index 92464e314..752aff6d9 100644 --- a/src/utils/utils.ts +++ b/src/utils/utils.ts @@ -479,11 +479,11 @@ export function getSourceFromLocations( let marked = false; let newLine = `${lineNum}\t`; while (locIndex < locations.length && maxWalk >= locations[locIndex].offset) { - // Mark the line as a highlited line + // Mark the line as a highlighted line marked = true; const currentLocation = locations[locIndex]; if (currentLocation.offset + currentLocation.length > maxWalk) { - // Case when node source spans accross multiple lines + // Case when node source spans across multiple lines newLine = newLine + source.substring(textWalked, currentLocation.offset) + diff --git a/src/warplib/generateWarplib.ts b/src/warplib/generateWarplib.ts index 50e98d118..89aeb39a8 100644 --- a/src/warplib/generateWarplib.ts +++ b/src/warplib/generateWarplib.ts @@ -60,7 +60,7 @@ export const warplibFunctions: WarplibFunctionInfo[] = [ int_conversions(), // ---external_input_checks--- external_input_check_ints(), - // external_inputt_check_address - handwritten + // external_input_check_address - handwritten ]; warplibFunctions.forEach((warpFunc: WarplibFunctionInfo) => generateFile(warpFunc)); diff --git a/tests/behaviour/errors.ts b/tests/behaviour/errors.ts index 495d3d21e..95fcb0c3d 100644 --- a/tests/behaviour/errors.ts +++ b/tests/behaviour/errors.ts @@ -1,2 +1,2 @@ export class InvalidTestError extends Error {} -export class NotYetSuportedTestCaseError extends Error {} +export class NotYetSupportedTestCaseError extends Error {} diff --git a/tests/behaviour/expectations/behaviour.ts b/tests/behaviour/expectations/behaviour.ts index 2031fb226..814d6cdc0 100644 --- a/tests/behaviour/expectations/behaviour.ts +++ b/tests/behaviour/expectations/behaviour.ts @@ -1364,7 +1364,7 @@ export const expectations = flatten( 'getD', [], ['1', '0', '1', '0', '2', '1', '2', '0'], - 'struct of structs is copyed form calldata to storage', + 'struct of structs is copied form calldata to storage', ), new Expect('dynamic array of structs of structs is copied from calldata to storage', [ ['setE', [], [], '0'], @@ -2849,7 +2849,7 @@ export const expectations = flatten( new Dir('externalFunctionInputs', [ File.Simple('dynamicArrayReturnIndex', [ new Expect( - 'testing that dynamic memory array as calldata are tranformed and returned correctly', + 'testing that dynamic memory array as calldata are transformed and returned correctly', [ [ 'dArrayCallDataExternal', @@ -2892,7 +2892,7 @@ export const expectations = flatten( [['dArrayPublic', ['4', '1', '2', '3', '4'], ['1'], '0']], ), new Expect( - 'testing that multiple inputs containing dynamic arrays that are handeled correctly to external functions', + 'testing that multiple inputs containing dynamic arrays that are handled correctly to external functions', [ [ 'dArrayMultipleInputsExternal', @@ -2903,7 +2903,7 @@ export const expectations = flatten( ], ), new Expect( - 'testing that multipe inputs containing dynamic arrays that are handeled correctly when passed to public functions', + 'testing that multiple inputs containing dynamic arrays that are handled correctly when passed to public functions', [ [ 'dArrayMultipleInputsPublic', @@ -3117,7 +3117,7 @@ export const expectations = flatten( 'Error: value out-of-bounds. Value must be less than 2**8', ], ]), - new Expect('testing solidity pure exernal unsigned int32 overflow', [ + new Expect('testing solidity pure external unsigned int32 overflow', [ [ 'testUint32', ['4294967296'], @@ -3137,7 +3137,7 @@ export const expectations = flatten( '0', ], ]), - new Expect('testing soldity unsigned int248 overflow', [ + new Expect('testing solidity unsigned int248 overflow', [ [ 'testInt248', ['452312848583266388373324160190187140051835877600158453279131187530910662656'], @@ -3153,7 +3153,7 @@ export const expectations = flatten( '0', ], ]), - new Expect('testing soldity unsigned int256 in bounds', [ + new Expect('testing solidity unsigned int256 in bounds', [ [ 'testInt256', ['340282366920938463463374607431768211455', '0'], @@ -4062,7 +4062,7 @@ export const expectations = flatten( 'Delete dynamic array but keep a reference copy', ), // Blocked by returning a struct containing a dynamic array - // Expect.Simple('deleteC', [], ['0'], 'Delete struct with a dyanmic array as a member'), + // Expect.Simple('deleteC', [], ['0'], 'Delete struct with a dynamic array as a member'), Expect.Simple( 'deleteCnotArray', ['3', '5', '1', '2'], diff --git a/tests/behaviour/expectations/semantic.ts b/tests/behaviour/expectations/semantic.ts index 061d9b8fc..a4e8a8f46 100644 --- a/tests/behaviour/expectations/semantic.ts +++ b/tests/behaviour/expectations/semantic.ts @@ -292,7 +292,7 @@ export function encodeValue(tp: TypeNode, value: SolValue, inference: InferType) } else if (tp instanceof BuiltinStructType) { throw new NotSupportedYetError('Serialising BuiltinStructType not supported yet'); } else if (tp instanceof MappingType) { - throw new Error('Mappings cannot be serialised as external function paramenters'); + throw new Error('Mappings cannot be serialised as external function parameters'); } else if (tp instanceof UserDefinedType) { const definition = tp.definition; if (definition instanceof UserDefinedValueTypeDefinition) { diff --git a/tests/behaviour/expectations/utils.ts b/tests/behaviour/expectations/utils.ts index 9f2b9182d..213a0ac09 100644 --- a/tests/behaviour/expectations/utils.ts +++ b/tests/behaviour/expectations/utils.ts @@ -41,7 +41,7 @@ export function stringFlatten(val: Value[]): string[] { } /** - * Given a series of numbers it produces an array of it's bytes32 represenation + * Given a series of numbers it produces an array of it's bytes32 representation * where the first value is the total amount of bytes * e.g. (3, 2) -> [64, 0 ..., 3, 0 ..., 2] * @param val number(s) to get it's byte32 representation diff --git a/warplib/memory.cairo b/warplib/memory.cairo index adf1b688d..96db05b0c 100644 --- a/warplib/memory.cairo +++ b/warplib/memory.cairo @@ -309,7 +309,7 @@ func index_struct(loc: felt, index: felt) -> (indexLoc: felt) { // -----------------Helper functions----------------- -// Returns an exisiting pointer to a reference data type structure. If it does not exist, it will +// Returns an existing pointer to a reference data type structure. If it does not exist, it will // create a new pointer func wm_read_id{range_check_ptr: felt, warp_memory: DictAccess*}(loc: felt, size: Uint256) -> ( val: felt From 54b6f1e8e9761cbb8f693717c070df88d876b47b Mon Sep 17 00:00:00 2001 From: AlejandroLabourdette Date: Wed, 22 Mar 2023 08:49:12 -0400 Subject: [PATCH 18/28] create WarpInferType, override Literal and MemberAccess TypeOf --- src/ast/ast.ts | 4 ++-- src/utils/nodeTypeProcessing.ts | 28 +++++++++++++++++++++++++--- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/src/ast/ast.ts b/src/ast/ast.ts index 4ec945fab..a4eccdf4c 100644 --- a/src/ast/ast.ts +++ b/src/ast/ast.ts @@ -26,7 +26,7 @@ import { TranspileFailedError } from '../utils/errors'; import { Implicits } from '../utils/implicits'; import { createBlock } from '../utils/nodeTemplates'; import { createImport } from '../utils/importFuncGenerator'; -import { safeGetNodeType } from '../utils/nodeTypeProcessing'; +import { safeGetNodeType, WarpInferType } from '../utils/nodeTypeProcessing'; import { getContainingSourceUnit, isExternalCall } from '../utils/utils'; import { CairoFunctionDefinition, CairoImportFunctionDefinition } from './cairoNodes'; import { ParameterInfo } from '../export'; @@ -74,7 +74,7 @@ export class AST { 'All contexts should be the same, otherwise they are from seperate solc-typed-ast compiles and they will have no relationship to each other.', ); this.context = roots[0].requiredContext; - this.inference = new InferType(compilerVersion); + this.inference = new WarpInferType(compilerVersion); assert( this.context.locate(this.tempId) === undefined, `Attempted to create an AST with a context that already has ${this.tempId} registered`, diff --git a/src/utils/nodeTypeProcessing.ts b/src/utils/nodeTypeProcessing.ts index 395d14f86..6ec7f308e 100644 --- a/src/utils/nodeTypeProcessing.ts +++ b/src/utils/nodeTypeProcessing.ts @@ -19,6 +19,7 @@ import { IntType, Literal, // eslint-disable-line MappingType, + MemberAccess, PackedArrayType, PointerType, StringType, @@ -289,14 +290,35 @@ export function isStorageSpecificType( return false; } +export class WarpInferType extends InferType { + typeOfLiteral(node: Literal): TypeNode { + return getNodeType(node, this); + } + typeOfMemberAccess(node: MemberAccess): TypeNode { + // The way infertype compute the type of a member access is by looking the member name inside the base type + // (eg: if we had A.B.C it will look for C inside of whatever is A.B). + // + // Doing this approach if we have an access to a contract 'C.access' + // it will look for a function or property with name 'access' inside 'C'. If it match a function with that name it will + // compute its signature, encoding its parameters. + // In inheritanceInliner, more specificly constructorInheritance, we create a function for each constructor from parent contracts + // and call those generated functions inside the constructor. With this approach constructors become functions definitions and + // therefore their signatures will be computed, abi-encoding their arguments. This will lead to errors. To see an example that + // break check: tests/behaviour/contracts/abstractContracts/mappingInConstructor.sol + // + // If we look at warp generated functions (like the ones to treat dynamic arrays) they are lack of an ast meaning, therefore + // properties access like 'len' will fail + // + // Until those troubles are solved the best idea is to compute type using the typeString. + return getNodeType(node, this); + } +} + export function safeGetNodeType( node: Expression | VariableDeclaration, inference: InferType, ): TypeNode { getContainingSourceUnit(node); - if (node instanceof Literal) { - return getNodeType(node, inference); - } if (node instanceof CairoAssert) { return new TupleType([]); } From 80662e6b361e061a48742fe7487174e48e912c4d Mon Sep 17 00:00:00 2001 From: AlejandroLabourdette Date: Wed, 22 Mar 2023 09:13:52 -0400 Subject: [PATCH 19/28] try to compute member access type first using inferType --- src/utils/nodeTypeProcessing.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/utils/nodeTypeProcessing.ts b/src/utils/nodeTypeProcessing.ts index 6ec7f308e..1e67c8d90 100644 --- a/src/utils/nodeTypeProcessing.ts +++ b/src/utils/nodeTypeProcessing.ts @@ -291,9 +291,6 @@ export function isStorageSpecificType( } export class WarpInferType extends InferType { - typeOfLiteral(node: Literal): TypeNode { - return getNodeType(node, this); - } typeOfMemberAccess(node: MemberAccess): TypeNode { // The way infertype compute the type of a member access is by looking the member name inside the base type // (eg: if we had A.B.C it will look for C inside of whatever is A.B). @@ -310,7 +307,11 @@ export class WarpInferType extends InferType { // properties access like 'len' will fail // // Until those troubles are solved the best idea is to compute type using the typeString. - return getNodeType(node, this); + try { + return super.typeOfMemberAccess(node); + } catch { + return getNodeType(node, this); + } } } @@ -319,6 +320,9 @@ export function safeGetNodeType( inference: InferType, ): TypeNode { getContainingSourceUnit(node); + if (node instanceof Literal) { + return getNodeType(node, inference); + } if (node instanceof CairoAssert) { return new TupleType([]); } From bf062206c4651e695b9f4b034786ba55ff8972d9 Mon Sep 17 00:00:00 2001 From: AlejandroLabourdette Date: Fri, 24 Mar 2023 03:14:13 -0400 Subject: [PATCH 20/28] convert int literal to intType when needed --- src/utils/nodeTypeProcessing.ts | 10 ++++++++++ src/utils/utils.ts | 9 +++++++-- src/warplib/implementations/maths/exp.ts | 8 ++++---- src/warplib/implementations/maths/shl.ts | 8 ++++---- src/warplib/implementations/maths/shr.ts | 8 ++++---- src/warplib/implementations/maths/sub.ts | 4 ++-- src/warplib/utils.ts | 4 ++-- 7 files changed, 33 insertions(+), 18 deletions(-) diff --git a/src/utils/nodeTypeProcessing.ts b/src/utils/nodeTypeProcessing.ts index 1e67c8d90..ebe81da3a 100644 --- a/src/utils/nodeTypeProcessing.ts +++ b/src/utils/nodeTypeProcessing.ts @@ -16,6 +16,7 @@ import { FunctionLikeType, generalizeType, InferType, + IntLiteralType, IntType, Literal, // eslint-disable-line MappingType, @@ -169,6 +170,15 @@ export function intTypeForLiteral(typestring: string): IntType { } } +export function literalToValueType(literal: TypeNode) { + if (literal instanceof IntLiteralType) { + const intType = literal.smallestFittingType(); + assert(intType !== undefined); + return intType; + } + return literal; +} + export function isDynamicArray(type: TypeNode): boolean { return ( (type instanceof PointerType && isDynamicArray(type.to)) || diff --git a/src/utils/utils.ts b/src/utils/utils.ts index 92464e314..06c65cd7d 100644 --- a/src/utils/utils.ts +++ b/src/utils/utils.ts @@ -69,7 +69,12 @@ import { createBytesTypeName, createNumberLiteral, } from './nodeTemplates'; -import { isDynamicArray, isDynamicCallDataArray, safeGetNodeType } from './nodeTypeProcessing'; +import { + isDynamicArray, + isDynamicCallDataArray, + literalToValueType, + safeGetNodeType, +} from './nodeTypeProcessing'; import { Class } from './typeConstructs'; import { TranspilationOptions } from '../cli'; @@ -231,7 +236,7 @@ export function typeNameFromTypeNode(node: TypeNode, ast: AST): TypeName { } else if (node instanceof FixedBytesType) { result = new ElementaryTypeName(ast.reserveId(), '', node.pp(), node.pp()); } else if (node instanceof IntLiteralType) { - throw new TranspileFailedError(`Attempted to create typename for int literal`); + result = typeNameFromTypeNode(literalToValueType(node), ast); } else if (node instanceof IntType) { result = new ElementaryTypeName(ast.reserveId(), '', node.pp(), node.pp()); } else if (node instanceof PointerType) { diff --git a/src/warplib/implementations/maths/exp.ts b/src/warplib/implementations/maths/exp.ts index daed4d75d..e94bf7c8c 100644 --- a/src/warplib/implementations/maths/exp.ts +++ b/src/warplib/implementations/maths/exp.ts @@ -8,7 +8,7 @@ import { } from 'solc-typed-ast'; import { AST } from '../../../ast/ast'; import { printNode, printTypeNode } from '../../../utils/astPrinter'; -import { safeGetNodeType } from '../../../utils/nodeTypeProcessing'; +import { literalToValueType, safeGetNodeType } from '../../../utils/nodeTypeProcessing'; import { mapRange, typeNameFromTypeNode } from '../../../utils/utils'; import { forAllWidths, getIntOrFixedByteBitWidth, mask, WarplibFunctionInfo } from '../../utils'; @@ -164,9 +164,9 @@ function getNegativeOneShortcutCode(signed: boolean, lhsWidth: number, rhsWide: } export function functionaliseExp(node: BinaryOperation, unsafe: boolean, ast: AST) { - const lhsType = safeGetNodeType(node.vLeftExpression, ast.inference); - const rhsType = safeGetNodeType(node.vRightExpression, ast.inference); - const retType = safeGetNodeType(node, ast.inference); + const lhsType = literalToValueType(safeGetNodeType(node.vLeftExpression, ast.inference)); + const rhsType = literalToValueType(safeGetNodeType(node.vRightExpression, ast.inference)); + const retType = literalToValueType(safeGetNodeType(node, ast.inference)); assert( retType instanceof IntType, `${printNode(node)} has type ${printTypeNode(retType)}, which is not compatible with **`, diff --git a/src/warplib/implementations/maths/shl.ts b/src/warplib/implementations/maths/shl.ts index 9ee6f870a..849687442 100644 --- a/src/warplib/implementations/maths/shl.ts +++ b/src/warplib/implementations/maths/shl.ts @@ -9,7 +9,7 @@ import { } from 'solc-typed-ast'; import { AST } from '../../../ast/ast'; import { printNode, printTypeNode } from '../../../utils/astPrinter'; -import { safeGetNodeType } from '../../../utils/nodeTypeProcessing'; +import { literalToValueType, safeGetNodeType } from '../../../utils/nodeTypeProcessing'; import { typeNameFromTypeNode } from '../../../utils/utils'; import { forAllWidths, getIntOrFixedByteBitWidth, WarplibFunctionInfo } from '../../utils'; @@ -71,9 +71,9 @@ export function shl(): WarplibFunctionInfo { } export function functionaliseShl(node: BinaryOperation, ast: AST): void { - const lhsType = safeGetNodeType(node.vLeftExpression, ast.inference); - const rhsType = safeGetNodeType(node.vRightExpression, ast.inference); - const retType = safeGetNodeType(node, ast.inference); + const lhsType = literalToValueType(safeGetNodeType(node.vLeftExpression, ast.inference)); + const rhsType = literalToValueType(safeGetNodeType(node.vRightExpression, ast.inference)); + const retType = literalToValueType(safeGetNodeType(node, ast.inference)); assert( lhsType instanceof IntType || lhsType instanceof FixedBytesType, diff --git a/src/warplib/implementations/maths/shr.ts b/src/warplib/implementations/maths/shr.ts index a42152d4e..db119ee91 100644 --- a/src/warplib/implementations/maths/shr.ts +++ b/src/warplib/implementations/maths/shr.ts @@ -9,7 +9,7 @@ import { } from 'solc-typed-ast'; import { AST } from '../../../ast/ast'; import { printNode, printTypeNode } from '../../../utils/astPrinter'; -import { safeGetNodeType } from '../../../utils/nodeTypeProcessing'; +import { literalToValueType, safeGetNodeType } from '../../../utils/nodeTypeProcessing'; import { mapRange, typeNameFromTypeNode } from '../../../utils/utils'; import { forAllWidths, @@ -217,9 +217,9 @@ export function shr_signed(): WarplibFunctionInfo { } export function functionaliseShr(node: BinaryOperation, ast: AST): void { - const lhsType = safeGetNodeType(node.vLeftExpression, ast.inference); - const rhsType = safeGetNodeType(node.vRightExpression, ast.inference); - const retType = safeGetNodeType(node, ast.inference); + const lhsType = literalToValueType(safeGetNodeType(node.vLeftExpression, ast.inference)); + const rhsType = literalToValueType(safeGetNodeType(node.vRightExpression, ast.inference)); + const retType = literalToValueType(safeGetNodeType(node, ast.inference)); assert( lhsType instanceof IntType || lhsType instanceof FixedBytesType, diff --git a/src/warplib/implementations/maths/sub.ts b/src/warplib/implementations/maths/sub.ts index d62feb3cb..efe6a1e7a 100644 --- a/src/warplib/implementations/maths/sub.ts +++ b/src/warplib/implementations/maths/sub.ts @@ -2,7 +2,7 @@ import assert from 'assert'; import { BinaryOperation, IntType } from 'solc-typed-ast'; import { AST } from '../../../ast/ast'; import { printTypeNode } from '../../../utils/astPrinter'; -import { safeGetNodeType } from '../../../utils/nodeTypeProcessing'; +import { literalToValueType, safeGetNodeType } from '../../../utils/nodeTypeProcessing'; import { forAllWidths, bound, @@ -163,7 +163,7 @@ export function sub_signed_unsafe(): WarplibFunctionInfo { //func warp_sub256{range_check_ptr, bitwise_ptr : BitwiseBuiltin*}(lhs : Uint256, rhs : Uint256) -> (res : Uint256): export function functionaliseSub(node: BinaryOperation, unsafe: boolean, ast: AST): void { - const typeNode = safeGetNodeType(node, ast.inference); + const typeNode = literalToValueType(safeGetNodeType(node, ast.inference)); assert( typeNode instanceof IntType, `Expected IntType for subtraction, got ${printTypeNode(typeNode)}`, diff --git a/src/warplib/utils.ts b/src/warplib/utils.ts index 9cb9162ee..bf7b95851 100644 --- a/src/warplib/utils.ts +++ b/src/warplib/utils.ts @@ -14,7 +14,7 @@ import { import { AST } from '../ast/ast'; import { printNode, printTypeNode } from '../utils/astPrinter'; import { mapRange, typeNameFromTypeNode } from '../utils/utils'; -import { safeGetNodeType } from '../utils/nodeTypeProcessing'; +import { literalToValueType, safeGetNodeType } from '../utils/nodeTypeProcessing'; import path from 'path'; export type WarplibFunctionInfo = { @@ -80,7 +80,7 @@ export function IntxIntFunction( ) { const lhsType = typeNameFromTypeNode(safeGetNodeType(node.vLeftExpression, ast.inference), ast); const rhsType = typeNameFromTypeNode(safeGetNodeType(node.vRightExpression, ast.inference), ast); - const retType = safeGetNodeType(node, ast.inference); + const retType = literalToValueType(safeGetNodeType(node, ast.inference)); assert( retType instanceof IntType || retType instanceof FixedBytesType, `${printNode(node)} has type ${printTypeNode(retType)}, which is not compatible with ${name}`, From 9caa683951e96cf8bb3c183c7c46f71cb9a39a10 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 24 Mar 2023 09:28:51 -0400 Subject: [PATCH 21/28] Bump @sideway/formula from 3.0.0 to 3.0.1 in /docs (#990) Bumps [@sideway/formula](https://github.com/sideway/formula) from 3.0.0 to 3.0.1. - [Release notes](https://github.com/sideway/formula/releases) - [Commits](https://github.com/sideway/formula/compare/v3.0.0...v3.0.1) --- updated-dependencies: - dependency-name: "@sideway/formula" dependency-type: indirect ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- docs/yarn.lock | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/yarn.lock b/docs/yarn.lock index 3a7e8876f..fb2397c5d 100644 --- a/docs/yarn.lock +++ b/docs/yarn.lock @@ -1700,9 +1700,9 @@ "@hapi/hoek" "^9.0.0" "@sideway/formula@^3.0.0": - version "3.0.0" - resolved "https://registry.yarnpkg.com/@sideway/formula/-/formula-3.0.0.tgz#fe158aee32e6bd5de85044be615bc08478a0a13c" - integrity sha512-vHe7wZ4NOXVfkoRb8T5otiENVlT7a3IAiw7H5M2+GO+9CDgcVUUsX1zalAztCmwyOr2RUTGJdgB+ZvSVqmdHmg== + version "3.0.1" + resolved "https://registry.yarnpkg.com/@sideway/formula/-/formula-3.0.1.tgz#80fcbcbaf7ce031e0ef2dd29b1bfc7c3f583611f" + integrity sha512-/poHZJJVjx3L+zVD6g9KgHfYnb443oi7wLu/XKojDviHy6HOEOA6z1Trk5aR1dGcmPenJEgb2sK2I80LeS3MIg== "@sideway/pinpoint@^2.0.0": version "2.0.0" From 6d4c6f795c65f4f0967fc7053b03ecad3b271a54 Mon Sep 17 00:00:00 2001 From: AlejandroLabourdette Date: Mon, 27 Mar 2023 02:23:15 -0400 Subject: [PATCH 22/28] infertype computes literal type using typeString parser --- src/utils/nodeTypeProcessing.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/utils/nodeTypeProcessing.ts b/src/utils/nodeTypeProcessing.ts index ebe81da3a..6d4458159 100644 --- a/src/utils/nodeTypeProcessing.ts +++ b/src/utils/nodeTypeProcessing.ts @@ -323,6 +323,9 @@ export class WarpInferType extends InferType { return getNodeType(node, this); } } + typeOfLiteral(node: Literal): TypeNode { + return getNodeType(node, this); + } } export function safeGetNodeType( @@ -330,9 +333,6 @@ export function safeGetNodeType( inference: InferType, ): TypeNode { getContainingSourceUnit(node); - if (node instanceof Literal) { - return getNodeType(node, inference); - } if (node instanceof CairoAssert) { return new TupleType([]); } From d4f35caa263327dcdc52cf4b2afa696337f24b89 Mon Sep 17 00:00:00 2001 From: AlejandroLabourdette Date: Mon, 27 Mar 2023 02:29:34 -0400 Subject: [PATCH 23/28] refactor --- src/passes/bytesConverter.ts | 183 ------------------ src/passes/bytesConverter/index.ts | 21 ++ .../replaceIndexAccessBytesConverter.ts | 72 +++++++ .../updateTypeStringBytesConverter.ts | 67 +++++++ src/passes/bytesConverter/utils.ts | 49 +++++ 5 files changed, 209 insertions(+), 183 deletions(-) delete mode 100644 src/passes/bytesConverter.ts create mode 100644 src/passes/bytesConverter/index.ts create mode 100644 src/passes/bytesConverter/replaceIndexAccessBytesConverter.ts create mode 100644 src/passes/bytesConverter/updateTypeStringBytesConverter.ts create mode 100644 src/passes/bytesConverter/utils.ts diff --git a/src/passes/bytesConverter.ts b/src/passes/bytesConverter.ts deleted file mode 100644 index d235c0fd3..000000000 --- a/src/passes/bytesConverter.ts +++ /dev/null @@ -1,183 +0,0 @@ -import { - ArrayType, - ElementaryTypeName, - Expression, - FixedBytesType, - generalizeType, - IntType, - PointerType, - TupleType, - VariableDeclaration, - FunctionType, - MappingType, - TypeNameType, - TypeNode, - TypeName, - IndexAccess, - Literal, - BytesType, - StringType, - StringLiteralType, -} from 'solc-typed-ast'; -import { AST } from '../ast/ast'; -import { ASTMapper } from '../ast/mapper'; -import { createCallToFunction } from '../utils/functionGeneration'; -import { generateExpressionTypeString } from '../utils/getTypeString'; -import { typeNameFromTypeNode } from '../utils/utils'; -import { - createNumberLiteral, - createUint8TypeName, - createUint256TypeName, - createArrayTypeName, -} from '../utils/nodeTemplates'; -import { safeGetNodeType } from '../utils/nodeTypeProcessing'; - -/* Convert fixed-size byte arrays (e.g. bytes2, bytes8) to their equivalent unsigned integer. - This pass does not handle dynamically-sized bytes arrays (i.e. bytes). -*/ - -export class BytesConverter extends ASTMapper { - // Function to add passes that should have been run before this pass - addInitialPassPrerequisites(): void { - const passKeys: Set = new Set([]); - passKeys.forEach((key) => this.addPassPrerequisite(key)); - } - - visitExpression(node: Expression, ast: AST): void { - const typeNode = safeGetNodeType(node, ast.inference); - if (typeNode instanceof StringLiteralType) { - return; - } - node.typeString = generateExpressionTypeString(replaceBytesType(typeNode)); - this.commonVisit(node, ast); - } - - visitVariableDeclaration(node: VariableDeclaration, ast: AST): void { - const typeNode = replaceBytesType(safeGetNodeType(node, ast.inference)); - node.typeString = generateExpressionTypeString(typeNode); - this.commonVisit(node, ast); - } - - visitElementaryTypeName(node: ElementaryTypeName, ast: AST): void { - const typeNode = ast.inference.typeNameToTypeNode(node); - if (typeNode instanceof StringType || typeNode instanceof BytesType) { - ast.replaceNode(node, createArrayTypeName(createUint8TypeName(ast), ast)); - return; - } - const replacementTypeNode = replaceBytesType(typeNode); - if (typeNode.pp() !== replacementTypeNode.pp()) { - const typeString = replacementTypeNode.pp(); - node.typeString = typeString; - node.name = typeString; - } - this.commonVisit(node, ast); - } - - visitIndexAccess(node: IndexAccess, ast: AST): void { - if ( - !( - node.vIndexExpression && - generalizeType(safeGetNodeType(node.vBaseExpression, ast.inference))[0] instanceof - FixedBytesType - ) - ) { - this.visitExpression(node, ast); - return; - } - - const baseTypeName = typeNameFromTypeNode( - safeGetNodeType(node.vBaseExpression, ast.inference), - ast, - ); - - const width: string = baseTypeName.typeString.slice(5); - - const indexTypeName = - node.vIndexExpression instanceof Literal - ? createUint256TypeName(ast) - : typeNameFromTypeNode(safeGetNodeType(node.vIndexExpression, ast.inference), ast); - - const stubParams: [string, TypeName][] = [ - ['base', baseTypeName], - ['index', indexTypeName], - ]; - const callArgs = [node.vBaseExpression, node.vIndexExpression]; - if (baseTypeName.typeString !== 'bytes32') { - stubParams.push(['width', createUint8TypeName(ast)]); - callArgs.push(createNumberLiteral(width, ast, 'uint8')); - } - - const importedFunc = ast.registerImport( - node, - 'warplib.maths.bytes_access', - selectWarplibFunction(baseTypeName, indexTypeName), - stubParams, - [['res', createUint8TypeName(ast)]], - ); - - const call = createCallToFunction(importedFunc, callArgs, ast); - ast.replaceNode(node, call, node.parent); - const typeNode = replaceBytesType(safeGetNodeType(call, ast.inference)); - call.typeString = generateExpressionTypeString(typeNode); - this.commonVisit(call, ast); - } - - visitTypeName(node: TypeName, ast: AST): void { - const typeNode = safeGetNodeType(node, ast.inference); - const replacementTypeNode = replaceBytesType(typeNode); - if (typeNode.pp() !== replacementTypeNode.pp()) { - const typeString = replacementTypeNode.pp(); - node.typeString = typeString; - } - this.commonVisit(node, ast); - } -} - -function replaceBytesType(type: TypeNode): TypeNode { - if (type instanceof ArrayType) { - return new ArrayType(replaceBytesType(type.elementT), type.size, type.src); - } else if (type instanceof FixedBytesType) { - return new IntType(type.size * 8, false, type.src); - } else if (type instanceof FunctionType) { - return new FunctionType( - type.name, - type.parameters.map(replaceBytesType), - type.returns.map(replaceBytesType), - type.visibility, - type.mutability, - type.implicitFirstArg, - type.src, - ); - } else if (type instanceof MappingType) { - return new MappingType( - replaceBytesType(type.keyType), - replaceBytesType(type.valueType), - type.src, - ); - } else if (type instanceof PointerType) { - return new PointerType(replaceBytesType(type.to), type.location, type.kind, type.src); - } else if (type instanceof TupleType) { - return new TupleType(type.elements.map(replaceBytesType), type.src); - } else if (type instanceof TypeNameType) { - return new TypeNameType(replaceBytesType(type.type), type.src); - } else if (type instanceof BytesType) { - return new ArrayType(new IntType(8, false, type.src), undefined, type.src); - } else if (type instanceof StringType) { - return new ArrayType(new IntType(8, false, type.src), undefined, type.src); - } else { - return type; - } -} - -function selectWarplibFunction(baseTypeName: TypeName, indexTypeName: TypeName): string { - if (indexTypeName.typeString === 'uint256' && baseTypeName.typeString === 'bytes32') { - return 'byte256_at_index_uint256'; - } - if (indexTypeName.typeString === 'uint256') { - return 'byte_at_index_uint256'; - } - if (baseTypeName.typeString === 'bytes32') { - return 'byte256_at_index'; - } - return 'byte_at_index'; -} diff --git a/src/passes/bytesConverter/index.ts b/src/passes/bytesConverter/index.ts new file mode 100644 index 000000000..b46ca647d --- /dev/null +++ b/src/passes/bytesConverter/index.ts @@ -0,0 +1,21 @@ +import { AST } from '../../ast/ast'; +import { ASTMapper } from '../../ast/mapper'; +import { ReplaceIndexAccessBytesConverter } from './replaceIndexAccessBytesConverter'; +import { UpdateTypeStringBytesConverter } from './UpdateTypeStringBytesConverter'; + +/* Convert fixed-size byte arrays (e.g. bytes2, bytes8) to their equivalent unsigned integer. + This pass does not handle dynamically-sized bytes arrays (i.e. bytes). +*/ +export class BytesConverter extends ASTMapper { + // Function to add passes that should have been run before this pass + addInitialPassPrerequisites(): void { + const passKeys: Set = new Set([]); + passKeys.forEach((key) => this.addPassPrerequisite(key)); + } + + static map(ast: AST): AST { + ast = ReplaceIndexAccessBytesConverter.map(ast); + ast = UpdateTypeStringBytesConverter.map(ast); + return ast; + } +} diff --git a/src/passes/bytesConverter/replaceIndexAccessBytesConverter.ts b/src/passes/bytesConverter/replaceIndexAccessBytesConverter.ts new file mode 100644 index 000000000..2a958d80a --- /dev/null +++ b/src/passes/bytesConverter/replaceIndexAccessBytesConverter.ts @@ -0,0 +1,72 @@ +import { FixedBytesType, generalizeType, TypeName, IndexAccess, Literal } from 'solc-typed-ast'; +import { AST } from '../../ast/ast'; +import { ASTMapper } from '../../ast/mapper'; +import { createCallToFunction } from '../../utils/functionGeneration'; +import { generateExpressionTypeString } from '../../utils/getTypeString'; +import { typeNameFromTypeNode } from '../../utils/utils'; +import { + createNumberLiteral, + createUint8TypeName, + createUint256TypeName, +} from '../../utils/nodeTemplates'; +import { safeGetNodeType } from '../../utils/nodeTypeProcessing'; +import { replaceBytesType } from './utils'; + +export class ReplaceIndexAccessBytesConverter extends ASTMapper { + visitIndexAccess(node: IndexAccess, ast: AST): void { + const a = generalizeType(safeGetNodeType(node.vBaseExpression, ast.inference))[0]; + if (!(node.vIndexExpression && a instanceof FixedBytesType)) { + this.visitExpression(node, ast); + return; + } + + const baseTypeName = typeNameFromTypeNode( + safeGetNodeType(node.vBaseExpression, ast.inference), + ast, + ); + + const width: string = baseTypeName.typeString.slice(5); + + const indexTypeName = + node.vIndexExpression instanceof Literal + ? createUint256TypeName(ast) + : typeNameFromTypeNode(safeGetNodeType(node.vIndexExpression, ast.inference), ast); + + const stubParams: [string, TypeName][] = [ + ['base', baseTypeName], + ['index', indexTypeName], + ]; + const callArgs = [node.vBaseExpression, node.vIndexExpression]; + if (baseTypeName.typeString !== 'bytes32') { + stubParams.push(['width', createUint8TypeName(ast)]); + callArgs.push(createNumberLiteral(width, ast, 'uint8')); + } + + const importedFunc = ast.registerImport( + node, + 'warplib.maths.bytes_access', + selectWarplibFunction(baseTypeName, indexTypeName), + stubParams, + [['res', createUint8TypeName(ast)]], + ); + + const call = createCallToFunction(importedFunc, callArgs, ast); + ast.replaceNode(node, call, node.parent); + const typeNode = replaceBytesType(safeGetNodeType(call, ast.inference)); + call.typeString = generateExpressionTypeString(typeNode); + this.commonVisit(call, ast); + } +} + +function selectWarplibFunction(baseTypeName: TypeName, indexTypeName: TypeName): string { + if (indexTypeName.typeString === 'uint256' && baseTypeName.typeString === 'bytes32') { + return 'byte256_at_index_uint256'; + } + if (indexTypeName.typeString === 'uint256') { + return 'byte_at_index_uint256'; + } + if (baseTypeName.typeString === 'bytes32') { + return 'byte256_at_index'; + } + return 'byte_at_index'; +} diff --git a/src/passes/bytesConverter/updateTypeStringBytesConverter.ts b/src/passes/bytesConverter/updateTypeStringBytesConverter.ts new file mode 100644 index 000000000..d6e59a74b --- /dev/null +++ b/src/passes/bytesConverter/updateTypeStringBytesConverter.ts @@ -0,0 +1,67 @@ +import { + ElementaryTypeName, + Expression, + VariableDeclaration, + TypeName, + BytesType, + StringType, + StringLiteralType, +} from 'solc-typed-ast'; +import { AST } from '../../ast/ast'; +import { ASTMapper } from '../../ast/mapper'; +import { generateExpressionTypeString } from '../../utils/getTypeString'; +import { createUint8TypeName, createArrayTypeName } from '../../utils/nodeTemplates'; +import { safeGetNodeType } from '../../utils/nodeTypeProcessing'; +import { replaceBytesType } from './utils'; + +/* Convert fixed-size byte arrays (e.g. bytes2, bytes8) to their equivalent unsigned integer. + This pass does not handle dynamically-sized bytes arrays (i.e. bytes). +*/ + +export class UpdateTypeStringBytesConverter extends ASTMapper { + // Function to add passes that should have been run before this pass + addInitialPassPrerequisites(): void { + const passKeys: Set = new Set([]); + passKeys.forEach((key) => this.addPassPrerequisite(key)); + } + + visitExpression(node: Expression, ast: AST): void { + const typeNode = safeGetNodeType(node, ast.inference); + if (typeNode instanceof StringLiteralType) { + return; + } + node.typeString = generateExpressionTypeString(replaceBytesType(typeNode)); + this.commonVisit(node, ast); + } + + visitVariableDeclaration(node: VariableDeclaration, ast: AST): void { + const typeNode = replaceBytesType(safeGetNodeType(node, ast.inference)); + node.typeString = generateExpressionTypeString(typeNode); + this.commonVisit(node, ast); + } + + visitElementaryTypeName(node: ElementaryTypeName, ast: AST): void { + const typeNode = ast.inference.typeNameToTypeNode(node); + if (typeNode instanceof StringType || typeNode instanceof BytesType) { + ast.replaceNode(node, createArrayTypeName(createUint8TypeName(ast), ast)); + return; + } + const replacementTypeNode = replaceBytesType(typeNode); + if (typeNode.pp() !== replacementTypeNode.pp()) { + const typeString = replacementTypeNode.pp(); + node.typeString = typeString; + node.name = typeString; + } + this.commonVisit(node, ast); + } + + visitTypeName(node: TypeName, ast: AST): void { + const typeNode = safeGetNodeType(node, ast.inference); + const replacementTypeNode = replaceBytesType(typeNode); + if (typeNode.pp() !== replacementTypeNode.pp()) { + const typeString = replacementTypeNode.pp(); + node.typeString = typeString; + } + this.commonVisit(node, ast); + } +} diff --git a/src/passes/bytesConverter/utils.ts b/src/passes/bytesConverter/utils.ts new file mode 100644 index 000000000..46432948b --- /dev/null +++ b/src/passes/bytesConverter/utils.ts @@ -0,0 +1,49 @@ +import { + ArrayType, + FixedBytesType, + IntType, + PointerType, + TupleType, + FunctionType, + MappingType, + TypeNameType, + TypeNode, + BytesType, + StringType, +} from 'solc-typed-ast'; + +export function replaceBytesType(type: TypeNode): TypeNode { + if (type instanceof ArrayType) { + return new ArrayType(replaceBytesType(type.elementT), type.size, type.src); + } else if (type instanceof FixedBytesType) { + return new IntType(type.size * 8, false, type.src); + } else if (type instanceof FunctionType) { + return new FunctionType( + type.name, + type.parameters.map(replaceBytesType), + type.returns.map(replaceBytesType), + type.visibility, + type.mutability, + type.implicitFirstArg, + type.src, + ); + } else if (type instanceof MappingType) { + return new MappingType( + replaceBytesType(type.keyType), + replaceBytesType(type.valueType), + type.src, + ); + } else if (type instanceof PointerType) { + return new PointerType(replaceBytesType(type.to), type.location, type.kind, type.src); + } else if (type instanceof TupleType) { + return new TupleType(type.elements.map(replaceBytesType), type.src); + } else if (type instanceof TypeNameType) { + return new TypeNameType(replaceBytesType(type.type), type.src); + } else if (type instanceof BytesType) { + return new ArrayType(new IntType(8, false, type.src), undefined, type.src); + } else if (type instanceof StringType) { + return new ArrayType(new IntType(8, false, type.src), undefined, type.src); + } else { + return type; + } +} From 653cb005d57cbfdfbfe806a96225a127c9f9ae61 Mon Sep 17 00:00:00 2001 From: AlejandroLabourdette Date: Mon, 27 Mar 2023 02:39:23 -0400 Subject: [PATCH 24/28] case typo in import --- src/passes/bytesConverter/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/passes/bytesConverter/index.ts b/src/passes/bytesConverter/index.ts index b46ca647d..f43920bf6 100644 --- a/src/passes/bytesConverter/index.ts +++ b/src/passes/bytesConverter/index.ts @@ -1,7 +1,7 @@ import { AST } from '../../ast/ast'; import { ASTMapper } from '../../ast/mapper'; import { ReplaceIndexAccessBytesConverter } from './replaceIndexAccessBytesConverter'; -import { UpdateTypeStringBytesConverter } from './UpdateTypeStringBytesConverter'; +import { UpdateTypeStringBytesConverter } from './updateTypeStringBytesConverter'; /* Convert fixed-size byte arrays (e.g. bytes2, bytes8) to their equivalent unsigned integer. This pass does not handle dynamically-sized bytes arrays (i.e. bytes). From adce8276069cfa41d244c597c93b4068dc816727 Mon Sep 17 00:00:00 2001 From: AlejandroLabourdette Date: Mon, 27 Mar 2023 03:37:32 -0400 Subject: [PATCH 25/28] generalize type on return var init --- src/passes/returnVariableInitializer.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/passes/returnVariableInitializer.ts b/src/passes/returnVariableInitializer.ts index 2305759d1..4258e24ba 100644 --- a/src/passes/returnVariableInitializer.ts +++ b/src/passes/returnVariableInitializer.ts @@ -1,4 +1,4 @@ -import { FunctionDefinition, VariableDeclarationStatement } from 'solc-typed-ast'; +import { FunctionDefinition, generalizeType, VariableDeclarationStatement } from 'solc-typed-ast'; import { AST } from '../ast/ast'; import { ASTMapper } from '../ast/mapper'; import { cloneASTNode } from '../utils/cloning'; @@ -27,7 +27,7 @@ export class ReturnVariableInitializer extends ASTMapper { '', [newDecl.id], [newDecl], - getDefaultValue(safeGetNodeType(decl, ast.inference), newDecl, ast), + getDefaultValue(generalizeType(safeGetNodeType(decl, ast.inference))[0], newDecl, ast), ); identifiers.forEach((identifier) => { identifier.referencedDeclaration = newDecl.id; From 4a278429cfd2a4f60bbf6de97456214f966fe3e8 Mon Sep 17 00:00:00 2001 From: AlejandroLabourdette Date: Mon, 27 Mar 2023 03:59:46 -0400 Subject: [PATCH 26/28] generalize specialized types --- src/cairoUtilFuncGen/calldata/calldataToMemory.ts | 2 +- src/cairoUtilFuncGen/memory/memoryToStorage.ts | 2 +- src/cairoUtilFuncGen/storage/copyToStorage.ts | 4 +++- src/cairoUtilFuncGen/utils/encodeToFelt.ts | 2 +- 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/cairoUtilFuncGen/calldata/calldataToMemory.ts b/src/cairoUtilFuncGen/calldata/calldataToMemory.ts index 1b32fdbd9..3fad4e752 100644 --- a/src/cairoUtilFuncGen/calldata/calldataToMemory.ts +++ b/src/cairoUtilFuncGen/calldata/calldataToMemory.ts @@ -196,7 +196,7 @@ export class CallDataToMemoryGen extends StringIndexedFuncGen { const [copyCode, funcCalls] = structDef.vMembers.reduce( ([copyCode, funcCalls, offset], decl) => { - const type = safeGetNodeType(decl, this.ast.inference); + const type = generalizeType(safeGetNodeType(decl, this.ast.inference))[0]; if (isReferenceType(type)) { const recursiveFunc = this.getOrCreateFuncDef(type); diff --git a/src/cairoUtilFuncGen/memory/memoryToStorage.ts b/src/cairoUtilFuncGen/memory/memoryToStorage.ts index 3291904ef..59bb53994 100644 --- a/src/cairoUtilFuncGen/memory/memoryToStorage.ts +++ b/src/cairoUtilFuncGen/memory/memoryToStorage.ts @@ -108,7 +108,7 @@ export class MemoryToStorageGen extends StringIndexedFuncGen { const funcName = `wm_to_storage_struct_${def.name}`; const [copyInstructions, funcsCalled] = this.generateTupleCopyInstructions( - def.vMembers.map((decl) => safeGetNodeType(decl, this.ast.inference)), + def.vMembers.map((decl) => generalizeType(safeGetNodeType(decl, this.ast.inference))[0]), ); return { name: funcName, diff --git a/src/cairoUtilFuncGen/storage/copyToStorage.ts b/src/cairoUtilFuncGen/storage/copyToStorage.ts index d059c2ba4..eb7e25ce3 100644 --- a/src/cairoUtilFuncGen/storage/copyToStorage.ts +++ b/src/cairoUtilFuncGen/storage/copyToStorage.ts @@ -121,7 +121,9 @@ export class StorageToStorageGen extends StringIndexedFuncGen { } private createStructCopyFunction(def: StructDefinition): GeneratedFunctionInfo { - const members = def.vMembers.map((decl) => safeGetNodeType(decl, this.ast.inference)); + const members = def.vMembers.map( + (decl) => generalizeType(safeGetNodeType(decl, this.ast.inference))[0], + ); const [copyCode, funcsCalled] = members.reduce( ([copyCode, funcsCalled, offset], memberType) => { const width = CairoType.fromSol( diff --git a/src/cairoUtilFuncGen/utils/encodeToFelt.ts b/src/cairoUtilFuncGen/utils/encodeToFelt.ts index 5bab9a666..7d21693a9 100644 --- a/src/cairoUtilFuncGen/utils/encodeToFelt.ts +++ b/src/cairoUtilFuncGen/utils/encodeToFelt.ts @@ -311,7 +311,7 @@ export class EncodeAsFelt extends StringIndexedFuncGenWithAuxiliar { const [encodeCode, encodeCalls] = type.definition.vMembers.reduce( ([encodeCode, encodeCalls], varDecl, index) => { - const varType = safeGetNodeType(varDecl, this.ast.inference); + const varType = generalizeType(safeGetNodeType(varDecl, this.ast.inference))[0]; const [memberEncodeCode, memberEncodeCalls] = this.generateEncodeCode( varType, `member_${index}`, From 4bae6b1f959cdf9a7d07d01bd79945b89d8edede Mon Sep 17 00:00:00 2001 From: AlejandroLabourdette Date: Mon, 27 Mar 2023 04:21:51 -0400 Subject: [PATCH 27/28] include eventType in generate expression typeString --- src/utils/getTypeString.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/utils/getTypeString.ts b/src/utils/getTypeString.ts index a955df65e..e705ccf39 100644 --- a/src/utils/getTypeString.ts +++ b/src/utils/getTypeString.ts @@ -12,6 +12,7 @@ import { ContractKind, DataLocation, EnumDefinition, + EventType, Expression, FixedBytesType, FunctionDefinition, @@ -258,6 +259,10 @@ export function generateExpressionTypeString(type: TypeNode): string { return `function ${ type.name !== undefined ? type.name : '' }(${argStr})${mutStr}${visStr}${retStr}`; + } else if (type instanceof EventType) { + const mapper = (node: TypeNode) => generateExpressionTypeString(node); + const argStr = type.parameters.map(mapper).join(','); + return `function ${type.name !== undefined ? type.name : ''}(${argStr})`; } else if (type instanceof ArrayType) { return `${generateExpressionTypeString(type.elementT)}[${ type.size !== undefined ? type.size : '' From efbf41864afbaf5f15a2c55de2b32b94d0ef15fb Mon Sep 17 00:00:00 2001 From: AlejandroLabourdette Date: Mon, 29 May 2023 00:20:55 -0400 Subject: [PATCH 28/28] remove bytes converter --- src/passes/bytesConverter/index.ts | 21 ------ .../replaceIndexAccessBytesConverter.ts | 72 ------------------- .../updateTypeStringBytesConverter.ts | 67 ----------------- src/passes/bytesConverter/utils.ts | 49 ------------- src/passes/export.ts | 1 - src/passes/index.ts | 1 - src/transpiler.ts | 2 - 7 files changed, 213 deletions(-) delete mode 100644 src/passes/bytesConverter/index.ts delete mode 100644 src/passes/bytesConverter/replaceIndexAccessBytesConverter.ts delete mode 100644 src/passes/bytesConverter/updateTypeStringBytesConverter.ts delete mode 100644 src/passes/bytesConverter/utils.ts diff --git a/src/passes/bytesConverter/index.ts b/src/passes/bytesConverter/index.ts deleted file mode 100644 index f43920bf6..000000000 --- a/src/passes/bytesConverter/index.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { AST } from '../../ast/ast'; -import { ASTMapper } from '../../ast/mapper'; -import { ReplaceIndexAccessBytesConverter } from './replaceIndexAccessBytesConverter'; -import { UpdateTypeStringBytesConverter } from './updateTypeStringBytesConverter'; - -/* Convert fixed-size byte arrays (e.g. bytes2, bytes8) to their equivalent unsigned integer. - This pass does not handle dynamically-sized bytes arrays (i.e. bytes). -*/ -export class BytesConverter extends ASTMapper { - // Function to add passes that should have been run before this pass - addInitialPassPrerequisites(): void { - const passKeys: Set = new Set([]); - passKeys.forEach((key) => this.addPassPrerequisite(key)); - } - - static map(ast: AST): AST { - ast = ReplaceIndexAccessBytesConverter.map(ast); - ast = UpdateTypeStringBytesConverter.map(ast); - return ast; - } -} diff --git a/src/passes/bytesConverter/replaceIndexAccessBytesConverter.ts b/src/passes/bytesConverter/replaceIndexAccessBytesConverter.ts deleted file mode 100644 index 2a958d80a..000000000 --- a/src/passes/bytesConverter/replaceIndexAccessBytesConverter.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { FixedBytesType, generalizeType, TypeName, IndexAccess, Literal } from 'solc-typed-ast'; -import { AST } from '../../ast/ast'; -import { ASTMapper } from '../../ast/mapper'; -import { createCallToFunction } from '../../utils/functionGeneration'; -import { generateExpressionTypeString } from '../../utils/getTypeString'; -import { typeNameFromTypeNode } from '../../utils/utils'; -import { - createNumberLiteral, - createUint8TypeName, - createUint256TypeName, -} from '../../utils/nodeTemplates'; -import { safeGetNodeType } from '../../utils/nodeTypeProcessing'; -import { replaceBytesType } from './utils'; - -export class ReplaceIndexAccessBytesConverter extends ASTMapper { - visitIndexAccess(node: IndexAccess, ast: AST): void { - const a = generalizeType(safeGetNodeType(node.vBaseExpression, ast.inference))[0]; - if (!(node.vIndexExpression && a instanceof FixedBytesType)) { - this.visitExpression(node, ast); - return; - } - - const baseTypeName = typeNameFromTypeNode( - safeGetNodeType(node.vBaseExpression, ast.inference), - ast, - ); - - const width: string = baseTypeName.typeString.slice(5); - - const indexTypeName = - node.vIndexExpression instanceof Literal - ? createUint256TypeName(ast) - : typeNameFromTypeNode(safeGetNodeType(node.vIndexExpression, ast.inference), ast); - - const stubParams: [string, TypeName][] = [ - ['base', baseTypeName], - ['index', indexTypeName], - ]; - const callArgs = [node.vBaseExpression, node.vIndexExpression]; - if (baseTypeName.typeString !== 'bytes32') { - stubParams.push(['width', createUint8TypeName(ast)]); - callArgs.push(createNumberLiteral(width, ast, 'uint8')); - } - - const importedFunc = ast.registerImport( - node, - 'warplib.maths.bytes_access', - selectWarplibFunction(baseTypeName, indexTypeName), - stubParams, - [['res', createUint8TypeName(ast)]], - ); - - const call = createCallToFunction(importedFunc, callArgs, ast); - ast.replaceNode(node, call, node.parent); - const typeNode = replaceBytesType(safeGetNodeType(call, ast.inference)); - call.typeString = generateExpressionTypeString(typeNode); - this.commonVisit(call, ast); - } -} - -function selectWarplibFunction(baseTypeName: TypeName, indexTypeName: TypeName): string { - if (indexTypeName.typeString === 'uint256' && baseTypeName.typeString === 'bytes32') { - return 'byte256_at_index_uint256'; - } - if (indexTypeName.typeString === 'uint256') { - return 'byte_at_index_uint256'; - } - if (baseTypeName.typeString === 'bytes32') { - return 'byte256_at_index'; - } - return 'byte_at_index'; -} diff --git a/src/passes/bytesConverter/updateTypeStringBytesConverter.ts b/src/passes/bytesConverter/updateTypeStringBytesConverter.ts deleted file mode 100644 index d6e59a74b..000000000 --- a/src/passes/bytesConverter/updateTypeStringBytesConverter.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { - ElementaryTypeName, - Expression, - VariableDeclaration, - TypeName, - BytesType, - StringType, - StringLiteralType, -} from 'solc-typed-ast'; -import { AST } from '../../ast/ast'; -import { ASTMapper } from '../../ast/mapper'; -import { generateExpressionTypeString } from '../../utils/getTypeString'; -import { createUint8TypeName, createArrayTypeName } from '../../utils/nodeTemplates'; -import { safeGetNodeType } from '../../utils/nodeTypeProcessing'; -import { replaceBytesType } from './utils'; - -/* Convert fixed-size byte arrays (e.g. bytes2, bytes8) to their equivalent unsigned integer. - This pass does not handle dynamically-sized bytes arrays (i.e. bytes). -*/ - -export class UpdateTypeStringBytesConverter extends ASTMapper { - // Function to add passes that should have been run before this pass - addInitialPassPrerequisites(): void { - const passKeys: Set = new Set([]); - passKeys.forEach((key) => this.addPassPrerequisite(key)); - } - - visitExpression(node: Expression, ast: AST): void { - const typeNode = safeGetNodeType(node, ast.inference); - if (typeNode instanceof StringLiteralType) { - return; - } - node.typeString = generateExpressionTypeString(replaceBytesType(typeNode)); - this.commonVisit(node, ast); - } - - visitVariableDeclaration(node: VariableDeclaration, ast: AST): void { - const typeNode = replaceBytesType(safeGetNodeType(node, ast.inference)); - node.typeString = generateExpressionTypeString(typeNode); - this.commonVisit(node, ast); - } - - visitElementaryTypeName(node: ElementaryTypeName, ast: AST): void { - const typeNode = ast.inference.typeNameToTypeNode(node); - if (typeNode instanceof StringType || typeNode instanceof BytesType) { - ast.replaceNode(node, createArrayTypeName(createUint8TypeName(ast), ast)); - return; - } - const replacementTypeNode = replaceBytesType(typeNode); - if (typeNode.pp() !== replacementTypeNode.pp()) { - const typeString = replacementTypeNode.pp(); - node.typeString = typeString; - node.name = typeString; - } - this.commonVisit(node, ast); - } - - visitTypeName(node: TypeName, ast: AST): void { - const typeNode = safeGetNodeType(node, ast.inference); - const replacementTypeNode = replaceBytesType(typeNode); - if (typeNode.pp() !== replacementTypeNode.pp()) { - const typeString = replacementTypeNode.pp(); - node.typeString = typeString; - } - this.commonVisit(node, ast); - } -} diff --git a/src/passes/bytesConverter/utils.ts b/src/passes/bytesConverter/utils.ts deleted file mode 100644 index 46432948b..000000000 --- a/src/passes/bytesConverter/utils.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { - ArrayType, - FixedBytesType, - IntType, - PointerType, - TupleType, - FunctionType, - MappingType, - TypeNameType, - TypeNode, - BytesType, - StringType, -} from 'solc-typed-ast'; - -export function replaceBytesType(type: TypeNode): TypeNode { - if (type instanceof ArrayType) { - return new ArrayType(replaceBytesType(type.elementT), type.size, type.src); - } else if (type instanceof FixedBytesType) { - return new IntType(type.size * 8, false, type.src); - } else if (type instanceof FunctionType) { - return new FunctionType( - type.name, - type.parameters.map(replaceBytesType), - type.returns.map(replaceBytesType), - type.visibility, - type.mutability, - type.implicitFirstArg, - type.src, - ); - } else if (type instanceof MappingType) { - return new MappingType( - replaceBytesType(type.keyType), - replaceBytesType(type.valueType), - type.src, - ); - } else if (type instanceof PointerType) { - return new PointerType(replaceBytesType(type.to), type.location, type.kind, type.src); - } else if (type instanceof TupleType) { - return new TupleType(type.elements.map(replaceBytesType), type.src); - } else if (type instanceof TypeNameType) { - return new TypeNameType(replaceBytesType(type.type), type.src); - } else if (type instanceof BytesType) { - return new ArrayType(new IntType(8, false, type.src), undefined, type.src); - } else if (type instanceof StringType) { - return new ArrayType(new IntType(8, false, type.src), undefined, type.src); - } else { - return type; - } -} diff --git a/src/passes/export.ts b/src/passes/export.ts index 4a8e8782b..a28f6eb04 100644 --- a/src/passes/export.ts +++ b/src/passes/export.ts @@ -2,7 +2,6 @@ export * from './abiBuiltins'; export * from './annotateImplicits'; export * from './argBoundChecker'; export * from './builtinHandler/export'; -export * from './bytesConverter'; export * from './cairoStubProcessor'; export * from './cairoUtilImporter'; export * from './conditionalSplitter/export'; diff --git a/src/passes/index.ts b/src/passes/index.ts index 71f6708e0..581e3e3ff 100644 --- a/src/passes/index.ts +++ b/src/passes/index.ts @@ -3,7 +3,6 @@ export * from './annotateImplicits'; export * from './argBoundChecker'; export * from './builtinHandler'; export * from './builtinHandler/require'; -export * from './bytesConverter'; export * from './cairoStubProcessor'; export * from './cairoUtilImporter'; export * from './conditionalSplitter/conditionalSplitter'; diff --git a/src/transpiler.ts b/src/transpiler.ts index 19e39ca5c..503f6c3ba 100644 --- a/src/transpiler.ts +++ b/src/transpiler.ts @@ -8,7 +8,6 @@ import { AnnotateImplicits, ArgBoundChecker, BuiltinHandler, - BytesConverter, CairoStubProcessor, CairoUtilImporter, ConditionalSplitter, @@ -141,7 +140,6 @@ function applyPasses( ['Abc', ArgBoundChecker], ['Ec', EnumConverter], ['B', BuiltinHandler], - ['Bc', BytesConverter], ['Us', UnreachableStatementPruner], ['Fp', FunctionPruner], ['E', ExpressionSplitter],