Skip to content

Commit

Permalink
Merge pull request #39 from samtkit/validate-pattern-constraint
Browse files Browse the repository at this point in the history
Validate regex patterns
  • Loading branch information
KCreate authored Jun 1, 2023
2 parents 5fffccc + 342e950 commit deb15c9
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 3 deletions.
15 changes: 12 additions & 3 deletions semantic/src/main/kotlin/tools/samt/semantic/ConstraintBuilder.kt
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,18 @@ internal class ConstraintBuilder(private val controller: DiagnosticController) {
private fun createPattern(
expression: ExpressionNode,
argument: StringNode,
): ResolvedTypeReference.Constraint.Pattern {
// We will validate the pattern here in the future
return ResolvedTypeReference.Constraint.Pattern(expression, argument.value)
): ResolvedTypeReference.Constraint.Pattern? {
val pattern = argument.value

try { Regex(pattern) } catch (e: Exception) {
argument.reportError(controller) {
message("Invalid regex pattern: '${e.message}'")
highlight(argument.location)
}
return null
}

return ResolvedTypeReference.Constraint.Pattern(expression, pattern)
}

private fun createValue(
Expand Down
18 changes: 18 additions & 0 deletions semantic/src/test/kotlin/tools/samt/semantic/SemanticModelTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,24 @@ class SemanticModelTest {
)
}

@Test
fun `pattern must be valid`() {
val source = """
package complex
record Foo {
name: String (pattern("fo/+++!hi"))
}
""".trimIndent()
parseAndCheck(
source to listOf(
"Error: Invalid regex pattern: 'Dangling meta character '+' near index 5${System.lineSeparator()}" +
"fo/+++!hi${System.lineSeparator()}" +
" ^'"
)
)
}

@Test
fun `cannot use non-existent constraints`() {
val source = """
Expand Down
5 changes: 5 additions & 0 deletions specification/examples/debug/debug.samt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package debug.test

record Foo {
name: String ("++")
}
5 changes: 5 additions & 0 deletions specification/examples/debug/samt.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
source: ./

generators:
- name: kotlin-ktor-consumer
output: ./out

0 comments on commit deb15c9

Please sign in to comment.