Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add formatter for the parse AST #820

Open
wants to merge 71 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 67 commits
Commits
Show all changes
71 commits
Select commit Hold shift + click to select a range
c69c9f5
First version of reformatter
LaurenzV Nov 16, 2024
18fa38e
Don't translate macros when reformatting
LaurenzV Nov 16, 2024
e3555bf
Refine expressions further
LaurenzV Nov 17, 2024
b2e8690
Update comment
LaurenzV Nov 17, 2024
6631424
Fix spacing
LaurenzV Nov 17, 2024
dfd7624
Change PForAll
LaurenzV Nov 18, 2024
abd6f49
more
LaurenzV Nov 18, 2024
b187fee
Tweak formatting of let and if statements
LaurenzV Nov 19, 2024
b90d0a6
First version of better trivia fetching
LaurenzV Nov 19, 2024
d7cd1a8
More broken now but still more progress
LaurenzV Nov 19, 2024
31b2d4e
Make reformatter context implicit
LaurenzV Nov 19, 2024
8d49529
Remove unused method
LaurenzV Nov 19, 2024
7e9dc9c
roll back to looking back for trivia
LaurenzV Nov 19, 2024
7c4c42a
Fix issue with missing indent after comment
LaurenzV Nov 20, 2024
96b6e97
Everything works as initially
LaurenzV Nov 20, 2024
e41dba2
Simplify code a bit
LaurenzV Nov 20, 2024
52627f3
next attempt
LaurenzV Nov 20, 2024
0c69493
Good progress towards better formatting!
LaurenzV Nov 20, 2024
d6ff157
Fix spacing in pre and post conditions
LaurenzV Nov 20, 2024
66d9326
Improve showBody method
LaurenzV Nov 21, 2024
10544dd
more
LaurenzV Nov 21, 2024
9e513c5
Create ReformatterPrettyPrinterBase
LaurenzV Nov 21, 2024
34b806f
More progress
LaurenzV Nov 22, 2024
4289ead
more progress towards new reformatter
LaurenzV Nov 22, 2024
f6a85f1
First seeminly working prototype
LaurenzV Nov 22, 2024
c2b3033
First working version, more or less back to where we started
LaurenzV Nov 22, 2024
761a9fe
Add short circuit
LaurenzV Nov 22, 2024
ced300e
Add hack for decreases keyword
LaurenzV Nov 22, 2024
e86b33a
Only reformat on leaf nodes
LaurenzV Nov 24, 2024
3db11ed
Fix trailing whitespaces
LaurenzV Nov 24, 2024
41683c1
Fix whitespace bug
LaurenzV Nov 24, 2024
edc2e71
Add a couple of tests for reformatting
LaurenzV Nov 25, 2024
63184b7
Remove POther
LaurenzV Nov 27, 2024
22e5cde
Add a test case for not working snippets
LaurenzV Nov 27, 2024
2789dc7
Add some license headers
LaurenzV Nov 27, 2024
a252425
Revert some unnecessary changes
LaurenzV Nov 27, 2024
b878493
Remove trailing whitespaces
LaurenzV Nov 27, 2024
490ccef
Remove parseResult variable
LaurenzV Nov 27, 2024
b38fcbc
Whitespaces and other small changes
LaurenzV Nov 27, 2024
b11b00d
Rearrange some imports
LaurenzV Nov 27, 2024
dbef794
Rename trivia to PTrivia
LaurenzV Nov 27, 2024
b77509a
Remove LeftLineIndent
LaurenzV Nov 27, 2024
cbfc105
Readd newlines
LaurenzV Nov 27, 2024
dd071e5
Add some comments and improve code formatting
LaurenzV Nov 27, 2024
04da717
Add another case for showAny
LaurenzV Nov 28, 2024
27d001c
Fix whitespaces and imports
LaurenzV Nov 28, 2024
1784b23
Add brackets to method calls
LaurenzV Nov 28, 2024
fd2938a
Fix some whitespace issues and similar
LaurenzV Nov 28, 2024
7700326
Merge branch 'master' into format-rnode
LaurenzV Dec 6, 2024
dfc656b
Merge remote-tracking branch 'mine/format-rnode' into format-rnode
LaurenzV Feb 10, 2025
2cea48a
Move tests from viperserver to silver
LaurenzV Feb 10, 2025
d808906
Merge branch 'master' into format-rnode
LaurenzV Feb 10, 2025
8bdba66
Avoid arbitrary whitespace changes
LaurenzV Feb 13, 2025
5c2eed8
Fix whitespaces in PProgram constructors
LaurenzV Feb 13, 2025
a3c4643
Make expandMacros the last argument and assign true by default
LaurenzV Feb 13, 2025
a6c7d39
Avoid another arbitrary whitespace change
LaurenzV Feb 13, 2025
1b5809b
Fix compilation
LaurenzV Feb 13, 2025
fe6a44c
Deduplicate comment and whitespace parsing
LaurenzV Feb 13, 2025
b2fcdde
Reduce the number of imports
LaurenzV Feb 13, 2025
d28ab8b
Fix compiler warnings
LaurenzV Feb 13, 2025
c0a3374
Improve whitespace handling again
LaurenzV Feb 14, 2025
04e9552
Deduplicate other whitespace, too
LaurenzV Feb 14, 2025
6035628
Fix wrong expandMacros
LaurenzV Feb 14, 2025
ef466ec
Undo newline
LaurenzV Feb 14, 2025
d4b29ee
Merge branch 'master' into format-rnode
LaurenzV Feb 14, 2025
ecbb283
Reduce the number of `reformat` and `reformatExp` implementations
LaurenzV Feb 14, 2025
8e239b5
Remove one more reformat override
LaurenzV Feb 14, 2025
034696e
More improvements
LaurenzV Feb 26, 2025
2ad28a0
Fix issue with empty assignments
LaurenzV Mar 1, 2025
8a32a03
Fix inhale exhale exp
LaurenzV Mar 1, 2025
063279a
Add manual override for package wand
LaurenzV Mar 1, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions src/main/scala/viper/silver/frontend/ReformatterAstProvider.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright (c) 2011-2024 ETH Zurich.

