Skip to content

Commit deb15c9

Browse files
authored
Merge pull request #39 from samtkit/validate-pattern-constraint
Validate regex patterns
2 parents 5fffccc + 342e950 commit deb15c9

4 files changed

Lines changed: 40 additions & 3 deletions

File tree

semantic/src/main/kotlin/tools/samt/semantic/ConstraintBuilder.kt

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -98,9 +98,18 @@ internal class ConstraintBuilder(private val controller: DiagnosticController) {
9898
private fun createPattern(
9999
expression: ExpressionNode,
100100
argument: StringNode,
101-
): ResolvedTypeReference.Constraint.Pattern {
102-
// We will validate the pattern here in the future
103-
return ResolvedTypeReference.Constraint.Pattern(expression, argument.value)
101+
): ResolvedTypeReference.Constraint.Pattern? {
102+
val pattern = argument.value
103+
104+
try { Regex(pattern) } catch (e: Exception) {
105+
argument.reportError(controller) {
106+
message("Invalid regex pattern: '${e.message}'")
107+
highlight(argument.location)
108+
}
109+
return null
110+
}
111+
112+
return ResolvedTypeReference.Constraint.Pattern(expression, pattern)
104113
}
105114

106115
private fun createValue(

semantic/src/test/kotlin/tools/samt/semantic/SemanticModelTest.kt

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,24 @@ class SemanticModelTest {
334334
)
335335
}
336336

337+
@Test
338+
fun `pattern must be valid`() {
339+
val source = """
340+
package complex
341+
342+
record Foo {
343+
name: String (pattern("fo/+++!hi"))
344+
}
345+
""".trimIndent()
346+
parseAndCheck(
347+
source to listOf(
348+
"Error: Invalid regex pattern: 'Dangling meta character '+' near index 5${System.lineSeparator()}" +
349+
"fo/+++!hi${System.lineSeparator()}" +
350+
" ^'"
351+
)
352+
)
353+
}
354+
337355
@Test
338356
fun `cannot use non-existent constraints`() {
339357
val source = """
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
package debug.test
2+
3+
record Foo {
4+
name: String ("++")
5+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
source: ./
2+
3+
generators:
4+
- name: kotlin-ktor-consumer
5+
output: ./out

0 commit comments

Comments
 (0)