ucglib/ast/rewrite.rs
1// Copyright 2020 Jeremy Wall
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14use std::path::PathBuf;
15
16use crate::ast::walk::Visitor;
17use crate::ast::Expression;
18
19pub struct Rewriter {
20 base: PathBuf,
21}
22
23impl Rewriter {
24 pub fn new<P: Into<PathBuf>>(base: P) -> Self {
25 Self { base: base.into() }
26 }
27}
28
29impl Visitor for Rewriter {
30 fn visit_expression(&mut self, expr: &mut Expression) {
31 // Rewrite all paths except for stdlib paths to absolute.
32 let main_separator = format!("{}", std::path::MAIN_SEPARATOR);
33 if let Expression::Include(ref mut def) = expr {
34 let path = PathBuf::from(def.path.fragment.as_ref());
35 if path.is_relative() {
36 def.path.fragment = self.base.join(path).to_string_lossy().to_string().into();
37 }
38 }
39 if let Expression::Import(ref mut def) = expr {
40 let path = PathBuf::from(
41 &def.path
42 .fragment
43 .replace("/", &main_separator)
44 .replace("\\", &main_separator),
45 );
46 // std/ paths are special and do not get made into absolute paths.
47 if path.starts_with(format!("std{}", main_separator)) {
48 return;
49 }
50 if path.is_relative() {
51 def.path.fragment = self.base.join(path).to_string_lossy().to_string().into();
52 }
53 }
54 }
55}