package viper.silver.frontend
import viper.silver.parser.PProgram
import viper.silver.reporter.Reporter
import viper.silver.verifier.{Failure, Success, VerificationResult}

class ReformatterAstProvider(override val reporter: Reporter) extends ViperAstProvider(reporter) {
override val phases: Seq[Phase] = Seq(Parsing)

override def doParsing(input: String): Result[PProgram] = parsingInner(input, false)

override def result: VerificationResult = {
if (_errors.isEmpty) {
require(state >= DefaultStates.Parsing)
Success
}
else {
Failure(_errors)
}
}
}
6 changes: 4 additions & 2 deletions src/main/scala/viper/silver/frontend/SilFrontend.scala
Original file line number Diff line number Diff line change
Expand Up @@ -310,11 +310,11 @@ trait SilFrontend extends DefaultFrontend {
_config = configureVerifier(args)
}

override def doParsing(input: String): Result[PProgram] = {
def parsingInner(input: String, expandMacros: Boolean): Result[PProgram] = {
val file = _inputFile.get
plugins.beforeParse(input, isImported = false) match {
case Some(inputPlugin) =>
val result = fp.parse(inputPlugin, file, Some(plugins), _loader)
val result = fp.parse(inputPlugin, file, Some(plugins), _loader, expandMacros)
if (result.errors.forall(p => p.isInstanceOf[ParseWarning])) {
reporter report WarningsDuringParsing(result.errors)
Succ({
Expand All @@ -327,6 +327,8 @@ trait SilFrontend extends DefaultFrontend {
}
}

override def doParsing(input: String): Result[PProgram] = parsingInner(input, true)

override def doSemanticAnalysis(input: PProgram): Result[PProgram] = {
plugins.beforeResolve(input) match {
case Some(inputPlugin) =>
Expand Down
62 changes: 52 additions & 10 deletions src/main/scala/viper/silver/parser/FastParser.scala
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,26 @@ object FastParserCompanion {
val whitespaceWithoutNewlineOrComments = {
import NoWhitespace._
implicit ctx: ParsingRun[_] =>
NoTrace((" " | "\t").rep)
NoTrace(space.rep)
}

def blockComment[$: P] = {
import NoWhitespace._
"/*" ~ (!StringIn("*/") ~ AnyChar).rep ~ "*/"
}

def lineComment[$: P] = {
import NoWhitespace._
"//" ~ CharsWhile(_ != '\n').? ~ ("\n" | End)
}

def space[$: P] = " " | "\t"
def newline[$: P] = StringIn("\r\n") | "\n" | "\r"

implicit val whitespace = {
import NoWhitespace._
implicit ctx: ParsingRun[_] =>
NoTrace((("/*" ~ (!StringIn("*/") ~ AnyChar).rep ~ "*/") | ("//" ~ CharsWhile(_ != '\n').? ~ ("\n" | End)) | " " | "\t" | "\n" | "\r").rep)
NoTrace((blockComment | lineComment | space | newline).rep)
}

def identStarts[$: P] = CharIn("A-Z", "a-z", "$_")
Expand Down Expand Up @@ -104,6 +117,27 @@ object FastParserCompanion {
).pos
}

/* These special parser methods are only used in the reformatter
to parse and interpret the whitespaces and comments between two AST nodes.
*/
def pSpace[$: P]: P[PSpace] = P(space map (_ => PSpace()))

def pNewline[$: P]: P[PNewLine] = P(newline map (_ => PNewLine()))

def pLineComment[$: P]: P[PComment] = P(lineComment.!.map { content =>
PComment(content)
})

def pBlockComment[$: P]: P[PComment] = P(blockComment.!.map { content =>
PComment(content)
})

def pComment[$: P]: P[PComment] = pLineComment | pBlockComment

def pTrivia[$: P]: P[Seq[PTrivia]] = {
P((pSpace | pNewline | pComment).repX)
}

/**
* A parser which matches leading whitespaces. See `LeadingWhitespace.lw` for more info. Can only be operated on in
* restricted ways (e.g. `?`, `rep`, `|` or `map`), requiring that it is eventually appended to a normal parser (of type `P[V]`).
Expand Down Expand Up @@ -167,7 +201,7 @@ object FastParserCompanion {
}

class FastParser {
def parse(s: String, f: Path, plugins: Option[SilverPluginManager] = None, loader: FileLoader = DiskLoader) = {
def parse(s: String, f: Path, plugins: Option[SilverPluginManager] = None, loader: FileLoader = DiskLoader, expandMacros: Boolean = true) = {
// Strategy to handle imports
// Idea: Import every import reference and merge imported methods, functions, imports, .. into current program
// iterate until no new imports are present.
Expand All @@ -179,7 +213,11 @@ class FastParser {
val file = f.toAbsolutePath().normalize()
val data = ParserData(plugins, loader, mutable.HashSet(file))
val program = RecParser(file, data, false).parses(s)
MacroExpander.expandDefines(program)
if (expandMacros) {
MacroExpander.expandDefines(program)
} else {
program
}
}

case class ParserData(plugins: Option[SilverPluginManager], loader: FileLoader, local: mutable.HashSet[Path], std: mutable.HashSet[Path] = mutable.HashSet.empty)
Expand Down Expand Up @@ -312,13 +350,13 @@ class FastParser {
//////////////////////////

import fastparse._
import FastParserCompanion.{ExtendedParsing, identContinues, identStarts, LeadingWhitespace, Pos, PositionParsing, reservedKw, reservedSym}
import FastParserCompanion.{ExtendedParsing, identContinues, identStarts, LeadingWhitespace, Pos, PositionParsing, reservedKw, reservedSym, blockComment, lineComment, newline, space}


implicit val whitespace = {
import NoWhitespace._
implicit ctx: ParsingRun[_] =>
NoTrace((("/*" ~ (!StringIn("*/") ~ AnyChar).rep ~ "*/") | ("//" ~ CharsWhile(_ != '\n').? ~ ("\n" | End)) | " " | "\t" | "\n" | "\r").rep)
NoTrace((blockComment | lineComment | space | newline).rep)
}

implicit val lineCol: LineCol = new LineCol(this)
Expand Down Expand Up @@ -859,7 +897,7 @@ class FastParser {
P(programMember.rep map (members => {
val warnings = _warnings
_warnings = Seq()
PProgram(Nil, members)(_, warnings)
PProgram(Nil, members)(_, warnings, Nil, "")
})).pos

def preambleImport[$: P]: P[PKw.Import => PAnnotationsPosition => PImport] = P(
Expand All @@ -886,7 +924,7 @@ class FastParser {
val axioms1 = members collect { case m: PAxiom1 => m }
val funcs = funcs1 map (f => (PDomainFunction(f.annotations, f.unique, f.function, f.idndef, f.args, f.c, f.typ, f.interpretation)(f.pos), f.s))
val axioms = axioms1 map (a => (PAxiom(a.annotations, a.axiom, a.idndef, a.exp)(a.pos), a.s))
val allMembers = block.update(PDomainMembers(PDelimited(funcs)(NoPosition, NoPosition), PDelimited(axioms)(NoPosition, NoPosition))(block.pos))
val allMembers = block.update(PDomainMembers(PDelimited(funcs)(NoPosition, NoPosition), PDelimited(axioms)(NoPosition, NoPosition))(block.pos, block.inner))
k => ap: PAnnotationsPosition => PDomain(
ap.annotations,
k,
Expand Down Expand Up @@ -970,7 +1008,11 @@ class FastParser {

// Assume entire file is correct and try parsing it quickly
fastparse.parse(s, entireProgram(_)) match {
case Parsed.Success(value, _) => return value
case Parsed.Success(value, _) => {
value.offsets = _line_offset;
value.rawProgram = s;
return value;
}
case _: Parsed.Failure =>
}
// There was a parsing error, parse member by member to get all errors
Expand Down Expand Up @@ -1018,7 +1060,7 @@ class FastParser {
val warnings = _warnings
_warnings = Nil
val pos = (FilePosition(lineCol.getPos(0)), FilePosition(lineCol.getPos(res.get.index)))
PProgram(Nil, members)(pos, errors ++ warnings)
PProgram(Nil, members)(pos, errors ++ warnings, Nil, "");
}

object ParserExtension extends ParserPluginTemplate {
Expand Down
4 changes: 2 additions & 2 deletions src/main/scala/viper/silver/parser/MacroExpander.scala
Original file line number Diff line number Diff line change
Expand Up @@ -156,9 +156,9 @@ object MacroExpander {
pos._1
}
}
return PProgram(newImported, program.members)(program.pos, program.localErrors ++ reports :+ ParseError(msg, location))
return PProgram(newImported, program.members)(program.pos, program.localErrors ++ reports :+ ParseError(msg, location), program.offsets, program.rawProgram)
}
PProgram(newImported, newMembers)(program.pos, program.localErrors ++ reports)
PProgram(newImported, newMembers)(program.pos, program.localErrors ++ reports, program.offsets, program.rawProgram)
}

doExpandDefinesAll(p, reports)
Expand Down
Loading
Loading