Skip to content

Commit

Permalink
Support abstract classes via interface "extends" (#19)
Browse files Browse the repository at this point in the history
  • Loading branch information
jasongwartz authored Mar 14, 2024
1 parent 394b4c6 commit 2df0122
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 8 deletions.
8 changes: 8 additions & 0 deletions codegen/snippet-tests/input/04-withClass.pkl
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,11 @@ class MyCustomClass {
}

value: MyCustomClass

abstract class MyAbstractClass {
someString: String
}

class MyConcreteClass extends MyAbstractClass {
anotherString: String
}
10 changes: 10 additions & 0 deletions codegen/snippet-tests/output/04_with_class.pkl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,16 @@ export interface MyCustomClass {
y: number
}

// Ref: Pkl class `04-withClass.MyAbstractClass`.
export interface MyAbstractClass {
someString: string
}

// Ref: Pkl class `04-withClass.MyConcreteClass`.
export interface MyConcreteClass extends MyAbstractClass {
anotherString: string
}

// LoadFromPath loads the pkl module at the given path and evaluates it into a N04WithClass
export const loadFromPath = async (path: string): Promise<N04WithClass> => {
const evaluator = await pklTypescript.newEvaluator(pklTypescript.PreconfiguredOptions);
Expand Down
10 changes: 2 additions & 8 deletions codegen/src/internal/ClassGen.pkl
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,6 @@ function getFields(
mappings: List<TypescriptMapping>
): Map<String, TypescriptInterfaceProperty> =
let (isSuperOpen: Boolean = clazz.superclass.modifiers.contains("open"))
// add the properties of the superclass as fields unless it is an open class (because its struct gets embedded),
// or the class does not inherit.
let (superFields: Map<String, TypescriptInterfaceProperty> =
if (doesNotInherit(clazz) || isSuperOpen) Map()
else getFields(clazz.superclass!!, mappings)
)
let (superProperties = getAllProperties(clazz.superclass))
clazz.properties
.filter((propName, prop: reflect.Property) ->
Expand Down Expand Up @@ -111,7 +105,7 @@ function getFields(
name = utils.toTypescriptPropertyName(prop)
property = prop
}
) + superFields.mapValues((_, field) -> (field) { isInherited = true })
)

local function doesNotInherit(clazz: reflect.Class?) =
clazz.superclass == null || clazz.superclass.reflectee == Module || clazz.superclass.reflectee == Typed
Expand All @@ -124,7 +118,7 @@ local interface: String = new Listing {
(
"export interface \(classInfo.interface.name) " +
(if (superClass != null)
superClass.type.render(classInfo.typescriptPackage)
"extends " + superClass.type.render(classInfo.typescriptModule) + " "
else "")
+ "{"
)
Expand Down

0 comments on commit 2df0122

Please sign in to comment.