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 48 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
48 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
7700326
Merge branch 'master' into format-rnode
LaurenzV Dec 6, 2024
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
3 changes: 1 addition & 2 deletions src/main/scala/viper/silver/ast/pretty/PrettyPrinter.scala
Original file line number Diff line number Diff line change
Expand Up @@ -346,8 +346,7 @@ trait FastPrettyPrinterBase extends PrettyPrintPrimitives {
def parens (d : Cont) : Cont =
char ('(') <> d <> char (')')




def brackets (d : Cont) : Cont =
char ('[') <> d <> char (']')

Expand Down
2 changes: 1 addition & 1 deletion src/main/scala/viper/silver/cfg/CfgTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ object CfgTest {
}

private def parse(input: String, file: Path): Option[PProgram] = {
val program = new FastParser().parse(input, file)
val program = new FastParser().parse(input, file, false)
if (program.errors.forall(_.isInstanceOf[ParseWarning])) Some(program)
else None
}
Expand Down
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, expandMacros, Some(plugins), _loader)
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
41 changes: 35 additions & 6 deletions src/main/scala/viper/silver/parser/FastParser.scala
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,26 @@ object FastParserCompanion {
).pos
}

def space[$: P]: P[PSpace] = P(("\t" | " ") map (_ => PSpace()))

def newline[$: P]: P[PNewLine] = P((StringIn("\n\r") | "\n" | "\r") map (_ => PNewLine()))

def lineComment[$: P]: P[PComment] = {
P(("//" ~~ CharsWhile(_ != '\n').?.!).map { content =>
PComment(content, false)
})
}

def blockComment[$: P]: P[PComment] = P(("/*" ~~ (!StringIn("*/") ~~ AnyChar).repX.! ~~ "*/").map { content =>
PComment(content, true)
})

def comment[$: P]: P[PComment] = lineComment | blockComment

def trivia[$: P]: P[Seq[PTrivia]] = {
P((space | newline | comment).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 +187,7 @@ object FastParserCompanion {
}

class FastParser {
def parse(s: String, f: Path, plugins: Option[SilverPluginManager] = None, loader: FileLoader = DiskLoader) = {
def parse(s: String, f: Path, expandMacros: Boolean, plugins: Option[SilverPluginManager] = None, loader: FileLoader = DiskLoader) = {
// 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 +199,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 @@ -859,7 +883,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 +910,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,9 +994,14 @@ 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
var startIndex = 0
var members: Seq[PMember] = Nil
Expand Down Expand Up @@ -1018,7 +1047,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